我正在尝试将一个类的 JTextArea
的 addText()
方法(或 append()
方法)添加到 JButton
位于另一个类中。
我不想在 JButton
中创建新对象或使方法静态,我已阅读此论坛上的一些答案,但我无法将其应用到我的代码中,所以请帮助我修复此代码:
class Frame extends JFrame {
public Frame() {
TextArea textarea = new TextArea();
Panel panel = new Panel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(dim());
setLayout(new BorderLayout());
add(textarea, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
setVisible(true);
pack();
setLocationRelativeTo(null);
}
private Dimension dim() {
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension d = kit.getScreenSize();
int width = (int)(d.getWidth() / 2);
int height = (int)(d.getHeight() / 2);
return new Dimension(width, height);
}
}
class TextArea extends JTextArea {
public TextArea() {}
public void addText(String s) {
append(s);
}
}
class Panel extends JPanel {
public Panel() {
Button button = new Button();
button.setText("Start");
button.addActionListener(new Button());
add(button);
}
class Button extends JButton implements ActionListener {
public Button() {}@Override
public void actionPerformed(ActionEvent e) {}
}
}
最佳答案
使用匿名类并删除Button
类。如果您已经在主代码中使用了 JButton
,我认为不需要从 JButton
扩展类。
解决方案
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
// setText() or append();
}
});
关于java - 一个类的 JButton 如何将文本附加到另一类的 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34238436/