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);
}
}
}
添加回答
举报