简体   繁体   English

用 mouseListener 改变 JButton 的颜色

[英]Changing Color of JButton with mouseListener

Im trying to make a simple tictactoe game.我正在尝试制作一个简单的tictactoe 游戏。 To create the grid I used and array of JButtons.要创建我使用的网格和 JButtons 数组。

mouseClicker m1 = new mouseClicker();//check for click

for (int i=0; i<9;i++) {//create buttons
            buttons[i] = new JButton();
            buttons[i].addMouseListener(m1);
            gameSpots.add(buttons[i]);
            
        }

In order to track a user's click I have a mouseListener for the buttons.为了跟踪用户的点击,我有一个用于按钮的 mouseListener。

public class mouseClicker extends MouseAdapter{ 
        public void mousePressed(MouseEvent e) {
              System.out.println(e.getSource());
              System.out.println(e.getX()+", "+e.getY());
              System.out.println();  
           }
    }

With it currently I can print the source of each JButton clicked but I have no idea how to modify the corresponding button with this info (add an x to the button clicked for example).有了它,目前我可以打印每个单击的 JButton 的源,但我不知道如何使用此信息修改相应的按钮(例如,将 x 添加到单击的按钮)。 How could I use the JButton source to achieve this?我如何使用 JButton 源来实现这一点?

You could setText or setIcon :你可以setTextsetIcon

public class MouseClicker extends MouseAdapter {    
    public void mousePressed(MouseEvent e) {
        System.out.println(e.getSource());
        System.out.println(e.getX() + ", " + e.getY());
        System.out.println();
        ((JButton)e.getSource()).setText("X");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM