我有一个 JButton 的 2D 数组,我希望用户能够在单击鼠标时绘制线条。按钮网格图像
目前,当用户单击网格中的特定 JButton 时,它会变为红色。我希望能够按住左键向下并将鼠标悬停在我想变红的 JButton 上。这是我到目前为止所拥有的
for (int i = 0; i < 40; i++) {
for (int j = 0; j < 40; j++) {
if (grid[i][j] != grid[0][0] && grid[i][j] != grid[39][39]) {
grid[i][j].addMouseListener(new java.awt.event.MouseAdapter(){
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
JButton button = (JButton) evt.getSource();
button.setBackground(Color.red);
paintedButtons.add(button);
button.transferFocus();
paintedButtons.add(button);
}
// public void mouseEntered(MouseEvent evt) {
// JButton button = (JButton) evt.getSource();
// button.setBackground(Color.red);
//
// paintedButtons.add(button);
//
// }
});
}
grid[0][0].setBackground(Color.GRAY);
grid[39][39].setBackground(Color.GREEN);
}
}
mouseEnter方法几乎可以满足我的需求。问题是我只希望它发生在我按住左键单击时。谢谢。
您可以使用鼠标输入事件中的javax.swing.SwingUtilities
来检查是否按下了鼠标左键:
@Override
public void mouseEntered(MouseEvent evt) {
if (SwingUtilities.isLeftMouseButton(evt))
button.setBackground(Color.BLUE);
}