user5671675
user5671675

Reputation:

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

Upvotes: 0

Views: 142

Answers (1)

Yassin Hajaj
Yassin Hajaj

Reputation: 21995

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

Upvotes: 2

Related Questions