![](/img/trans.png)
[英]How to make a JButton add text from one JTextArea to another JTextArea
[英]How JButton of one class append text to JTextArea of another class
我试图将我的一个类的JTextArea
的addText()
方法(或append()
方法) 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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.