|
发表于 2021-11-9 20:31:03
|
显示全部楼层
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyEvent;
- import java.util.EventObject;
- public class SwingTextFieldView extends JPanel implements ActionListener {
- public static void main(String[] args) {
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- createAndShowGUI();
- }
- });
- }
- protected JTextField textField;
- protected JTextArea textArea;
- protected JButton enter;
- private final static String newline = "\n";
- public SwingTextFieldView() {
- setLayout(new BorderLayout()); //设置为边界布局模式
- textField = new JTextField(30);
- textField.addActionListener(this);
- enter = new JButton("Enter");
- enter.addActionListener(this);
- enter.setMnemonic(KeyEvent.VK_E);
- add(enter,BorderLayout.EAST); //将按钮放置此面板中的东侧(右侧)
- textArea = new JTextArea(10, 40);
- textArea.setEditable(false);
- JScrollPane scrollPane = new JScrollPane(textArea);
- GridBagConstraints c = new GridBagConstraints();
- c.gridwidth = GridBagConstraints.REMAINDER;
- c.fill = GridBagConstraints.HORIZONTAL;
- add(textField, c);
- c.fill = GridBagConstraints.BOTH;
- c.weightx = 1.0;
- c.weighty = 1.0;
- add(scrollPane, c);
- }
- public void actionPerformed(ActionEvent evt) {
- String text = textField.getText();
- if(evt.getSource() == enter) {
- textArea.append(text + newline);
- textField.selectAll();
- textArea.setCaretPosition(textArea.getDocument().getLength());
- }
- }
- private static void createAndShowGUI() {
- JFrame frame = new JFrame("SwingTextFieldView");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.add(new TextDemo());
- SwingTextFieldView newContenPanw = new SwingTextFieldView();
- newContenPanw.setOpaque(true);
- frame.setContentPane(newContenPanw);
- frame.pack();
- frame.setVisible(true);
- }
- }
复制代码
|
|