gpt4 book ai didi

Java:无法从其他类在 TextArea 上打印

转载 作者:行者123 更新时间:2023-12-02 05:01:03 25 4
gpt4 key购买 nike

我有一个框架,其中有一个 TestArea。当我附加此类中的一些字符串时,则会附加字符串,但是当我想附加其他类中的字符串时,则不会附加字符串。我创建了一种在 TextArea 中附加字符串的方法,当我在此类中调用此方法时,字符串将附加到文本区域中。但是当我从其他类调用此方法时,字符串不会附加到 TextArea 上。

代码(主类):

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()");
}
}

请给出一些想法,为什么这不起作用。

最佳答案

我认为问题在于您尝试绘制文本区域的方式是错误的。

在您的操作方法中,您创建一个扩展MainClassSecondClass新对象。这意味着该对象有自己的 textarea 对象。但是这个新的对象(frame)并没有显示出来,因为你只在MainClass#main中调用了setVisibile,因此你看不到显示的文本!

简而言之:有两个不同的文本区域!其中之一是不可见的

关于Java:无法从其他类在 TextArea 上打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9800415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com