我想创建一个程序,其中有 4 个按钮,用户需要将它们匹配在一起。
因此,如果有 4 个按钮:按钮 1、按钮 2、按钮 3、按钮 4,并且用户按下按钮 1 和按钮 3,则按钮会改变颜色。否则他们保持不变。
我曾尝试在动作侦听器中使用动作侦听器和 if 语句,但我不太确定我将如何做到这一点,以便它检查两个按钮是否都被按下。
谢谢。
这是我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.Color.*;
import javax.swing.Box;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.border.LineBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.BorderFactory;
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
public class test3 extends JPanel {
JFrame frame;
JPanel panel;
public test3() {
/*Frame and panel */
frame = new JFrame("Keyboard");
panel = new JPanel();
/* Buttons fot letters*/
final JButton button1 =new JButton("button1");
final JButton button2 =new JButton("button2");
final JButton button3 =new JButton("button3");
final JButton button4 =new JButton("button4");
frame.setVisible(true);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
panel.setLayout(null);
panel.setBackground(Color.WHITE);
panel.setCursor( new Cursor(Cursor.HAND_CURSOR) ); // set the cursor to a hand
frame.add(panel);
Insets insets = panel.getInsets();
button1.setLayout(null);
button1.setBounds(130 + insets.left, 300 + insets.top, 50,50);
button1.setBackground(Color.WHITE);
button1.setBorder(BorderFactory.createEmptyBorder());
button2.setLayout(null);
button2.setBounds(180 + insets.left, 300 + insets.top, 50,50);
button2.setBackground(Color.WHITE);
button2.setBorder(BorderFactory.createEmptyBorder());
button3.setLayout(null);
button3.setBounds(230 + insets.left, 300 + insets.top, 50,50);
button3.setBackground(Color.WHITE);
button3.setBorder(BorderFactory.createEmptyBorder());
button4.setLayout(null);
button4.setBounds(280 + insets.left, 300 + insets.top, 50,50);
button4.setBackground(Color.WHITE);
button4.setBorder(BorderFactory.createEmptyBorder());
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
}
public static void main(String[] args) {
new test3();
}
}