gpt4 book ai didi

java - JButton 不显示

转载 作者:行者123 更新时间:2023-12-01 23:43:18 25 4
gpt4 key购买 nike

嗨,有人知道为什么我的“button1”不显示吗?当我执行该程序时,我似乎无法弄清楚它一切正常并成功运行,但它不显示此按钮。任何帮助将不胜感激,谢谢。

private Container c;
private JPanel gridPanel;
private JComboBox combo;
final JLabel label = new JLabel();
private JButton button1 = new JButton("Clear");
private JButton button2 = new JButton("Exit");

/**
* Christopher Haddad - 559815X
*/
public Planets() {
c = getContentPane();
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(5, 0, 0, 0));

label.setVisible(true);

combo = new JComboBox();
combo.setEditable(false);
combo.addItem("No Planet Selected");
combo.addItem("Mercury");
combo.addItem("Venus");
combo.addItem("Earth");
gridPanel.add(combo);

add(button1);
add(button2);
button1.addActionListener(this);
button2.addActionListener(this);

c.add(gridPanel, BorderLayout.NORTH);
setTitle("Planet Diameter");
setSize(700, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {

JComboBox comboBox = (JComboBox) event.getSource();

Object select = comboBox.getSelectedItem();

if(select.toString().equals("No Planet Selected"))
label.setText("");
else if(select.toString().equals("Mercury"))
label.setText("The planet Mercury is 3100kms in diameter");
else if(select.toString().equals("Venus"))
label.setText("The planet Venus is 7500kms in diameter");
else if (select.toString().equals("Earth"))
label.setText("The planet Earth is 8000kms in diameter");

}
});
getContentPane().add(combo);
getContentPane().add(label);
}

// event handling method, implementing the actionPerformed method of ActionListener
public void actionPerformed(ActionEvent e)
{
// set the button label to number of times it has been clicked
if(e.getSource() == button1) {
label.setText(" ");
}
else if(e.getSource() == button2) {
System.exit(0);
}
}

最佳答案

很难确定,但我假设您将内容直接添加到顶级容器,例如JFrame

JFrame 使用 BorderLayout 作为默认布局管理器,因此使用

add(button1);
add(button2);

基本上是说,添加 button1CENTER位置,然后添加 button2CENTER 位置。 BorderLayout 只允许单个组件存在于特定位置。

首先尝试将按钮添加到另一个面板...

关于java - JButton 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17583712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com