简体   繁体   中英

How JButton of one class append text to JTextArea of another class

I'm trying to add my addText() method (or append() method) of JTextArea of one class to JButton located in another class.

I don't wanna to create new object in JButton or make method static, I have read some answers on this forum but I can't apply it to my code, so please help me to fix this code:

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) {}
    }
}

Use an anonymous class and delete the Button class. I do not see the need of having a class extending from JButton if you're already using JButton in your main code.


Solution

button.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        // setText() or append();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM