Java Swing

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);
        }
    }
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值