import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo extends JPanel implements ActionListener
{
JButton b1,b2;
String message="";
int row,col;
public ButtonDemo()
{
setLayout(null);
b1=new JButton("First Button");
b1.setMnemonic(KeyEvent.VK_CONTROL|KeyEvent.VK_F);
b1.setActionCommand("first");
b2=new JButton("Second Button");
b2.setMnemonic(KeyEvent.VK_S);
b2.setActionCommand("second");
b1.addActionListener(this);
b2.addActionListener(this);
b1.setBounds(100,20,100,100);
b2.setBounds(300,20,100,100);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("first"))
{
message=new String("第一个按钮被按下!");
row=150;
col=150;
}
else if(e.getActionCommand().equals("second"))
{
message=new String("第二个按钮被按下!");
row=150;
col=150;
}
repaint();
}
public static void main(String args[])
{
JFrame jf=new JFrame("按钮测试");
jf.getContentPane().add(new ButtonDemo());
jf.setSize(500,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(message,col,row);
repaint();
}
}
这是我以前学习时打的代码 你看看 我布局用的null 大小用setBounds控制的
子非鱼,安知鱼之江湖?子非我,安知我之功夫 http://20681.