Java Swing 组件未显示

标签 java swing layout layout-manager flowlayout

帮帮我!每当我尝试启动下面的代码时,它只显示底部的按钮和其他地方的密码字段。我想看到一切,但我看不到

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);
}

最佳答案

BorderLayoutJFrame 的默认布局。当 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);

这是它的样子:

enter image description here

编辑:

来自 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/

相关文章:

java - 实现连续线程的高效方式

html - 断词将下一个 li 推下

layout - 如何在一个基线上对齐 TextBlock 和 TextBox 文本

java - 根据 CardLayout 中另一张卡片的输入更新一张卡片的(JPanel)内容

php - Opencart - 当我在布局中选择它时,模块没有出现

java - 使用可选部分格式化日期

java - 为什么当我的类中的计数器较大时,java 线程的行为有所不同?

java - Java 扫描器的问题

java - 验证输入对话框

java - 添加到使用 GroupLayout 的 JPanel