Using addMouseListener() and paintComponent() for JPanel

This is not an immediate answer to your question, but knowing (or at least suspecting) what it is that you wish to offer (a simple paint program), I suggest starting with this approach based around a BufferedImage as the painting surface.. import java.awt.*; import java.awt.RenderingHints.Key; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; … Read more

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