Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

turn the background of the content panel to red if user click yellowButton and t

ID: 3651008 • Letter: T

Question

turn the background of the content panel to red if user click yellowButton and
the background of the content panel to green if the greenButton is click.


public class ButtonTest extends JFrame
{
private JButton yellowButton, greenButton;
private Container window;

public static void main()
{
ButtonTest repo = new ButtonTest();
repo.setSize(300,300);
repo.createGUI();
repo.setVisible(true);
}

private void createGUI()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
window = getContentPane();
window.setLayout(new FlowLayout());

yellowButton = new JButton("Yellow");
yellowButton.addActionListener(new YellowButtonAction());
window.add(yellowButton);
greenButton = new JButton("Green");
greenButton.addActionListener(new GreenButtonAction());
window.add(greenButton);
}

// missing code

}

Explanation / Answer

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonTest extends JFrame { private JButton yellowButton, greenButton; private Container window; public static void main(String args[]) { ButtonTest repo = new ButtonTest(); repo.setSize(300,300); repo.setVisible(true); repo.createGUI(); } private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); window = getContentPane(); window.setLayout(new FlowLayout()); yellowButton = new JButton("Yellow"); yellowButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { YellowButtonAction(); } }); window.add(yellowButton); greenButton = new JButton("Green"); greenButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GreenButtonAction(); } }); window.add(greenButton); } void YellowButtonAction() { window.setBackground(Color.red); } void GreenButtonAction() { window.setBackground(Color.green); } }