Java GUI Programming Tips
Java GUI FAQ
Inner Classes and Compilation
Q: After compiling a Java program called Mike, a Mike$1.class file appears. What’s this?
A: This indicates an anonymous inner class.
Painting Components
Q: How do you call the paint(Graphics g) method in a JComponent (like JPanel) to redraw it?
A: Indirectly, using the repaint() method.
Adding Multiple Buttons
Q: How can multiple buttons be added to a Frame and displayed?
A: Add a JPanel to the Frame, then add the buttons to the JPanel.
Handling Button Clicks
Q: When creating a GUI, the windows and components display, but button clicks cause a “cannot find symbol” error related to the ActionListener interface. What’s wrong?
A: Ensure you’ve imported the necessary event packages (e.g., java.awt.event.*) alongside Swing and AWT packages.
Mouse Tracking
Q: How can a small circle be drawn around the mouse cursor as it moves over a JPanel?
A: Add a MouseMotionListener to the panel and capture the (x, y) coordinates in the mouseMoved() method. Use these coordinates to draw the circle in the paint() method.
Mouse Listeners
Q: What’s the difference between MouseListener and MouseMotionListener?
A: MouseListener handles mouse clicks, while MouseMotionListener handles mouse movements (like dragging and hovering).
Button Click Actions
Q: Which method assigns the action to be performed when a button is clicked?
A: addActionListener(...)
Implementing ActionListeners
There are three main ways to create an ActionListener for a JButton:
- Inner Class: Defined within another class, providing access to all members (including private ones). Useful for button actions interacting with other program parts.
- External Class: A separate class implementing
ActionListener. Promotes reusability but requires passing references to access private members of the button’s class. - Anonymous Inner Class/Current Class Implementation: Define actions inline or handle multiple buttons within a single
actionPerformed()method using conditional logic.
