我创建了一个简单的应用程序,其中包含一个面板(通过JPanel扩展)和一个小框(myMessagePanel - 请参见下面的代码)。
基本上,当按下框时,我希望从面板和框中生成焦点事件。但是,只有在面板中调用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时,“聚焦到box”没有被打印出来。
谢谢。
(附注:由于这是一个简单的应用程序,因此没有编写注释。如果需要注释,请告知)
msgBox
添加到Panel
。同时,组件的边界没有设置。 - Prince John Wesley