可變String
結果不會在JPanel
outpanel顯示,當我運行該程序顯示。有人能告訴我爲什麼嗎?我嘗試過使用Google搜索和static
等幾小時試驗,但我相信static
不是OO友好的答案,即使它確實解決了它。字符串變量將不顯示是不會在JFrame中
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();
}
}
使用邏輯和一致的代碼格式風格!代碼縮進旨在幫助人們遵循程序流程。 – 2014-09-05 07:56:18
請記住,您可以簡單地使用'frameInstance.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)',而不是覆蓋'WindowListener'方法,與'windowClosing()'方法試圖實現的效果相同。這1行相當於那10行:-) – 2014-09-05 08:12:12