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

importjava.awt.GridBagConstraints;importjava.awt.GridBagLayout;importjava.awt.event.A... 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);

}

}

我想知道这是为什么,并且 这样的问题怎么解决, 答的好的 我会追加悬赏
展开
 我来答
查俉此人
2013-06-06 · 超过12用户采纳过TA的回答
知道答主
回答量:22
采纳率:0%
帮助的人:25.9万
展开全部
frame.setVisible(true); 这句写在前面,显示窗体后,再添加控件需要刷新窗体才能显示,改变窗体大小会自动刷新窗体,所以显示了

把这句frame.setVisible(true);放在frame.getContentPane().add(panel);这句后面就可以了
追问
恩 按照你这么做 组件显示出来了,但是为什么我之前也按照这样的顺序完成这样的操作的时候 没有出现这个情况,就比如在这个 只在panel上添加一个JButton然后放到Frame上?
追答
可以把之前的代码给我看看吗
匿名用户
2013-06-06
展开全部
在初始化后,调用一下doLayout()试试
追问
我刚才尝试了下,没用,这个方法应该不适合这种情况
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式