【问题标题】:Drawing on a JButton[][] grid in a Java GUI在 Java GUI 中的 JButton[][] 网格上绘图
【发布时间】:2020-01-28 04:57:39
【问题描述】:

我有一个二维 JButton 数组,我希望用户能够在单击鼠标时在其上绘制线条。 Grid of Buttons Image

目前,当用户单击网格中的特定 JButton 时,它会变为红色。我希望能够按住左键单击并将鼠标悬停在我想变成红色的 JButtons 上。这是我到目前为止所拥有的

      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);
            }
       }

mouseEntered 方法几乎可以满足我的要求。问题是我只希望它在我按住左键时发生。谢谢。

【问题讨论】:

标签: java swing user-interface mouseevent jbutton


【解决方案1】:

您可以通过在 mouseEntered 事件中使用 javax.swing.SwingUtilities 来检查鼠标左键是否被按下:

@Override
public void mouseEntered(MouseEvent evt) {
    if (SwingUtilities.isLeftMouseButton(evt))
        button.setBackground(Color.BLUE);
}

【讨论】:

  • 正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多