![]() |
#2
疯狂的小a2018-03-09 19:57
![]() package com.xiaoa.demo; import java.awt.Button; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; public class Gaibianyanse extends JFrame implements ActionListener { Button bt1, bt2; JPanel jp1, jp2; public static void main(String[] args) { Gaibianyanse keke = new Gaibianyanse(); } public Gaibianyanse() { bt1 = new Button("红色"); bt2 = new Button("绿色"); jp1 = new JPanel(); jp2 = new JPanel(); bt1.addActionListener(this); bt2.addActionListener(this); bt1.setActionCommand("Tutu"); bt2.setActionCommand("Kaka"); jp2.add(bt1); jp2.add(bt2); jp2.setLayout(new FlowLayout(FlowLayout.CENTER)); this.setLayout(new GridLayout(2, 1)); this.add(jp1); this.add(jp2); this.setTitle("改颜色的面板"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); this.setLocation(300, 300); this.setSize(300, 300); } @Override //方法名首字母小写,否则就不是重写方法了actionPerformed public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Tutu")) { jp1.setBackground(Color.BLACK); } else if (e.getActionCommand().equals("Kaka")) { jp1.setBackground(Color.RED); } } } |
执行不了,但没看出来哪里有错,请老司机帮看看。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Gaibianyanse extends JFrame implements ActionListener{
Button bt1,bt2;
JPanel jp1,jp2;
public static void main(String[] args) {
Gaibianyanse keke=new Gaibianyanse();
}
public Gaibianyanse() {
bt1=new Button("红色");
bt2=new Button("绿色");
jp1=new JPanel();
jp2=new JPanel();
bt1.addActionListener(this);
bt2.addActionListener(this);
bt1.setActionCommand("Tutu");
bt2.setActionCommand("Kaka");
jp2.add(bt1);
jp2.add(bt2);
jp2.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setLayout(new GridLayout(2,1));
this.add(jp1);
this.add(jp2);
this.setTitle("改颜色的面板");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setLocation(300, 300);
this.setSize(300,300);
}
public void ActionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Tutu")) {
jp1.setBackground(Color.BLACK);
}
else if(e.getActionCommand().equals("Kaka")) {
jp1.setBackground(Color.RED);
}
}
}