GridLayout +鼠标侦听器 [英] GridLayout + Mouse Listener
问题描述
好的,我有一个问题,我不知道如何知道在网格布局上单击了哪个单元格,有什么功能吗?
Okay guys I have a problem, I dont know how know which cell was clicked on a grid layout, is there any function?
我在容器上有网格布局,可容纳10行10列,而我想要的是对所有单元格的鼠标侦听器,因此,当我单击单元格(2,1)时,它会说我正在单击哪个单元格,原因是鼠标侦听器.
I have grid layout on container, for 10 rows and 10 columns, and what I want is a mouse listener to all the cells, so when I click cell (2,1) it would say which cell I am clicking because of the mouse listener.
有任何线索吗?在此先感谢
Any clues? thanks alot in advance
推荐答案
向使用GridLayout并在网格中保存组件的容器中添加一个MouseListener.然后在mousePressed上,使用MouseEvent对象(称为myMouseEvent)来获取点击点,并调用getComponentAt(myMouseEvent.getPoint);
来获取被点击的组件.没什么大惊小怪的.
Add a MouseListener to the Container that uses GridLayout and that holds the components in the grid. Then on mousePressed use the MouseEvent object, say called myMouseEvent, to get the point of the click and call getComponentAt(myMouseEvent.getPoint);
to get the clicked component. No muss no fuss.
例如:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class TestComponentAt extends JPanel {
private static final int ROW_COUNT = 10;
private static final int W = 60;
private static final int H = W;
private static final Dimension PREF_SIZE = new Dimension(W, H);
protected static final Color SELECTION_COLOR = Color.pink;
private JPanel selectedPanel = null;
private Color originalColor = null;
public TestComponentAt() {
setLayout(new GridLayout(ROW_COUNT, ROW_COUNT, 1, 1));
setBackground(Color.black);
for (int i = 0; i < ROW_COUNT * ROW_COUNT; i++) {
JPanel panel = new JPanel();
String name = String.format("[%d, %d]",
i / ROW_COUNT, i % ROW_COUNT);
panel.setName(name);
if (i == 0) {
originalColor = panel.getBackground();
}
panel.setPreferredSize(PREF_SIZE);
add(panel);
}
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
JPanel panel = (JPanel) getComponentAt(e.getPoint());
if (panel == null || panel == TestComponentAt.this) {
return;
}
if (selectedPanel != null) {
selectedPanel.setBackground(originalColor);
selectedPanel.removeAll();
selectedPanel.revalidate();
selectedPanel.repaint();
}
selectedPanel = panel;
selectedPanel.setBackground(SELECTION_COLOR);
selectedPanel.add(new JLabel(selectedPanel.getName()));
selectedPanel.revalidate();
selectedPanel.repaint();
}
});
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestComponentAt");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestComponentAt());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
这篇关于GridLayout +鼠标侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!