Java Swing; Two classes, where to put if statements and new actionlisteners?

Because ClockListener is a nested class (lower), the enclosing instance (upper) can access the listener’s private fields. If you have a reference to an instance of ClockListener, ClockListener cl = new ClockListener(); you can use it to initialize your timer Timer t = new Timer(1000, cl); and you can use it in your test: if … Read more

Composing Swing Components: How do I add the ability to add ActionListeners?

I’d use a JToggelButton, as shown here, or delegate to the contained buttons, as @duffymo suggests. If you really need a custom OnOffSwitchEvent, the standard wiring is outlined in EventListenerList, an instance of which is contained in every JComponent. Addendum: Here’s an example of delegating to a ButtonGroup containing two buttons. The label is decorated … Read more

Giving JMenuItem’s name to it’s ActionListener

another way as implementing inner ActionListener (with setActionCommand(String actionCommand)) for whole JMenu is wrote java.swing.Action for each of JMenuItem or implements EventHandler (seems like as valid for all Listeners that I tried) example about JButtons and with implemented ActionListener and EventHandler (both Listeners firing events) EDIT: EventHandler os too hacky, because in Swing aren’t another … Read more

How do you add an ActionListener onto a JButton in Java

Two ways: 1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you’ll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from. 2. Use anonymous … Read more

Dynamic JComboBoxes

Yes, simply create a DefaultComboBoxModel for each set, and do setModel() on JComboBox2 when JComboBox1 changes. Addendum: For example, import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; public class ComboTest extends JPanel implements ActionListener, Runnable { private final JComboBox combo1 = new JComboBox( new String[]{“Course 1”, “Course … Read more

Differences between action and actionListener

actionListener Use actionListener if you want have a hook before the real business action get executed, e.g. to log it, and/or to set an additional property (by <f:setPropertyActionListener>), and/or to have access to the component which invoked the action (which is available by ActionEvent argument). So, purely for preparing purposes before the real business action … Read more