gpt4 book ai didi

Java GUI 按钮不会将字符串打印到界面

转载 作者:行者123 更新时间:2023-12-01 20:13:06 25 4
gpt4 key购买 nike

GUI 初学者在这里。

我的问题不是创建 GUI 界面,而是让 2 个按钮在界面内的 JTextArea 中打印字符串。
第一个“已学习”按钮从数组中获取随机元素并打印它。第二个按钮“清除”应该在按下时打印一个字符串我有两个按钮的 Action 监听器,但仍然无法完全理解它。

感谢您的宝贵时间。

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


public class GUI extends JFrame {


String [] sentences = {"Random sentence 1", "random sentence 2", "random sentence 3", "random sentence 4", random sentence 5", "random sentence 6"};


private Container contents;
JButton learned = new JButton("Learned");
JButton clear = new JButton("Clear");
JTextArea clearDisplay;


public GUI()
{
super ("GUI"); //title bar text

contents = getContentPane ();
contents.setLayout(new FlowLayout()); //make buttons appear

//set the layout manager

//instantiate buttons
learned = new JButton("I Learned");
clear = new JButton("Clear");

//add components to window
contents.add(learned);
contents.add(clear);



//instantiate event handler
ButtonHandler bh = new ButtonHandler ();

//add event handler as listener for both buttons
learned.addActionListener (bh);
clear.addActionListener(bh);

setSize (400, 200); //size of window
setVisible (true); //see the window

}


public class ButtonHandler implements ActionListener
{
//implement ActionPerformed method

public void actionPerformed(ActionEvent e)
{
Container contentPane = getContentPane();
if (e.getSource() == learned)
{
String random = (sentances[new Random().nextInt(sentances.length)]); //random from array
JTextArea learned = new JTextArea(random);
}
else if (e.getSource() == clear)
{
JTextArea clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here.");
}

}

}

public static void main(String[] args)
{
GUI basicGui = new GUI ();
basicGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //program exits on close
}

}

最佳答案

您的问题在这里:

else if (e.getSource() == clear)           
{
JTextArea clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here.");
}

您正在创建一个永远不会添加到 GUI 的新 JTextArea。你应该这样写:

else if (e.getSource() == clear)           
{
clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here.");
}

并将其添加到 GUI。

您还应该考虑一种不同的方法:首先创建 JTextField,将其添加到 GUI,然后仅更改上面代码中的文本。

此外,您这里还有一些拼写错误:

String random = (sentances[new Random().nextInt(sentances.length)]);

关于Java GUI 按钮不会将字符串打印到界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379711/

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