Javaswing 如何修改按钮组件的名字!

是一个事件处理的题目,要求有两个按钮“确定”“取消”,按下任意一个之后两个按钮名称互换,请问如果修改按钮名称!感谢感谢!
直接用按钮对象调用getActionCommand()让他等于另一个按钮对象的getActionCommand ()可以吗

回答:修改名称是不难的

img

package test;

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

/**
 * @author bbyh
 * @date 2022/11/26 0026 0:03
 * @description
 */
public class Test extends JFrame {
    public Test() {
        JButton ensure = new JButton("确定");
        JButton cancel = new JButton("取消");

        setLayout(new GridLayout(1, 2));
        add(ensure);
        add(cancel);
        Font font = new Font("楷体", Font.BOLD, 20);
        ensure.setFont(font);
        cancel.setFont(font);

        ensure.addActionListener(e -> {
            ensure.setText("取消");
            cancel.setText("确定");
        });

        cancel.addActionListener(e -> {
            ensure.setText("确定");
            cancel.setText("取消");
        });
    }

    public static void main(String[] args) {
        JFrame frame = new Test();

        frame.setTitle("交换按钮名称");
        frame.setSize(200, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}