简体   繁体   English

为什么我的按钮在点击后没有变化?

[英]Why doesn't my button change after clicking?

Please help with the problem.请帮助解决问题。 I need the label to change to X after click on my button, and to O after the second click.我需要 label 在单击我的按钮后更改为X ,在第二次单击后更改为O Please check my code below, and tell me what is wrong?请检查我下面的代码,并告诉我出了什么问题? My program just changes the label to X , but doesn't change to O :(我的程序只是将 label 更改为X ,但不会更改为O :(

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test extends MouseAdapter {
    JPanel windowContent;
    JFrame frame;
    Button myButton;
    test() {
        windowContent = new JPanel();
        FlowLayout fl = new FlowLayout();
        windowContent.setLayout(fl);
        
        myButton = new Button("Change text");
        myButton.addMouseListener(this);
        windowContent.add(myButton);
        
        frame = new JFrame("Tic Tac Toe");
        frame.setContentPane(windowContent);
        frame.setSize(100, 100);
        frame.setVisible(true);
    }
    
    public void mouseClicked(MouseEvent e) {
        int i = 0;
        if (i == 0) {
            myButton.setLabel("X");
            i++;
        } else if (i == 1) {
            myButton.setLabel("O");
        }
    }
    
    public static void main(String[] args) {
        new test();
    }

}

Apart from your question, there are several other things in your code that I think need to be changed.除了您的问题之外,我认为您的代码中还有其他几处需要更改。

  1. I don't know if it's a mistake or if it's intentional, but the type for variable myButton should be javax.swing.JButton and not java.awt.Button because you should, as much as possible, not mix AWT components with Swing components since Swing components are considered lightweight whereas AWT components are referred to as heavyweight . I don't know if it's a mistake or if it's intentional, but the type for variable myButton should be javax.swing.JButton and not java.awt.Button because you should, as much as possible, not mix AWT components with Swing components因为Swing组件被认为是轻量级的,而 AWT 组件被称为重量级 Refer to Mixing Heavyweight and Lightweight Components .请参阅混合重量级和轻量级组件
  2. When using JButton , you should add an ActionListener and not a MouseListener .使用JButton时,您应该添加ActionListener而不是MouseListener
  3. The default layout manager for JPanel is FlowLayout so no need to explicitly set it. JPanel的默认布局管理器FlowLayout ,因此无需显式设置。
  4. Rather than requiring a separate variable to record the number of times the JButton was clicked, I suggest using client properties .我建议使用客户端属性,而不是要求单独的变量来记录JButton被单击的次数。

Here is my rewrite of your test class that implements the above points.这是我对实现上述几点的test class 的重写。 Note that I changed the name of the class from test to Testing0 .请注意,我将 class 的名称从test更改为Testing0

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Testing0 implements ActionListener {
    JPanel windowContent;
    JFrame frame;

    public Testing0() {
        windowContent = new JPanel();
        
        JButton myButton = new JButton("Change text");
        myButton.putClientProperty("count", Integer.valueOf(0));
        myButton.addActionListener(this);
        windowContent.add(myButton);
        
        frame = new JFrame("Tic Tac Toe");
        frame.setContentPane(windowContent);
        frame.setSize(100, 100);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source instanceof JButton) {
            JButton button = (JButton) source;
            Object value = button.getClientProperty("count");
            if (value instanceof Integer) {
                Integer objVal = (Integer) value;
                int intVal = objVal.intValue();
                String text = switch (intVal) {
                    case 0 -> "X";
                    case 1 -> "O";
                    default -> "";
                };
                button.setText(text);
                intVal = intVal == 0 ? 1 : 0;
                button.putClientProperty("count", Integer.valueOf(intVal));
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new Testing0());
    }
}

Method actionPerformed , in the above code, uses switch expressions which were introduced in Java 12.上述代码中的方法actionPerformed使用了在 Java 12 中引入的switch 表达式

While not specifically stated in your question, the above code alternates the text of the JButton .虽然您的问题中没有具体说明,但上面的代码替换了JButton的文本。 If the text is X then it is changed to O when the button is clicked and if the text is O then it is changed to X .如果文本为X则在单击按钮时更改为O ,如果文本为O则更改为X You can click the button as many times as you like and the text will change from X to O and back again.您可以根据需要多次单击该按钮,文本将从X变为O并再次变回。

The reason why your i variable always set to 0 is that you initialize it in your mouseClicked function.您的i变量始终设置为 0 的原因是您在mouseClicked function 中对其进行了初始化。 So every time the function was called, you will always set the i to 0.所以每次调用 function 时,总是将i设置为 0。

public void mouseClicked(MouseEvent e) {
        int i = 0;      //here is the problem
        if (i == 0) {
            myButton.setLabel("X");
            i++;
        } else if (i == 1) {
            myButton.setLabel("O");
        }
    }

Try to initialize it outside your mouseClicked function.尝试在鼠标外初始化它点击mouseClicked

  • Move out i from the function mouseClicked , put it in global space.i从 function mouseClicked移出,放到全局空间。 It prevents resetting i value.它可以防止重置i值。
  • I rename i , new name is buttonStateChanger我重命名i ,新名称是buttonStateChanger
  • Also, reset buttonStateChanger inside else block.此外,在else块中重置buttonStateChanger
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest extends MouseAdapter {
    JPanel windowContent;
    JFrame frame;
    Button myButton;
    int buttonStateChanger = 0;
    ButtonTest() {
        windowContent = new JPanel();
        FlowLayout fl = new FlowLayout();
        windowContent.setLayout(fl);
        
        myButton = new Button("Change text");
        myButton.addMouseListener(this);
        windowContent.add(myButton);
        
        frame = new JFrame("Tic Tac Toe");
        frame.setContentPane(windowContent);
        frame.setSize(100, 100);
        frame.setVisible(true);
    }
    
    public void mouseClicked(MouseEvent e) {

        if (buttonStateChanger == 0) {
            myButton.setLabel("X");
            buttonStateChanger++;
        } else if (buttonStateChanger == 1) {
            myButton.setLabel("O");
            buttonStateChanger = 0;
        }
    }
    
    public static void main(String[] args) {
        new ButtonTest();
    }

}

在此处输入图像描述 在此处输入图像描述

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

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