发布网友 发布时间:2022-04-26 00:55
共1个回答
热心网友 时间:2022-06-19 00:08
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* @author Gerrad
*
* 色盲测试
*/
public class ColorBlindnessTest extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel infoPanel = new JPanel();
private JPanel bgPanel = new JPanel();
private JPanel resultPanel = new JPanel();
private JButton btnRed = new JButton("红色");
private JButton btnGreen = new JButton("绿色");
private JButton btnTryAgain = new JButton("再试一次");
private JLabel lblInfo = new JLabel("请根据下面的颜色来点击相应的按钮!");
private JLabel lblResult = new JLabel();
private int score = 0;
private int flag = 0;
public ColorBlindnessTest() {
this.setTitle("色盲测试:两次都选对才不是色盲");
this.setLayout(new BorderLayout());
infoPanel.add(lblInfo);
btnRed.addActionListener(this);
btnGreen.addActionListener(this);
infoPanel.add(btnRed);
infoPanel.add(btnGreen);
infoPanel.add(lblResult);
this.add(infoPanel, BorderLayout.NORTH);
bgPanel.setBackground(Color.RED);
this.add(bgPanel, BorderLayout.CENTER);
resultPanel.add(lblResult);
btnTryAgain.addActionListener(this);
//resultPanel.add(btnTryAgain);
this.add(resultPanel, BorderLayout.SOUTH);
this.setSize(400, 400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new ColorBlindnessTest();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(btnRed)) {
flag++;
if (bgPanel.getBackground().equals(Color.red)) {
score += 50;
bgPanel.setBackground(Color.green);
} else {
bgPanel.setBackground(Color.green);
}
} else if (e.getSource().equals(btnGreen)) {
flag++;
if (bgPanel.getBackground().equals(Color.green)) {
score += 50;
bgPanel.setBackground(Color.green);
} else {
bgPanel.setBackground(Color.green);
}
}
if (flag == 2){
if (score == 100) {
lblResult.setText("恭喜您!不是色盲!");
resultPanel.add(btnTryAgain);
} else {
lblResult.setText("很遗憾~您没有通过测试!您是色盲!");
resultPanel.add(btnTryAgain);
}
}
if (e.getSource().equals(btnTryAgain)) {
this.setVisible(false);
new ColorBlindnessTest();
}
}
}
运行结果: