日期:2014-05-20 浏览次数:20716 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class bu extends JFrame implements ActionListener { private JFrame jf; private JButton jb1; private JButton jb2; bu() { jf=new JFrame(); jb1=new JButton("jb1"); jb2=new JButton("jb2"); jf.setLayout(new FlowLayout()); jf.setLocation(512,384); jf.setBounds(10,10,200,400); jb1.addActionListener(this); jb2.addActionListener(this); add(jb1); add(jb2); setVisible(true); } public void actionPerformed(ActionEvent e) { JButton temp; temp=(JButton)e.getSource(); if(temp==jb1) System.out.println("jb1"); if(temp==jb2) System.out.println("jb2"); } public static void main(String args[]) { new bu(); } }
package com.myapp.struts; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class Main { public static void main(String[] args) { new Bu(); } } class Bu extends JFrame implements ActionListener { private JButton jb1; private JButton jb2; public Bu() { jb1 = new JButton("jb1"); jb2 = new JButton("jb2"); setLayout(new FlowLayout()); setLocation(512, 384); setBounds(10, 10, 200, 400); jb1.addActionListener(this); jb2.addActionListener(this); add(jb1); add(jb2); setVisible(true); } public void actionPerformed(ActionEvent e) { JButton temp; temp = (JButton) e.getSource(); if (temp == jb1) { System.out.println("jb1"); } if (temp == jb2) { System.out.println("jb2"); } } }
------解决方案--------------------
Do not use javax.swing.JFrame.setLayout() use javax.swing.JFrame.getContentPane().setLayout() instead。
jf.getContentPane().setLayout(new FlowLayout());
jf.getContentPane().add(jb1);
jf.getContentPane().add(jb2);