gpt4 book ai didi

java - 使用 JButton 和 JTabbedPane 从 JTextArea 获取文本

转载 作者:行者123 更新时间:2023-11-29 03:19:34 25 4
gpt4 key购买 nike

这里的新手尝试使用 JTabbedPane 制作一个简单的 GUI。我查看了很多示例,但一直无法找到解决方案。基本上,我试图将字符串打印到 JTextArea。虽然看起来很简单,但我一直无法让所有东西一起工作。我了解局部变量和全局变量之间的区别,但我认为这就是我的问题所在。任何指导将不胜感激。 *请注意,我们无法为此项目使用布局管理器。

下面的代码表示具有 JButton 和 JTextArea 的选项卡的一部分。

    //Text area that shows details. Scrolls.
JTextArea areaDeets = new JTextArea();
areaDeets.setBounds(65, 300, 250, 300 );
areaDeets.setText("");
JScrollPane scroll = new JScrollPane (areaDeets);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(areaDeets);
panel2.add(scroll);
areaDeets.addActionListener(new StopTest());

//Stop button--stops tests when pressed.
JButton stop = new JButton("Stop");
stop.setBounds(215, 650, 100, 40);
panel2.add(stop);
stop.addActionListener(new StopTest());

下面的代码是调用ActionListener的方法。

//Panel 1 - Stop, shows that the test has been stopped
static class StopTest implements ActionListener{
public void actionPerformed(ActionEvent e){
String stop = "The test has been stopped";
areaDeets.setText(stop);
panel2.repaint();

}
}

编辑:代码无法编译。 Eclipse 说我不能在 JTextField 上调用 addActionListener。

最佳答案

您可以将 JTextArea 的引用传递给 ActionListener 的构造函数:

  public class StopTest implements ActionListener {

private JTextArea area;

public StopTest(JTextArea area) {
this.area = area;
}

public void actionPerformed(ActionEvent e) {
String stop = "The test has been stopped";
area.setText(stop);
}
}

关于java - 使用 JButton 和 JTabbedPane 从 JTextArea 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24497295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com