java 绝对布局及添加按钮文本框

package com.xinhua.testswing;


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.WindowConstants;


public class JTextFieldTest extends JFrame {


public JTextFieldTest() {

Container cont = getContentPane();

//此处要使用绝对布局,所以要取消布局管理器

setLayout(null);
// cont.setLayout(new FlowLayout(3,10,10));

final JTextField jt = new JTextField("aaa", 20);
jt.setBounds(0, 0, 100, 100);
final JButton jb = new JButton("Clear");
jb.setBounds(200, 200, 150, 100);
jt.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent e) {


//此处要在文本框中按下回车键才能显示

jt.setText("触发事件");
}
});

jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jt.setText("");
jt.requestFocus();
}
});

cont.add(jt);
cont.add(jb);

JButton jb2 = new JButton("DDDDs");
jb2.setBounds(400, 400, 150, 50);
cont.add(jb2);

// setSize(800,800);
setBounds(0,0,800,800);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

new JTextFieldTest();

}

}

你可能感兴趣的:(java)