【问题标题】:How to make a JButton add text from one JTextArea to another JTextArea如何使 JButton 将文本从一个 JTextArea 添加到另一个 JTextArea
【发布时间】:2021-08-12 14:35:55
【问题描述】:

我希望能够在 JTextArea 't1' 中输入文本,然后按下 JButton 'b1' 这会将文本从 't1' 添加到 JTextArea 't2'。我在 actionPerformed 方法中已经有一些代码,但它似乎不起作用,我不知道为什么。没有错误消息,而是代码根本不起作用。在我的代码示例中,我只包含了创建按钮的方法、JTextAreas 和动作侦听器方法。抱歉,如果我没有完全正确地提出这个问题,这是我在这个平台上的第一个问题。

private JTextArea t1, t2;
private JButton b1, b2;
private final static String newline = "\n";

UserInterface()
{
    t1 = new JTextArea();
    t1.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(15, 15, 15, 15)));
    t1.setLineWrap(true);
    t1.setBounds(470, 25, 280, 330);
    t2 = new JTextArea("Enter Addresses Here");
    t2.setBorder(BorderFactory.createCompoundBorder(border2, BorderFactory.createEmptyBorder(15, 15, 15, 15)));
    t2.setLineWrap(true);
    
    b1 = new JButton("Click");
    b1.setBackground(Color.decode("#95edc5"));
    b1.setBorderPainted(false);
    b1.setOpaque(true);
    b1.setText("View Addresses");
    b1.setForeground(Color.decode("#2f4d3f"));
    b1.setFont(new Font("Helvetica", Font.PLAIN, 18));
    b1.addActionListener(this);
    b1.setBounds(470, 395, 280, 63);
}

@Override
public void actionPerformed(ActionEvent e)
{
    String text = t2.getText();
    
    if (e.getActionCommand().equals("Click"))
    {
        t1.append(text + newline);
    }
}

【问题讨论】:

    标签: java swing awt


    【解决方案1】:

    走线: b1.setText("查看地址") 因为它现在是 buttonName,而不是 Click,因为 actionCommand 事件 您正在检查的平等

    否则,这种方法应该可以解决您的问题

      @Override
      public void actionPerformed(ActionEvent e)
      {
           String text = t2.getText();
    
           if (e.getSource() == b1)
           {
             t1.append(text +  newline);
           }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-15
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2014-12-11
      相关资源
      最近更新 更多