如何使用swing类Java绘制网格,并在单击和拖动时检测鼠标位置
我正在尝试使用Swing类创建一个网格UI(5*5)。我尝试了一个嵌套循环,并向jFrame动态添加了一个jPanel。我还尝试在用户点击并落在每个jPanel上时改变其背景颜色。 但在我的代码中,每个单元格之间都有巨大的间隙,我无法让拖动事件工作
public class clsCanvasPanel extends JPanel {
private static final int intRows = 5;
private static final int intCols = 5;
private List<JPanel> jpllist = new ArrayList<JPanel>();
public clsCanvasPanel() {
/*
*
* Add eventListener to individual JPanel within CanvasPanel
*
*
* TODO :
* 1) mousePressed --> update Temperature and HeatConstant of clsElement Class
* 2) start a new thread and
* 3) call clsElement.run() method
*
*
* Right Now : it updates the colours of the JPanel
* */
MouseListener mouseListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
JPanel panel = (JPanel) e.getSource();
Component[] components = panel.getComponents();
for (Component component : components) {
component.setVisible(!component.isVisible());
component.setBackground(new Color(255,255,0));
}
panel.revalidate();
panel.repaint();
}
};
//TODO : refactoring
GridLayout gdlyPlates = new GridLayout();
gdlyPlates.setColumns(intCols);
gdlyPlates.setRows(intRows);
gdlyPlates.setHgap(0);
gdlyPlates.setVgap(0);
setLayout(gdlyPlates);
//TODO : refactoring
for (int row = 0; row < intRows; row++) {
for (int col = 0; col < intCols; col++) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setOpaque(false);
JPanel jl = new JPanel();
jl.setVisible(true);
panel.add(jl);
panel.addMouseListener(mouseListener);
jpllist.add(panel);
add(panel);
}
}
}
}
所以现在我试着创建一个面板,在上面画网格,然后检测鼠标在网格上的位置,进一步改变每个单元格的颜色
有人能给我一些建议,如何在JPanel上实现这个网格,并改变所选单元格的颜色吗
# 1 楼答案
在MuleMeRever方法中的Mouististor示例中,您可能需要考虑XOffice/YOffice,以获得更平滑的小区识别。
# 2 楼答案
有很多方法可以让它发挥作用,这取决于你想要实现什么
第一个示例只使用2D Graphics API渲染单元格,并使用
MouseMotionListener
监视高亮显示的单元格本例确实使用窗口调整网格大小,但将单元格设置为固定大小只是一个很小的改变
查看2D Graphics了解更多详细信息
使用组件示例更新
本例使用一系列
JPanel
来表示每个单元格每个单元格都定义有固定的宽度和高度,不随主窗口调整大小
在本例中,每个单元格面板都有自己的鼠标侦听器。重新编写代码,使主面板有一个鼠标侦听器,并自行管理工作负载,并不太困难
# 3 楼答案
我不喜欢渲染边框,因为在网格中,如果有更多的边框,则会复制一些边框。我认为这个解决方案更好:
编辑:
我的解决方案更好,因为如果原始代码是5x5个单元,但更多,比如10x10。。。一些细胞的内边缘会相互接触,并在某些地方形成厚厚的网格。很高兴在截图上看到 thick grid