可能这是一个非常基本的问题,但这是MWE。我想在我的Swing应用程序启动时启动一些基本的设置活动(对话框等),例如,这可以是数据库连接信息,以便代码可以跨机器移植,等等,然后才启动实际的应用程序。下面的示例显示了这种情况:它询问什么是“ 2 + 2”,并且在提交答案时启动另一个JFrame
。
如何使启动主要活动的“ Launcher”活动消失?
此前发布的MWE,我试图有一个CardLayout
这样的发射活动是“面孔”,这被通过实际活动所取代的一个(例如,使用CardLayout
的first
和last
方法),但也有与布局不尊重的问题我的GridBagLayout
设置(如果放在自己的设置中效果很好JFrame
,但这是另一回事了)。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Launcher extends JFrame {
private static class MainActivity extends JFrame {
MainActivity() {
this.getContentPane().add(new JLabel("Welcome to main activity"));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
JTextArea textArea;
JButton button;
Launcher() {
textArea= new JTextArea("(2+2) mod 2= ?");
button= new JButton("submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String ans= textArea.getText();
if ( ans.equals("0") ) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame= new MainActivity();
frame.pack();
frame.setVisible(true);
}
});
}
}
});
this.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();
c.gridx= 0;
c.gridy= 0;
this.getContentPane().add(textArea,c);
c.gridy= 1;
this.getContentPane().add(button,c);
}
public static void main( String ... args ) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame= new Launcher();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
更改:
frame.setVisible(true);
至:
frame.setVisible(true);
Launcher.this.setVisible(false); // set the current window invisible!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句