如何在Java的窗口中添加组件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Mr_wxc/article/details/93486009

如何在Java中的窗口中添加组件

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class addZJ extends Frame implements ActionListener{
	Button btn1,btn2;
	TextField tf1,tf2,tf3;
	TextArea area;
	addZJ(){
		super();
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		setSize(350, 250);
		setLocation(200, 200);
		setFont(new Font("Arial", Font.PLAIN, 12));
		setLayout(new FlowLayout());
		area=new TextArea(6,40);
		tf2=new TextField(10);
		tf3=new TextField(10);
		btn1=new Button("show");
		btn2=new Button("exit");
		tf1=new TextField(20);
		add(area);
		add(new Label("username"));
		add(tf2);
		add(new Label("tell"));
		add(tf3);
		add(tf1);
		add(btn1);
		add(btn2);
		tf2.addActionListener(this);
		tf3.addActionListener(this);
		btn1.addActionListener(this);
		btn2.addActionListener(this);
		setVisible(true);
	}

	public static void main(String[] args) {
		new addZJ();
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==btn1) {
			tf1.setText("你按下了"+e.getActionCommand()+"按钮");
			area.append("用户名:"+tf2.getText()+"\n");
			area.append("电话:"+tf3.getText()+"\n");
		}
		
		if(e.getSource()==btn2) {
			dispose();
			}
		}
	}

运行结果如下: 

经过测试运行正常,可以放心使用 

猜你喜欢

转载自blog.csdn.net/Mr_wxc/article/details/93486009