我创建了一个简单的应用程序,其中包含一个面板(由 JPanel 扩展),其中包含一个小框(myMessagePanel - 请参见下面的代码)。
基本上,我想在按下框时从面板和框生成焦点事件。但是,只调用了 Panel 中的 focusGained 和 focusLost。这是代码:
myMessageBox 是框,Panel 是面板,FocusListenerTest 包含主要
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Panel extends JPanel implements MouseListener, FocusListener {
myMessageBox msgBox;
public Panel() {
addMouseListener(this);
addFocusListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.GREEN);
msgBox = new myMessageBox(g);
g.dispose();
}
public void focusGained(FocusEvent fe) {
System.out.println("Focus gained in JPanel");
}
public void focusLost(FocusEvent fe){
System.out.println("Focus lost in JPanel");
}
public void mousePressed(MouseEvent me) {
requestFocus();
System.out.println("Mouse Pressed in JPanel");
}
public void mouseReleased(MouseEvent me) {}
public void mouseClicked(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
}
class myMessageBox extends Component implements FocusListener, MouseListener{
myMessageBox(Graphics g) {
addMouseListener(this);
addFocusListener(this);
paintComponent(g);
System.out.println("Done");
}
public void paintComponent(Graphics g) {
g.fillRect(150,100,100,100);
}
public void mousePressed(MouseEvent me) {
requestFocus();
System.out.println("Mouse pressed on box");
}
public void mouseReleased(MouseEvent me) {}
public void mouseClicked(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void focusGained(FocusEvent fe){
System.out.println("Focus gained by box");
}
public void focusLost(FocusEvent fe) {
System.out.println("Focus lost by box");
}
}
public class FocusListenertest {
public static void main(String args[]) {
JFrame window = new JFrame();
Panel content = new Panel();
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(100,75);
window.setSize(400, 400);
window.setVisible(true);
}
}
当我运行此代码时,按下 myMessageBox 时不会打印“框获得的焦点”。
谢谢
(PS:没有写评论,因为它是一个简单的应用程序。如果需要评论,请告诉我)