JAVA控件学习
JAVA很多控件都存放在import javax.swing.*;里边
而触发事件的响应机制则是放在import java.awt.event.*;
消息响应需要添加,如 控件实体.addActionListener(this);当触发的时候会寻找 public void actionPerformed(ActionEvent event)函数,函数名参数结构都是固定的。消息通过ActionEvent event传递,在方法中通过if(event.getSource()==button1)来判断消息源,控件实体.setBounds(x, y, width, height);来设定控件实体的位置大小。
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1 implements ActionListener
{
JButton button1;
JButton button2;
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
SimpleGui1 gui=new SimpleGui1();
gui.go();
}
public void go()
{
JFrame frame=new JFrame();
button1=new JButton("click me");
button2=new JButton("click me");
button1.addActionListener(this);
button2.addActionListener(this);
button1.setBounds(0, 0, 300, 150);
button2.setBounds(0, 150, 300, 150);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setBounds(0, 0, 300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button1)
button1.setText("button is clicked");
if(event.getSource()==button2)
button2.setText("button is clicked");
}
}