直到调整窗口大小,GUI元素才会显示 [英] GUI elements not showing until resize of window
问题描述
我一直在尝试用Java制作GUI,而不是一直使用静态",而是遇到了"SwingUtilities.invokeLater()"方法.我设法进行了所有设置,但是当要运行该应用程序时,在我调整窗口大小之前,JPanel上什么也没有出现.有解决办法吗?还是我做错了?
I have been experimenting with making GUIs in java as opposed to just using "static" all the time and come across the "SwingUtilities.invokeLater()" method. I manage to get everything setup but when it comes to run the application, nothing appears on the JPanel until I resize the window. Is there a fix for this or am I doing it wrong?
这里是我的代码:
public class main extends JPanel implements ActionListener{
public JLabel userLabel;
public JLabel passLabel;
public JTextField userField;
public JTextField passField;
public JButton login;
public JButton closeLogin;
public JButton help;
public main(){
userLabel = new JLabel("Username: ");
passLabel = new JLabel("Password: ");
userField = new JTextField(16);
passField = new JTextField(16);
login = new JButton("Login");
login.setActionCommand("login");
login.setMnemonic(KeyEvent.VK_L);
closeLogin = new JButton("Close");
closeLogin.setActionCommand("closeLogin");
closeLogin.setMnemonic(KeyEvent.VK_E);
help = new JButton("Help");
help.setActionCommand("helpLogin");
help.setMnemonic(KeyEvent.VK_H);
login.addActionListener(this);
closeLogin.addActionListener(this);
help.addActionListener(this);
add(userLabel);
add(userField);
add(passLabel);
add(passField);
add(login);
add(help);
add(closeLogin);
}
public void actionPerformed(ActionEvent e){
}
public static void initComponents(){
JFrame loginFrame = new JFrame("Encrypted Chat - Login");
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main loginPanel = new main();
loginPanel.setLayout(new FlowLayout());
loginFrame.setSize(300, 125);
loginFrame.setResizable(false);
loginFrame.setVisible(true);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
initComponents();
}
});
}
}
我知道密码JTextField是一个JPasswordField ..所以请忽略它:P
I know the password JTextField is meant to be a JPasswordField.. so ignore it :P
推荐答案
您永远不会将内容添加到JFrame.您需要进行的最少更改:
You never add your content to the JFrame. The minimal set of changes you need:
public static void main(String args[]){
final main main = new main();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
initComponents(main);
}
});
}
然后修改 initComponents
以采用 main
对象:
public static void initComponents(main main){
JFrame loginFrame = new JFrame("Encrypted Chat - Login");
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main loginPanel = new main();
loginPanel.setLayout(new FlowLayout());
loginFrame.setSize(300, 125);
loginFrame.setResizable(false);
loginFrame.setVisible(true);
loginFrame.add(main); // <----- this line is added
}
这篇关于直到调整窗口大小,GUI元素才会显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!