简体   繁体   中英

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. 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 :(

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 . Refer to Mixing Heavyweight and Lightweight Components .
  2. When using JButton , you should add an ActionListener and not a MouseListener .
  3. The default layout manager for JPanel is FlowLayout so no need to explicitly set it.
  4. Rather than requiring a separate variable to record the number of times the JButton was clicked, I suggest using client properties .

Here is my rewrite of your test class that implements the above points. Note that I changed the name of the class from test to 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.

While not specifically stated in your question, the above code alternates the text of the 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 . You can click the button as many times as you like and the text will change from X to O and back again.

The reason why your i variable always set to 0 is that you initialize it in your mouseClicked function. So every time the function was called, you will always set the i to 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.

  • Move out i from the function mouseClicked , put it in global space. It prevents resetting i value.
  • I rename i , new name is buttonStateChanger
  • Also, reset buttonStateChanger inside else block.
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();
    }

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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