하나의 TestArea가있는 프레임이 하나 있습니다. 이 클래스의 문자열을 추가하면 String이 추가되지만 다른 클래스의 String을 추가하려면 String이 추가되지 않습니다. TextArea에 문자열을 추가하는 한 가지 방법을 만들었습니다.이 클래스에서이 메서드를 호출하면 문자열이 텍스트 영역에 추가됩니다. 하지만 다른 클래스에서이 메서드를 호출하면 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) 빨리,이 [SSCCE] (http://sscce.org/)을 게시 할 수 있습니다. 2) Swing (예 :'JFrame' /'JButton')과 AWT (예 :'Canvas') 구성 요소를 섞지 마십시오. 3) * "아이디어를주십시오."* Q & A 사이트이므로 ***에 질문 할 것입니다. *** 4)'null '레이아웃을 사용하지 말고'setBounds()'- 그것은 네이티브 PLAF를 사용할 때 실제 세계에서 * 특히 * 채워질 것입니다! –