pip*_*ips 4 java swing input jframe invokeandwait
我需要一些简单的java应用程序的帮助,它使用两个jframe来获取一些输入参数.这是我的代码草图:
//second jframe, called when the button OK of the first frame is clicked
public class NewParamJFrame extends JFrame{
...
}
//first jframe
public class StartingJFrame extends JFrame{
private static NewParamJFrame newPFrame = null;
private JTextField gnFilePath;
private JButton btnOK;
public StartingJFrame(){
//..
initComponents();
}
private void initComponents(){
btnOK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
EventQueue.invokeAndWait(new Runnable(){
public void run() {
try {
newPFrame = new NewParamJFrame();
newPFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
catch(InvocationTargetException e2) {}
catch(InterruptedException e1){}
dispose();
}
}
public String getText(){
return gnFilePath.getText();
}
}
public class Main {
private static StartingJFrame begin = null;
public static void main(String[] args) {
try{
EventQueue.invokeAndWait(new Runnable(){
public void run() {
try {
begin = new StartingJFrame();
begin.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
catch(InvocationTargetException e) {}
catch(InterruptedException e1){}
String s= begin.getText();
//...use s ...
}
}
Run Code Online (Sandbox Code Playgroud)
对getText()的调用会导致NullPointerException.我希望主类等到帧关闭但我不知道该怎么做.我第一次使用秋千.
我希望主类等到帧关闭但我不知道该怎么做.我第一次使用秋千.
如果我正确理解您的问题,您需要StartingJFrame
等待直到NewParamJFrame
关闭然后继续执行.如果是这种情况,则不会发生因为JFrame
不支持模态.但是JDialog
,所以你可以只有一个JFrame
并在JDialog
其父元素中执行参数请求JFrame
.
另请参阅此主题:使用多个JFrame,好/坏练习?
在任何情况下,您可能都会遇到一个新问题:JFrame
如果用户在没有输入任何参数的情况下关闭/取消对话框应该怎么做?怎么会JFrame
知道对话中刚刚发生了什么?在这个答案中描述了一种方法.您将看到示例是关于登录对话框,但问题与此类似:如何通过对话框通知其父框架进程如何进行?
在不修改代码流的情况下等待关闭的最简单方法是使用 modal JDialog
。因此,您必须更改您的StartingJFrame
类以使其成为JDialog
而不是的子类JFrame
,并将以下内容添加到其构造函数的开头:
super((Window)null);
setModal(true);
Run Code Online (Sandbox Code Playgroud)
然后实例setVisible(true);
上的调用StartingJFrame
将等到对话框关闭,因此invokeAndWait
调用也将等待。
归档时间: |
|
查看次数: |
15777 次 |
最近记录: |