1 回答

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