java - 使用按钮将文本从文本字段移动到文本区域

标签 java user-interface textarea textfield

此代码编译并运行,但它不会从文本字段复制文本,然后将其放入文本区域。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class NameGameFrame extends JFrame
{

    static JTextField textfield = new JTextField(20);
    static JTextArea  textarea = new JTextArea(30,30);

    public static void main( String[] args)
    {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Name Game");
        frame.setLocation(500,400);
        frame.setSize(800,800);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        JLabel label = new JLabel("Enter the Name or Partial Name to search:");
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(2,2,2,2);

        panel.add(label,c);

        c.gridx = 0;
        c.gridy = 1;
        panel.add(textarea,c);

        JButton button = new JButton("Search");
        c.gridx = 1;
        c.gridy = 1;
        panel.add(button,c);

        c.gridx = 1;
        c.gridy = 0;
        panel.add(textfield,c);

        frame.getContentPane().add(panel, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);

    }
        static class Action implements ActionListener
        {
        public void actionPerformed(ActionEvent e)
        {

           //This is the code that should  perform the task
            String name  = textfield.getText();
            textarea.append(name);
        }
    }
}

我是 Java 编程的新手,如果我的问题过于简单,我深表歉意。

最佳答案

在声明按钮之后将下面的代码附加到您的程序中
IE。 JButton button = new JButton("Search");

button.addActionListener(new ActionAdapter()
{
     public void actionPerformed(ActionEvent ae)
     {
          textarea.setText(textfield.getText());
     }
});

关于java - 使用按钮将文本从文本字段移动到文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059915/

相关文章:

java - java中的null或空字符串比较?或者是其他东西?

java - 我们可以阻止Excel工作表的某个单元格进行删除操作吗?

user-interface - 冰镇 : How to create window in fullscreen?

使用-webkit-overflow-scrolling : touch 时隐藏的 iOS textarea 文本

javascript - 逐行读取文本区域中的文本

html - textarea 在其他元素之后填充未使用的垂直空间 - 在叠加层中

java - 昆德拉使用 getResultList() 方法时抛出空指针异常

java - 如何将 Java 中的 URI 解析和解码为 URI 组件?

windows - 为命令行程序生成 GUI 的工具

html - 网络应用程序模板