gpt4 book ai didi

java - 如何在 JPanel GridLayout 上实现鼠标进入和鼠标退出?

转载 作者:行者123 更新时间:2023-11-30 01:48:11 26 4
gpt4 key购买 nike

我在如何让鼠标退出和鼠标进入 JPanel 上的 GridLayout 时遇到问题,其中 1 个单元格中包含 2 个面板。

我不知道如何知道网格布局上输入了哪个单元格,有什么功能吗?

我在容器上有网格布局,5行3列,我想要的是所有单元格的鼠标监听器,所以当我输入单元格时,它会因为鼠标监听器而显示我正在输入哪个单元格。

有什么线索吗?

最佳答案

MouseEvent.getComponent() 将返回生成事件的组件。如果代码向网格中的每个面板添加鼠标监听器,则很容易找出哪个面板触发了事件。

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

public class MousePanelArrayTest {

private final JComponent ui = new JPanel(new BorderLayout(4, 4));
MouseListener mouseListener;

MousePanelArrayTest() {
initUI();
}

public final void initUI() {
mouseListener = new MouseAdapter() {

@Override
public void mouseEntered(MouseEvent e) {
Component c = e.getComponent();
c.setBackground(Color.BLACK);
}

@Override
public void mouseExited(MouseEvent e) {
Component c = e.getComponent();
c.setBackground(Color.WHITE);
}
};

ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel gridPanel = new JPanel(new GridLayout(0, 5, 4, 4));
ui.add(gridPanel);
for (int ii=0; ii<20; ii++) {
gridPanel.add(getPanel());
}
}

private JPanel getPanel() {
JPanel p = new JPanel();
p.addMouseListener(mouseListener);
p.setBorder(new EmptyBorder(10, 20, 10, 20));

return p;
}

public JComponent getUI() {
return ui;
}

public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
MousePanelArrayTest o = new MousePanelArrayTest();

JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);

f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());

f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}````

关于java - 如何在 JPanel GridLayout 上实现鼠标进入和鼠标退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57130688/

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