1) Make the exit button work. 2) If the \"new\" button is depressed, make the ba
ID: 3540506 • Letter: 1
Question
1) Make the exit button work.
2) If the "new" button is depressed, make the background color of the frame change back and forth from blue to green.
====================================================
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
public class Main extends JFrame
{
Main(){ //constructor
JFrame frame = new JFrame("For Mouse Click");
JButton button = new JButton("Exit");
JButton button2 = new JButton("New"); //added
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLayout(new FlowLayout() );
frame.setLocation(200,200);
frame.add(button);
frame.add(button2);
ButtonListener btlistener = new ButtonListener(); //this uses the ButonListener below
button.addActionListener(btlistener);
button2.addActionListener(btlistener);
frame.setVisible(true);
}
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getActionCommand() == "Exit") System.out.println("Exit button pressed");
if(e.getActionCommand() == "New") System.out.println("New button pressed");
}
}
public static void main(String[] args) {
Main m = new Main();
}
}
Explanation / Answer
Please rate my efforts :)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
public class Main extends JFrame
{
Main(){ //constructor
JFrame frame = new JFrame("For Mouse Click");
JButton button = new JButton("Exit");
JButton button2 = new JButton("New"); //added
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLayout(new FlowLayout() );
frame.setLocation(200,200);
frame.add(button);
frame.add(button2);
ButtonListener btlistener = new ButtonListener(); //this uses the ButonListener below
button.addActionListener(btlistener);
button2.addActionListener(btlistener);
frame.setVisible(true);
}
class ButtonListener implements ActionListener{
int count=0;
public void actionPerformed(ActionEvent e){
if(e.getActionCommand() == "Exit") {
System.out.println("Exit button pressed");
System.exit(0)
}
if(e.getActionCommand() == "New")
{
if(count%2==0) frame.getContentPane().setBackground( Color.BLUE )
else frame.getContentPane().setBackground( Color.GREEN )
count++;
System.out.println("New button pressed");
}
}
}
public static void main(String[] args) {
Main m = new Main();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.