我有一个框架,其中有一个TestArea。当我从这个类中追加一些字符串时,会附加String但是当我想从其他类中追加String时,则不会追加String。我创建了一个在TextArea中追加字符串的方法,当我在这个类中调用此方法时,字符串将附加在文本Area上。但是当我从其他类调用此方法时,String不会附加在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()");
}
}
请提出一些想法,为什么这不起作用。
答案 0 :(得分:4)
我认为问题在于你尝试绘制到文本区域的方式是错误的。
在您的操作方法中,您创建了一个SecondClass
的新对象,该对象扩展了MainClass
。这意味着此对象具有自己的textarea对象。但是这个新对象(框架)没有显示,因为你只在setVisibile
中调用MainClass#main
,因此你看不到显示的文字!
简而言之:有两个不同的文字区域!其中一个不可见
答案 1 :(得分:3)
SecondClass 有自己的textArea。所以你可能需要将 MainClass 的textArea传递给 SecondClass 。
public class SecondClass {
private TextArea tArea;
SecondClass(TextArea ta) {
tArea = ta;
}
void printOnTextArea() {
System.out.println("*** printOnTextArea() ***");
tArea.append("call from Second Class in printOnTextArea()");
}
}
您应该像这样更改 MainClass 。
....
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
secondClass = new SecondClass(textArea);
secondClass.printOnTextArea();
}
});
....
希望这会有所帮助...