gpt4 book ai didi

java - 使用 GUI 打印字符串

转载 作者:行者123 更新时间:2023-12-02 10:27:12 24 4
gpt4 key购买 nike

我是 Java 新手。我正在家里练习,以便在计算机科学课上取得更好的成绩,但我在尝试编写的某些代码方面遇到了问题。下面粘贴的代码应该打印“Joketeller”类中“public static void Associate()”中找到的五个选项之一。但是,当我运行 GUI 并单击按钮进行测试时,应显示响应的文本框不会执行任何操作。

public class GUIWindow extends JFrame {
private Joketeller robot= new Joketeller();
private JLabel speakerlabel = new JLabel("Joke");
private JLabel MarcoLabel= new JLabel ("Marco");
private JTextField speakerfield= new JTextField ("Enter Joke Here");
private JTextField Marcofield= new JTextField ("");
private JButton Jokebutton=new JButton("Recite Joke >>>");

public GUIWindow() {
JPanel dataPanel= new JPanel(new GridLayout(6,2,12,16));
dataPanel.add(speakerlabel);
dataPanel.add(MarcoLabel);
dataPanel.add(speakerfield);
dataPanel.add(Marcofield);

JPanel buttonPanel= new JPanel();
buttonPanel.add(Jokebutton);
Container container = getContentPane();
container.add(dataPanel,BorderLayout.CENTER);
container.add(buttonPanel,BorderLayout.SOUTH);
Jokebutton.addActionListener(new JokeListener());
}

private class JokeListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String input=speakerfield.getText();
robot.setJoke(input);
String Response= Joketeller.getResponse();
Marcofield.setText(Response);


}
}
}

这是我的 Joketeller 类(class):

public class Joketeller {


private static String Marco;
private static String Response;
static int i= (int)(Math.random()*((5-1)+1))+1;
static String r;

public void setMarco(String Joke ) {
Marco=Joke;
}

public void setJoke(String Joke) {
Marco=Joke;
}


public String getJoke() {
return Marco;
}

public static String getMarco() {
return Marco;
}

public static void associate(){
if(i==1)
r= "Connect Angie";
else if(i==2)
r= "*Cloud Laugh*";
else if(i==3)
r= "Community";
else if(i==4)
r=getMarco();
else if(i==5)
r= "Indeed!";
Response=r;

}

public static String getResponse() {
return Response;
}

}

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

请检查以下链接:

http://leepoint.net/notes-java/GUI/components/30textfield/11textfield.html

基本上你应该这样做

JTextField myOutput = new JTextField(16);

其中 myOutput 是您选择的 JTextField 变量,16 是 GUI 中 JTextField 的长度。显示消息:

myOutput.setText("一些文本");您还可以在声明文本字段的同时初始化 JTextField 的值

JTextField myOutput = new JTextField("someInitialValue", 20);代码不言而喻

希望这有帮助

关于java - 使用 GUI 打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863083/

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