英文:
How to Add text to JTextArea
问题
import javax.swing.*;
import java.awt.event.*;
class Boton extends JFrame implements ActionListener {
    JButton boton;
    JTextArea textArea = new JTextArea();
    JLabel etiqueta = new JLabel();
    public Boton() {
        setLayout(null);
        boton = new JButton("Escribir");
        boton.setBounds(100, 150, 100, 30);
        boton.addActionListener(this);
        add(boton);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == boton) {
            try {
                String texto = textArea.getText();
                etiqueta.setText(texto);
                Thread.sleep(3000);
                System.exit(0);
            } catch (Exception excep) {
                System.exit(0);
            }
        }
    }
}
public class Main {
    public static void main(String[] ar) {
        Boton boton1 = new Boton();
        boton1.setBounds(0, 0, 450, 350);
        boton1.setVisible(true);
        boton1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
英文:
Im creating a programme using java. I want the user to enter some text, then push the button so the text entered shows in the label. However, I have 2 problems. First, the text are isn´t displaying when I execute the app. Second, I don´t know how to allow the user to type in the area. Im new in java so that´s why Im asking. Here is the code. Thank you.
import javax.swing.*;
import java.awt.event.*;
class Boton extends JFrame implements ActionListener {
    JButton boton;
    JTextArea textArea = new JTextArea();
    JLabel etiqueta = new JLabel();
    public Boton() {
        setLayout(null);
        boton = new JButton("Escribir");
        boton.setBounds(100, 150, 100, 30);
        boton.addActionListener(this);
        add(boton);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == boton) {
            try {
                String texto = textArea.getText();
                etiqueta.setText(texto);
                Thread.sleep(3000);
                System.exit(0);
            } catch (Exception excep) {
                System.exit(0);
            }
        }
    }
}
public class Main{
    public static void main(String[] ar) {
        Boton boton1 =new Boton();
        boton1.setBounds(0,0,450,350);
        boton1.setVisible(true);
        boton1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
答案1
得分: 3
问题:
- 您从未将JTextArea添加到您的GUI中,如果它不显示,用户将无法直接与其交互。
 - 您在Swing事件线程上调用了
Thread.sleep,这将使整个应用程序进入休眠状态,这意味着您添加的文本将不会显示。 - 其他问题包括使用了空布局和setBounds —— 避免这样做。
 
解决方案:
- 设置JTextArea的列和行属性,以便其大小合适。
 - 由于您的JTextArea的文本要放入一个JLabel中,而JLabel只允许单行文本,我想您是否真的应该使用JTextArea。也许使用JTextField会更好,因为它允许用户输入但只有一行文本。
 - 将JTextArea添加到JScrollPane(实际上是它的视口),然后将其添加到您的GUI中。然后用户就可以直接与它交互。最简单的方法是将JTextArea传递给JScrollPane的构造函数。
 - 去掉
Thread.sleep,而是如果想要使用延迟,可以使用Swing定时器。在这里查看教程:链接 
示例代码:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Main2 {
    public static void main(String[] args) {
        // 以线程安全的方式创建GUI
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
    private static void createAndShowGui() {
        BotonExample mainPanel = new BotonExample();
        JFrame frame = new JFrame("GUI");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}
class BotonExample extends JPanel {
    private JLabel etiqueta = new JLabel(" ");
    private JButton boton = new JButton("Escribir");
    // jtext area的行和列属性
    private int rows = 5;
    private int columns = 30;
    private JTextArea textArea = new JTextArea(rows, columns);
    public BotonExample() {
        // alt-e将激活按钮
        boton.setMnemonic(KeyEvent.VK_E);
        boton.addActionListener(e -> {
            boton.setEnabled(false); // 防止按钮重新激活
            String text = textArea.getText();
            etiqueta.setText(text);
            // 延迟计时器
            int delay = 3000;
            Timer timer = new Timer(delay, e2 -> {
                // 获取当前窗口并关闭它
                Window window = SwingUtilities.getWindowAncestor(boton);
                window.dispose();
            });
            timer.setRepeats(false);
            timer.start();  // 启动计时器
        });
        // 创建要添加到GUI的JPanels
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 5));
        topPanel.add(new JLabel("Etiqueta:"));
        topPanel.add(etiqueta);
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(boton);
        JScrollPane scrollPane = new JScrollPane(textArea);
        // 使用布局管理器并添加组件
        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.PAGE_START);
        add(scrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }
}
英文:
Problems:
- You never add the JTextArea into your GUI, and if it doesn't show, a user cannot directly interact with it.
 - You are calling 
Thread.sleepon the Swing event thread, and this will put the entire application to sleep, meaning the text that you added will not show. - Other issues include use of null layouts and setBounds -- avoid doing this.
 
Solutions:
- Set the JTextArea's column and row properties so that it sizes well.
 - Since your JTextArea's text is going into a JLabel, a component that only allows a single line of text, I wonder if you should be using a JTextArea at all. Perhaps a JTextField would work better since it allows user input but only one line of text.
 - Add the JTextArea to a JScrollPane (its viewport actually) and add that to your GUI. Then the user can interact directly with it. This is most easily done by passing the JTextArea into a JScrollPane's constructor.
 - Get rid of the 
Thread.sleepand instead, if you want to use a delay, use a Swing Timer. check out the tutorial here 
For example:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.KeyEvent;	
import javax.swing.*;
public class Main2 {
public static void main(String[] args) {
// create GUI in a thread-safe manner
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
BotonExample mainPanel = new BotonExample();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class BotonExample extends JPanel {
private JLabel etiqueta = new JLabel(" ");
private JButton boton = new JButton("Escribir");
// jtext area rows and column properties
private int rows = 5;
private int columns = 30;
private JTextArea textArea = new JTextArea(rows, columns);
public BotonExample() {
// alt-e will activate button
boton.setMnemonic(KeyEvent.VK_E);
boton.addActionListener(e -> {
boton.setEnabled(false); // prevent button from re-activating
String text = textArea.getText();
etiqueta.setText(text);
// delay for timer
int delay = 3000;
Timer timer = new Timer(delay, e2 -> {
// get current window and dispose ofit
Window window = SwingUtilities.getWindowAncestor(boton);
window.dispose();
});
timer.setRepeats(false);
timer.start();  // start timer
});
// create JPanels to add to GUI
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 5));
topPanel.add(new JLabel("Etiqueta:"));
topPanel.add(etiqueta);
JPanel bottomPanel = new JPanel();
bottomPanel.add(boton);
JScrollPane scrollPane = new JScrollPane(textArea);
// use layout manager and add components
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
}
答案2
得分: -1
textarea.setText("文本");  // 这会将文本插入到文本区域
textarea.setVisible(true); // 这会显示文本区域,以便您可以在其中输入
textarea.setSize(500, 500); // 设置文本区域的大小,以便实际显示
用户应该能够在显示文本区域时输入内容,然后只需使用 `getText` 来获取文本
英文:
textarea.setText("Text");  // this will insert text into the text area
textarea.setVisable(true); // this will display the text area so you can type in it
textarea.setSize(500,500); // set size of the textarea so it actually shows
The user should be able to type in the TA when it is displayed and just do a getText to pull the text
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论