Reputation: 249
I am working on a project from a textbook and I'm stuck. The goal is: When the GUI first appears, both buttons are visible, but when one button is clicked, that button disappears and only the other button is visible. Thereafter only one button is visible; when the button is clicked, it disappears and the other button appears
public class ButtonDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
public ButtonDemo()
{
setSize(WIDTH, HEIGHT);
WindowDestroyer listener = new WindowDestroyer();
addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(new FlowLayout());
JButton sunnyButton = new JButton("Sunny");
sunnyButton.addActionListener(this);
contentPane.add(sunnyButton);
JButton cloudyButton = new JButton("Cloudy");
cloudyButton.addActionListener(this);
contentPane.add(cloudyButton);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
Container contentPane = getContentPane();
if(actionCommand.equals("Sunny"))
{
contentPane.setBackground(Color.BLUE);
}
else if (actionCommand.equals("Cloudy"))
{
contentPane.setBackground(Color.GRAY);
}
else
System.out.println("Error in button interface.");
}
}
Upvotes: 0
Views: 7027
Reputation: 865
What about
source.setVisible(false)
to hide and
source.setVisible(true)
to show the buttons?
Edit: You should get the source of the event (e.getSource()) and hide it
Upvotes: 0
Reputation: 7812
Using setVisible on the buttons should work. Try the following:
Move the following lines to the fields of ButtonDemo:
JButton sunnyButton = new JButton("Sunny");
JButton cloudyButton = new JButton("Cloudy");
Change the if statements in your actionPerformed
to:
if(actionCommand.equals("Sunny"))
{
contentPane.setBackground(Color.BLUE);
sunnyButton.setVisible(false);
cloudyButton.setVisible(true);
}
else if (actionCommand.equals("Cloudy"))
{
contentPane.setBackground(Color.GRAY);
sunnyButton.setVisible(true);
cloudyButton.setVisible(false);
}
Upvotes: 3
Reputation: 46841
It's very simple code. Make sunnyButton
and cloudyButton
as instance member.
Simply check for the source of the action event and hide the source component and show the other one.
public void actionPerformed(ActionEvent e) {
if (sunnyButton == e.getSource()) {
sunnyButton.setVisible(false);
cloudyButton.setVisible(true);
} else if (cloudyButton == e.getSource()) {
sunnyButton.setVisible(true);
cloudyButton.setVisible(false);
}
...
}
Upvotes: 1