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.JPanel;
public class Test extends JFrame{
public Test(){
this.setSize(400,300);
this.setLocationRelativeTo(null);//设置居中
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp =new JPanel();
final JButton jb1 = new JButton("弹出蓝色");
JButton jb2 = new JButton("弹出青色");
jp.add(jb1);
jp.add(jb2);
//给第一个按钮添加监听
jb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame jf=new JFrame();
JPanel jp=new JPanel();
jf.setSize(200, 200);
jf.add(jp);
jp.setBackground(Color.blue);
jf.setLocationRelativeTo(jb1);
jf.setVisible(true);
}
});
//给第二个按钮添加监听
jb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame jf=new JFrame();
JPanel jp=new JPanel();
jf.setSize(200, 200);
jf.add(jp);
jp.setBackground(Color.cyan);
jf.setLocationRelativeTo(jb1);
jf.setVisible(true);
}
});
this.add(jp);
}
public static void main(String arg[]){
new Test().setVisible(true);
}
}
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Pratice1 extends Frame implements ActionListener{
Button b1,b2;
Pratice1(){
b1=new Button("b1");
b2=new Button("b2");
add(b1,"North");
add(b2,"Center");
b1.addActionListener(this);
b2.addActionListener(this);
pack();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1){
Frame f1=new Frame("我是b1的窗口");
f1.setVisible(true);
f1.setSize(300, 300);// TODO 自动生成的方法存根
}
else if(e.getSource()==b2){
Frame f1=new Frame("我是b2的窗口");
f1.setVisible(true);
f1.setSize(300, 300);
}
}
public static void main(String args[]){
Pratice1 p=new Pratice1();
p.setVisible(true);
}
}
在各自的事件监听里面,new不同的窗口的构造函数就行了。
你没有把两个按钮区分开来