【发布时间】:2014-09-05 05:11:31
【问题描述】:
当我运行这个程序时,变量String result 不会显示在JPanel outpanel 中。有人能告诉我为什么吗?我已经尝试使用谷歌搜索和尝试static 等几个小时,但我相信static 不是面向对象的答案,即使它确实解决了它。
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();
}
}
【问题讨论】:
-
使用逻辑一致的代码格式风格!代码缩进旨在帮助人们遵循程序流程。
-
请记住,可以简单地使用
frameInstance.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE),而不是覆盖WindowListener方法,以达到与windowClosing()方法相同的效果。这 1 行相当于那 10 行 :-)
标签: java swing arraylist jframe