我有一個框架,其中有一個TestArea。當我從這個類中追加一些字符串時,字符串被追加,但是當我想從其他類追加字符串時,字符串不會被追加。我創建了一個方法來在TextArea中追加字符串,當我在這個類中調用這個方法時,字符串被附加在文本區域上。但是當我從其他類調用此方法時,字符串不會附加在TextArea上。Java:無法在其他類的TextArea上打印
碼(MainClass):
public class MainClass {
private JFrame frame;
private TextArea textArea;
private Font font;
private JButton button1;
private JButton button2;
private SecondClass secondClass;
public MainClass() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame = new JFrame("XXX");
frame.setBounds(200, 200, 600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
button1 = new JButton("Button1");
font = new Font("Arial", Font.BOLD, 13);
button1.setFont(font);
button1.setBounds(4, 4, 289, 30);
button2 = new JButton("Button2");
button2.setFont(font);
button2.setBounds(300, 4, 289, 30);
font = null;
textArea = new TextArea();
textArea.setBounds(4, 38, 585, 322);
textArea.setEnabled(true);
font = new Font("Arial", Font.PLAIN, 13);
textArea.setFont(font);
frame.add(button1);
frame.add(button2);
frame.add(textArea);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
textArea.append("*** I am in actionPerformed() ***\n");
appendToTextArea("Call from actionPerformed() method\n");
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
secondClass = new SecondClass();
secondClass.printOnTextArea();
}
});
} catch (Exception e) {
textArea.append(e.toString());
}
}
public void appendToTextArea(String str) {
System.out.println(str+"\n");
textArea.append(str+"\n"); //this line not work when I call this method from other class
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainClass window = new MainClass();
window.frame.setVisible(true);
}
});
}
}
碼(二等):
import com.grissserver.MainClass;
public class SecondClass extends MainClass{
void printOnTextArea() {
System.out.println("*** printOnTextArea() ***");
super.appendToTextArea("call from Second Class in printOnTextArea()");
}
}
請給一些想法,爲什麼這是行不通的。
1)爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。 2)不要將Swing(例如'JFrame' /'JButton')與AWT(例如'Canvas')組件混合使用。 3)*「請給出一些想法..」*由於這是一個問答網站,它可能會支付***問一個問題*** 4)不要使用'null'佈局和'setBounds()' - 它會在現實世界中充斥,特別是在使用本地PLAF時! – 2012-03-21 07:55:44