gpt4 book ai didi

java - 具有边框布局的 JPanel 上的事件

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:27 26 4
gpt4 key购买 nike

当我将 MouseListener/FocusListener 添加到其中包含 BorderLayout 和 JComponents 的 JPanel 时,我无法捕获鼠标或焦点事件。有什么方法可以捕获具有 BorderLayout 的 JPanel 的鼠标和焦点事件?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Application extends JFrame{

public Application(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel jPanel = new JPanel(new BorderLayout());
jPanel.add(new JButton("Button"));

jPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
});

// if border is set then listener works if not does not
// jPanel.setBorder(new LineBorder(Color.black, 1));
setLayout(new FlowLayout());
add(jPanel);
setSize(400, 400);
setVisible(true);
}

public static void main(String[]args){
new Application().setVisible(true);
}

}

最佳答案

如前所述,只是一个简单的错误。因为 JFrame 被赋予了 FlowLayout,所以 JPanel 仅占用 JButton 所需的区域。您可以通过向 JPanel 添加 Border 来测试它。

现在可以了,

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Application extends JFrame {

private static final long serialVersionUID = 1L;

public Application() {
JPanel jPanel = new JPanel();
jPanel.setLayout(new FlowLayout());
jPanel.add(new JButton("Button"));
jPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(jPanel);
setSize(400, 400);
setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new Application().setVisible(true);
}
});
}
}

关于java - 具有边框布局的 JPanel 上的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7696861/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com