为什么我用java swing包 写了一个窗口,里面的组件只有在我改变窗口大小的时候才能显示

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class loginframe {

public static void main(String[] args ){
loginframe login = new loginframe();
login.go();
}

private static void go(){
JFrame frame = new JFrame("login");
frame.setSize(600,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

panel.setLayout(new GridBagLayout());

GridBagConstraints c= new GridBagConstraints();

JLabel username = new JLabel("username");
JLabel password = new JLabel("password");

JTextArea username_input = new JTextArea();
JTextArea password_input = new JTextArea();

username_input.setSize(20, 1);
password_input.setSize(20,1);

JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
JButton register = new JButton("Register");

ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

}
});

cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

}
});

register.setEnabled(false);

c.gridx =1;
c.gridy =1;
c.weighty =1 ;
// c.fill= GridBagConstraints.BOTH;
panel.add(username,c);

c.gridx = 2;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(username_input,c);
c.fill =GridBagConstraints.NONE;

c.gridx=1;
c.gridy=2;
c.gridwidth=1;
panel.add(password,c);
c.gridx=2;
c.gridwidth=2;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(password_input,c);
c.fill =GridBagConstraints.NONE;

c.gridx=1;
c.gridy=4;
c.gridwidth=1;
c.gridheight=2;
c.weighty=2;
c.weightx = 1;
panel.add(ok,c);

c.gridx=3;
panel.add(cancel,c);

c.gridx=5;
panel.add(register,c);

// panel.setVisible(true);

frame.getContentPane().add(panel);

}

}

我想知道这是为什么,并且 这样的问题怎么解决, 答的好的 我会追加悬赏

frame.setVisible(true); 这句写在前面,显示窗体后,再添加控件需要刷新窗体才能显示,改变窗体大小会自动刷新窗体,所以显示了

把这句frame.setVisible(true);放在frame.getContentPane().add(panel);这句后面就可以了追问

恩 按照你这么做 组件显示出来了,但是为什么我之前也按照这样的顺序完成这样的操作的时候 没有出现这个情况,就比如在这个 只在panel上添加一个JButton然后放到Frame上?

追答

可以把之前的代码给我看看吗

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-06
在初始化后,调用一下doLayout()试试追问

我刚才尝试了下,没用,这个方法应该不适合这种情况

相似回答