有问题的代码:
package com.a.b; import javax.swing.*; import java.awt.Color;
import java.awt.event.*;
import java.util.Random; class SB extends JFrame implements ActionListener {
JButton jb, jb2; public SB() {
jb2 = new JButton("我我我我");
JPanel jp = new JPanel(); jb = new JButton("你你你");
jb.addActionListener(this);// 注册监听
jp.add(jb);
jp.add(jb2);
this.setVisible(true);
this.add(jp);
this.setBounds(333, 333, 500, 500);
this.setDefaultCloseOperation(3); } public void actionPerformed(ActionEvent a) {
String s = a.getActionCommand();
if (s.equals("我我我我")) {
System.out.println("你好");
Random r = new Random(); if (jb.getBackground() == Color.red) {// 我想实现
jb.setBackground(Color.gray);// 这个set方法是设置,get方法是获取
} else { jb.setBackground(Color.pink); }
} else { if (jb2.getBackground() == Color.black) {
jb2.setBackground(Color.pink);
} else jb2.setBackground(Color.orange); } }
} public class Shi {
public static void main(String[] args) {
new SB();
} }