1 回答

TA貢獻1853條經驗 獲得超18個贊
我試著在 JDK8 上編譯你的代碼,它給出了錯誤,我可以看到它幾乎沒有問題。
首先是:
MAL = new MyActionListener(south);
south = new JTextArea(5, 20);
south.setEditable(false);
您將 Null 作為參數傳遞給您的偵聽器。在將構造函數中的“south”傳遞給 MAL 之前,您必須先對其進行初始化。此外,Button 沒有任何方法作為 getString。它具有用于 JButton 的 getLabel 或 getText。同樣正如@vince 所說,在“LeftButton”中添加空格。我對你的代碼做了一些調整。下面是工作代碼。為簡單起見,我在同一個文件中添加了自定義監聽器,并將 Button 替換為 JButton(您已經在使用 swing 的 JFrame,因此最好嘗試使用所有 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);
}
}
}
添加回答
舉報