Reputation: 6745
Hi does anyone know why my "button1" is not displaying? I can not seem to figure it out when I execute the program it all works and runs successfully but it does not display this button. Any help would be appreciated thanks.
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);
}
}
Upvotes: 0
Views: 958
Reputation: 347334
It is difficult to be sure, but I assume you are adding content directly to a top level container, like a JFrame
JFrame
uses a BorderLayout
as it's default layout manager, so using
add(button1);
add(button2);
Basially says, add
button1
to the CENTER
position then add
button2
to the CENTER
position. BorderLayout
will only allow a single component to exist at a specific location.
Try adding the buttons to another panel first...
Upvotes: 3