I\'m having difficulty in getting my program to execute properly. My goal is for
ID: 3660559 • Letter: I
Question
I'm having difficulty in getting my program to execute properly. My goal is for the left button to move all buttons to FlowLayout.LEFT when selected. Currently, the left button only moves the contentPane and leaves an empty space in the right margin when I select the Red color button. I understand that using the contentPane is the cause of the white space but can't figure out how to use the setLayout method to fix it. Other buttons are working properly. Any assistance any appreciated.
My code is as follows:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Class extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private JButton leftButton;
private JButton redButton;
private JButton resetButton;
private Point location;
private Color red;
public Class()
{
createContents();
setTitle("Test");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
location = new Point();
setLocation(location);
red = getBackground();
}
private void createContents()
{
leftButton = new JButton("Left");
leftButton.addActionListener(new ButtonListener());
add(leftButton);
redButton = new JButton("Red");
redButton.addActionListener(new ButtonListener());
add(redButton);
resetButton = new JButton("Reset");
resetButton.addActionListener(new ButtonListener());
add(resetButton);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Container contentPane = getContentPane();
if (e.getSource() == leftButton)
{
contentPane.setLocation((location.x - 30), location.y);
}
else if (e.getSource() == redButton)
{
contentPane.setBackground(Color.RED);
}
else
{
contentPane.setLocation(location);
contentPane.setBackground(red);
}
}
}
public static void main(String[] args)
{
new Class();
}
}
Explanation / Answer
It fixes the problem
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Container contentPane = getContentPane();
if (e.getSource() == leftButton) {
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
contentPane.setVisible(false);
contentPane.setVisible(true);
} else if (e.getSource() == redButton) {
contentPane.setBackground(Color.RED);
} else {
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER));
contentPane.setVisible(false);
contentPane.setVisible(true);
contentPane.setBackground(red);
}
}
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.