1つのフレームにTestAreaが1つあります。このクラスからいくつかの文字列を追加するとStringが追加されますが、他のクラスのStringを追加する場合はStringが付加されません。 TextAreaに文字列を追加するメソッドを1つ作成しました。このメソッドをこのクラスで呼び出すと、文字列がテキストエリアに追加されます。しかし、私が他のクラスからこのメソッドを呼び出すと、Stringは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);
}
});
}
}
コード(SecondClass):これが機能しない理由
import com.grissserver.MainClass;
public class SecondClass extends MainClass{
void printOnTextArea() {
System.out.println("*** printOnTextArea() ***");
super.appendToTextArea("call from Second Class in printOnTextArea()");
}
}
は、いくつかのアイデアを教えてください。
1 ...このことができます願っています。 2)Swing(例えば、 'JFrame' /' JButton')とAWT(例えば 'Canvas')コンポーネントを混在させないでください。 3)* "いくつかのアイディアを教えてください" * Q&Aサイトであれば***に質問することができます*** 4) 'null'レイアウトと' setBounds() 'を使わない - 実際のPLAFを使用している場合は、実際の世界では*特に*大きくなります! –