java特有的GUI问题
出于某种尴尬的原因,每当我将所需的帧设置为actionPerformed()内部可见(true)时,它就会打印出帧,带有标题,但没有我以前选择的组件和颜色
但是,当在当前帧的顶部将可见性设置为true时(无需按下按钮),效果良好
这是我正在使用的框架:
但一旦我将actionPerformed内的visibility设置为true,就会打印此内容:
我已经在actionPerformed()中将另一个框架(主客户端框架)设置为true,并且工作正常。这是我第一次遇到这个问题,所以我真的不知道是什么原因造成的
我还假设,这可能是因为在执行操作期间,客户端必须连接到特定的服务器详细信息,但同样,在第一个帧被实例化后,帧对象就被实例化了,所以应该可以
这是我的actionPerformed(),很抱歉代码太乱:
JButton connectButton = new JButton("Connect");
connectButton.setBackground(SystemColor.activeCaption);
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//If any of the first three fields are empty, turn them red
if(serverField.getText().equalsIgnoreCase("")){
lblSever.setForeground(new Color(240, 128, 128));
}
if(channelField.getText().equalsIgnoreCase("")){
lblChannel.setForeground(new Color(240, 128, 128));
}
if(nicknameField.getText().equalsIgnoreCase("")){
lblNickname.setForeground(new Color(240, 128, 128));
}
//Set Waiting Connection frame to true
wc.setVisible(true);
//None of the first three fields are empty
if(!serverField.getText().equalsIgnoreCase("")
&& !channelField.getText().equalsIgnoreCase("")
&& !nicknameField.getText().equalsIgnoreCase("")){
//Set current frame visibility to false
setVisible(false);
//Set connection details
Main.bot.setServer(serverField.getText());
Main.bot.setChannel(channelField.getText());
Main.bot.setNickname(nicknameField.getText());
Main.bot.setPassword(formattedTextField.getText());
//Connect to server and channel
try{
Main.bot.connect(serverField.getText());
Main.bot.changeNick(nicknameField.getText());
Main.bot.joinChannel(channelField.getText());
}catch(Exception e){ //Catch all errors, if invalid server is thrown, close Waiting Connection frame
InvalidServer error = new InvalidServer();
e.printStackTrace();
wc.setVisible(false);
wc.dispose();
error.setVisible(true);
}
setVisible(false);
//Custom Timer class
Timer runTime = new Timer();
while(runTime.getTimeElapsed() < 5000){
//To-Do
}
wc.setVisible(false);
//Instantiate next frame
MainFrame mainFrame = new MainFrame();
mainFrame.setVisible(true);
//Kill current frame
dispose();
}
}
});
# 1 楼答案
一些要点:
添加所有组件后,最后调用
frame.setVisible(true)
对于任何延迟,使用最适合swing应用程序的Swing Timer
阅读更多How to Use Swing Timers
使用SwingUtilities.invokeLater()或EventQueue.invokeLater()确保EDT已正确初始化
阅读更多
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
Should we use EventQueue.invokeLater for any GUI update in a Java desktop application?
阅读更多The Use of Multiple JFrames, Good/Bad Practice?