请问怎么在swing中添加按钮和文本框,然后点击这个按钮后读取文本框里的内容并将自己和文本框删除?
发布网友
发布时间:2022-05-16 01:46
我来回答
共1个回答
热心网友
时间:2023-10-08 20:37
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
public class FrameTest extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("确认");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String string = textField.getText();
if(!string.equals("")){
lblNewLabel.setText(string);
contentPane.remove(textField);
contentPane. remove(btnNewButton);
contentPane.updateUI();
}
}
});
btnNewButton.setBounds(60, 10, 297, 50);
contentPane.add(btnNewButton);
textField = new JTextField();
textField.setBounds(60, 70, 297, 85);
contentPane.add(textField);
textField.setColumns(10);
lblNewLabel= new JLabel("");
lblNewLabel.setBounds(60, 165, 297, 56);
contentPane.add(lblNewLabel);
}
}