Java 字符串变量不会显示在JFrame中
当我运行此程序时,变量字符串结果将不会显示在JPanel outpanel中。有人能告诉我为什么吗?我已经尝试了几个小时的谷歌搜索和静态等实验,但我相信静态作为一个答案是不友好的,即使它解决了它Java 字符串变量不会显示在JFrame中,java,swing,arraylist,jframe,Java,Swing,Arraylist,Jframe,当我运行此程序时,变量字符串结果将不会显示在JPanel outpanel中。有人能告诉我为什么吗?我已经尝试了几个小时的谷歌搜索和静态等实验,但我相信静态作为一个答案是不友好的,即使它解决了它 import java.util.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import java.awt.*; import java.aw
import java.util.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.*;
public class AProgram extends JFrame
implements WindowListener, ActionListener {
public JButton gbt = new JButton("GO");
public JPanel outpanel = new JPanel();
public ArrayList<String> responses;
public String result;
public AProgram() {
super ("Program");
}
public void init() {
//output
outpanel.setOpaque(true);
outpanel.setPreferredSize(new Dimension(600, 75));
outpanel.setBorder(new LineBorder(Color.black, 2));
JLabel jl = new JLabel();
jl.setText(result);
outpanel.add(jl);
this.add("South", outpanel);
//press-button - does NOT sit in a panel.
gbt.setBackground(Color.GREEN);
gbt.setPreferredSize(new Dimension(75, 75));
gbt.setBorder(new LineBorder(Color.black, 2));
this.add("East", gbt);
//all
gbt.addActionListener(this);
this.addWindowListener(this);
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
public void actionPerformed (ActionEvent evt) {
String input = "A Lion is ";
finishSentence(input);
}
public void windowClosing (WindowEvent e) {
this.setVisible(false);
this.dispose();
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public String finishSentence(String inwds) {
responses = new ArrayList<String>();
responses.add(0, "a bookish creature");
responses.add(1, "quiet and unassuming");
responses.add(2, "King of the Jungle");
String result = inwds + responses.get(2);
return result;
}
public static void main (String[] args) {
AProgram me = new AProgram();
me.init();
}
}
在init方法中,您将jl的文本设置为null
然后在actionPerformed中调用finishSequence方法,该方法返回一个字符串,但未将其分配给任何变量或元素
在actionPerformed中再次调用jl.setText
:D以及使我的JLabel类级数据正常工作。哦,天哪,谢谢你。我已经被困在这上面三个小时了!如果有助于解决问题,请给出答案。我还建议您检查您的代码,并为其选择答案。使用逻辑一致的代码格式样式!代码缩进旨在帮助人们遵循程序流程。请记住,不重写WindowListener方法,只需在WindowClose方法中使用frameInstance.setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE,即可获得与您尝试实现的效果相同的效果。这1行相当于这10行:-
public void actionPerformed (ActionEvent evt) {
String input = "A Lion is ";
jl.setText(finishSentence(input));
}