帮帮我!每当我尝试启动下面的代码时,它只显示底部的按钮和其他地方的密码字段。我想看到一切,但我看不到
public void setup(){
frame = new JFrame("Votinator 3000");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
voteconfirm = new JLabel("");
textarea = new JTextField(1);
submit = new JButton("Submit Vote!");
chooser = new JList(items);
password = new JPasswordField(1);
password.setVisible(true);
choices = new JComboBox();
choices.addItem("Choose");
choices.addItem("Submit Own");
type = new JPanel();
type.add(textarea);
choices.setEditable(false);
choices.setSelectedIndex(0);
frame.setBounds(300, 300, 400, 400);
frame.getContentPane().add(type);
frame.getContentPane().add(choices);
frame.getContentPane().add(voteconfirm);
frame.getContentPane().add(chooser);
frame.getContentPane().add(textarea);
frame.getContentPane().add(password,BorderLayout.CENTER);
frame.getContentPane().add(submit,BorderLayout.SOUTH);
frame.setVisible(true);
}
最佳答案
BorderLayout
是 JFrame
的默认布局。当 add()
方法中没有参数时,代码中的所有组件都会添加到 BorderLayout.CENTER
。因此只有 password
出现在 BorderLayout.CENTER
中,因为它会替换其他组件。尝试创建一个面板,用控件填充它并将这个面板添加到框架中,即:
JPanel content = new JPanel();
content.add(type);
content.add(choices);
content.add(voteconfirm);
content.add(chooser);
content.add(textarea);
content.add(password);
content.add(submit);
frame.getContentPane().add(content);
这是它的样子:
编辑:
来自 BorderLayout规范:
As a convenience, BorderLayout interprets the absence of a string specification the same as the constant CENTER:
Panel p2 = new Panel(); p2.setLayout(new BorderLayout()); p2.add(new TextArea()); // Same as p.add(new TextArea(), BorderLayout.CENTER);
关于Java Swing 组件未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041915/