Как я могу добавить текст в JTextArea с собственным классом ActionListener после нажатия кнопок - PullRequest
0 голосов
/ 28 мая 2019

Эй, я хочу JFrame, который должен иметь кнопки «LeftButton» и «RightButton» и JTextArea. После того, как я нажму одну из двух, я хочу, чтобы JTextArea записал, какие кнопки были нажаты в новой строке. Для этого я хочу использовать класс MyActionListener с ссылками на JTextArea, который реализует Actionlistener.

Я попытался дать ActionPerformed JTextArea и понял, что должен создавать сеттеры самостоятельно. Затем я понял, что класс MyActionListener требует также объект типа JTextArea, который такой же, как в классе JFrame. Затем я узнал, что мне нужно обновить JTextArea в классе JFrame, и вот я сейчас немного застрял. Я попытался поместить сеттеры в класс JFrame и вызвать их из MyActionListener безуспешно, и я попытался сделать что-то вроде A_18_c.south = south

package Aufgabe_18;

import javax.swing.*;
import java.awt.*;

public class A_18_c extends JFrame {
    private Button LeftButton;
    private Button RightButton;
    private JScrollPane scroll;
    private JTextArea south;
    private MyActionListener MAL;

    public static void main(String[] args) {
        A_18_c l = new A_18_c("Aufgabe18c");
    }


    public A_18_c(String title) {
        super(title);
        setSize(300, 150);
        this.setLocation(300, 300);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        MAL = new MyActionListener(south);

        south = new JTextArea(5, 20);
        south.setEditable(false);
        JScrollPane sroll = new JScrollPane(south);
        this.add(sroll, BorderLayout.SOUTH);

        LeftButton = new Button("Left Button");
        LeftButton.setOpaque(true);
        LeftButton.addActionListener(MAL);
        this.add(LeftButton, BorderLayout.WEST);

        RightButton = new Button("Right Button");
        RightButton.setOpaque(true);
        RightButton.addActionListener(MAL);
        this.add(RightButton, BorderLayout.EAST);

        setVisible(true);
    }
}

MyActionListener:

package Aufgabe_18;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyActionListener implements ActionListener{

    private final JTextArea south;

    public MyActionListener(JTextArea south)
    {
        this.south = south;
    }

    private void setTextLeftButton(JTextArea south){
        south.append("Left Button \n");
    }

    private void setTextRightButton(JTextArea south){
        south.append("Right Button \n");
    }

@Override
        public void actionPerformed(ActionEvent e) {
        String a;
        Object src = e.getSource();
        Button b = null;
        b = (Button) src;
        a = b.getString();
        if (a == "LeftButton")
            setTextRightButton(south);
        if (a == "RightButton")
            setTextRightButton(south);
    }
}

Я ожидаю, что JTextArea напишет, какая кнопка была нажата, но после нажатия ничего не происходит. Ошибки не появляются.

1 Ответ

0 голосов
/ 28 мая 2019

Я попытался скомпилировать ваш код на JDK8, он дал ошибки, и я вижу, что у него мало проблем.

Прежде всего это:

MAL = new MyActionListener(south);

south = new JTextArea(5, 20);
south.setEditable(false);

Вы передаете Null в качестве параметра своему слушателю. Вы должны инициализировать «юг», прежде чем передавать его в конструкторе в MAL. Также у Баттона не было метода getString. У него есть getLabel или getText для JButton. Также, как сказал @vince, добавьте пробел в поле «LeftButton». Я немного подправил твой код. Ниже приведен рабочий код. Для простоты я добавил пользовательский Listener в тот же файл и заменил Button на JButton (вы уже используете JFrame в Swing, поэтому лучше использовать все компоненты Swing). Вы получите суть с этим:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;

public class Test extends JFrame {
    private JButton LeftButton;
    private JButton RightButton;
    private JScrollPane scroll;
    private JTextArea south;
    private MyActionListener MAL;

    public static void main(String[] args) {
        Test l = new Test("Aufgabe18c");
    }

    public Test(String title) {
        super(title);
        setSize(300, 150);
        this.setLocation(300, 300);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        //initialize south
        south = new JTextArea(5, 20);
        south.setEditable(true);

        //pass it to your Listener
        MAL = new MyActionListener(south);
        JScrollPane scroll = new JScrollPane(south);
        this.add(scroll, BorderLayout.SOUTH);

        LeftButton = new JButton("Left Button");
        LeftButton.setOpaque(true);
        LeftButton.addActionListener(MAL);
        this.add(LeftButton, BorderLayout.WEST);

        RightButton = new JButton("Right Button");
        RightButton.setOpaque(true);
        RightButton.addActionListener(MAL);
        this.add(RightButton, BorderLayout.EAST);

        setVisible(true);
    }


public class MyActionListener implements ActionListener{

    private final JTextArea south;

    public MyActionListener(JTextArea south)
    {
        this.south = south;
    }

    private void setTextLeftButton(JTextArea south){
        south.append("Left Button \n");
    }

    private void setTextRightButton(JTextArea south){
        south.append("Right Button \n");
    }

@Override
        public void actionPerformed(ActionEvent e) {
        String a;
        Object src = e.getSource();
        JButton b = null;
        b = (JButton) src;
        a = b.getText();
        if (a == "Left Button")
            setTextLeftButton(south);
        else
            setTextRightButton(south);
    }
}
}
...