1) You are writing a simple GUI application using a class called MyGuiClass. You
ID: 3532053 • Letter: 1
Question
1) You are writing a simple GUI application using a class called MyGuiClass. Your GUI will have a JCheckBox which your program will need to respond to when it is clicked. Describe what you would need to do to setup event handling using a named nested inner class. Use Java code fragments in your answer.
2) If the GUI in the above example had three JCheckBoxes, how would you change your actionPerformed method to handle events from the three different check boxes using only one object of your named event handler class?
Explanation / Answer
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; public class MyGUIClass extends JFrame{ private JCheckBox checkBox1; private JCheckBox checkBox2; private JCheckBox checkBox3; JLabel label; public MyGUIClass() { super("Gui test"); checkBox1 = new JCheckBox("one"); checkBox2 = new JCheckBox("two"); checkBox3 = new JCheckBox("three"); label = new JLabel(); add(checkBox1); add(checkBox2); add(checkBox3); add(label); checkBox1.addActionListener(new MyActionListener()); checkBox2.addActionListener(new MyActionListener()); checkBox3.addActionListener(new MyActionListener()); setSize(250, 250); setLayout(new FlowLayout()); setVisible(true); } class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub label.setText("You Clicked on : " + arg0.getActionCommand()); } } public static void main(String args[]) { new MyGUIClass(); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.