I'm trying to repaint a simple massage in a panel by firing an ActionEvent.
I Have a MessagePanel
that extends JPanel
, in which I defined an addActionListener
method and a processEvent
method to process the event:
import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.*;
import java.awt.event.*;
public class MessagePanel extends JPanel {
private String message = new Date().toString();
ArrayList<ActionListener> actionListenerList;
public MessagePanel(String message) {
this.message = message;
}
public void setMessage(String message){
this.message = message;
}
public void addActionListener(ActionListener listener) {
if (actionListenerList == null) {
actionListenerList = new ArrayList<>(2);
}
if (!actionListenerList.contains(listener)) {
actionListenerList.add(listener);
}
}
public void removeActionListener(ActionListener listener) {
if (actionListenerList != null &&
actionListenerList.contains(listener)) {
actionListenerList.remove(listener);
}
}
public void processEvent(ActionEvent e) {
ArrayList<ActionListener> list;
synchronized(this) {
if (actionListenerList == null) {
return;
}
list = (ArrayList<ActionListener>)actionListenerList.clone();
}
for (int i = 0; i < list.size(); i++) {
ActionListener listener = (ActionListener)list.get(i);
listener.actionPerformed(e);
}
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString(message, 0, 0);
}
}
Here's my test class:
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public TestMessaePanel extends JFrame {
MessagePanel messagePanel = new MessagePanel(new Date().toString());
public TestMessagePanel() {
add(messagePanel);
messagePanel.setCentered(true);
messagePanel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
messagePanel.setMessage(new Date().toString());
}
});
}
public static void main(String[] args) {
JFrame frame = new TestMessagePanelWithActionEvent();
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I'm trying to have the panel repaint the current time with every click of the panel (without using any other event sets) but I can't figure out what event is supposed to fire and invoke my processEvent
method. I'm not even really sure if I even need the processEvent
, if I can just implement the process elsewhere.
EDIT WITH TEXTBOOK PROBLEM (below)
(Enable MessagePanel to fire ActionEvent) The MessagePanel class in
Listing 15.7 is a subclass of JPanel; it can fire a MouseEvent,
KeyEvent, and ComponentEvent, but not an ActionEvent. Modify the
MessagePanel class so that it can fire an ActionEvent when an instance
of the MessagePanel class is clicked. Name the new class
MessagePanelWithActionEvent. Test it with a Java applet that displays
the current time in a message panel whenever the message panel is
clicked, as shown in Figure 36.9.