从JOptionPane输入,在JFrame中的JTextArea中输出?

时间:2011-11-23 14:39:33

标签: java swing jtextarea joptionpane

如何在接受来自JOptionPane的多个输入的JFrame中创建JTextArea?这甚至可能吗?感谢无论谁帮忙!

1 个答案:

答案 0 :(得分:3)

  1. 创建一个新类并扩展JFrame
  2. 为其添加JTextArea。使其成为成员变量
  3. 在框架上添加一个按钮。在操作方法调用中打开输入对话框
  4. 当对话框返回时,使用其JTextArea方法将文本附加到append(不要忘记检查空/空字符串)
  5. 以下是一个示例程序:

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    
    public class InputTest extends JFrame {
    
        private final JTextArea textarea;
        private final JButton button;
    
        public InputTest(String title) {
            super(title);
    
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            textarea = new JTextArea(5,30);
    
            button = new JButton("new input");
            button.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    String input = JOptionPane.showInputDialog(InputTest.this, "Please enter some text");
    
                    if((input != null) && !input.isEmpty()) {
                        textarea.append(input);
                        textarea.append(System.getProperty("line.separator"));
                    }                
                }
            });
    
            JPanel p = new JPanel(new BorderLayout());
            p.add(textarea, BorderLayout.NORTH);
            p.add(button, BorderLayout.SOUTH);
    
    
            this.getContentPane().add(p);
    
        }
    
        public static void main(String[] args) {
            InputTest it = new InputTest("Input Test");
            it.setSize(200, 200);
            it.setVisible(true);
        }
    
    }