编写一个程序,使之有如图所示的界面,并实现简单的控制:按Clear按钮清除文本框内容,按copy按钮将sorce文本框的内容复制到target文本框内;按close关闭程序。
代码如下:
package com.tcz.exersise5;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Exercise9_1 extends JFrame{
public static void main(String[] args) {
Exercise9_1 e=new Exercise9_1();
}
public Exercise9_1(){
setTitle("My Frame"); //窗体名
setSize(600,300); //窗体大小
Container c=getContentPane();
c.setLayout(new GridLayout(2, 1));
setLocation(800,500); //设置窗体位置
//顶部面板
JPanel top=new JPanel();
JPanel bot=new JPanel();
JLabel l1=new JLabel("Sorce");
l1.setFont(new Font("Times new roman", Font.BOLD, 18)); //设置字体样式
JLabel l2=new JLabel("Target");
l2.setFont(new Font("Times new roman", Font.BOLD, 18));
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
top.add(l1);
top.add(t1);
top.add(l2);
top.add(t2);
top.setLayout(new FlowLayout(FlowLayout.CENTER));
c.add(top);
//添加按钮
JButton jb1=new JButton("Clear");
JButton jb2=new JButton("Copy");
JButton jb3=new JButton("Close");
bot.add(jb1);
bot.add(jb2);
bot.add(jb3);
c.add(bot);
//添加事件监听
jb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
t1.setText("");
t2.setText("");
}
});
jb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str=t1.getText();
t2.setText(str);
}
});
jb3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
运行结果
1.清除
2.复制
3.退出
怎么样,很有意思吧!