Java Swing 入门
窗口实例,求矩形周长,面积
public class Main {
public static void main(String[] args) {
Window a = new Window();
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Police implements ActionListener {
Window window;
Police(Window window){
this.window = window;
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == window.b1){
double a = Double.parseDouble(window.t1.getText());
double b = Double.parseDouble(window.t2.getText());
// 执行相应的操作
double c = 2*(a+b);
double d = a*b;
window.t3.setText(String.valueOf(c));
window.t4.setText(String.valueOf(d));
}
else if(e.getSource() == window.b2){
window.t3.setText(String.valueOf(""));
window.t4.setText(String.valueOf(""));
}
else if(e.getSource() == window.b3){
window.dispose();
}
}
}
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
JTextField t1,t2,t3,t4;
JButton b1,b2,b3;
JLabel l1,l2,l3,l4;
Police police;
Window(){
setLayout(new FlowLayout());
l1 = new JLabel("矩形的长");
l2 = new JLabel("矩形的宽");
l3 = new JLabel("矩形的周长");
l4 = new JLabel("矩形的面积");
b1 = new JButton("计算");
b2 = new JButton("清空");
b3 = new JButton("退出");
t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);
t4 = new JTextField(20);
police =new Police(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(t4);
add(b1);
add(b2);
add(b3);
b1.addActionListener(police);
b2.addActionListener(police);
b3.addActionListener(police);
setBounds(600,600,620,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}