这可能是一个愚蠢的问题,但我无法理解“Mainframe类”中的语法,如图所示: Here, the setStringListener method is called from toolbar reference. But the syntax used inside the circular bracket is quite weird to me. I usually have parameters like strings or reference inside the call method. I did not understand how JButton will call this method. This programms works fine. I jst dont understand that part下面输入了整个源代码。
public class App {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new MainFrame();
}
});
}}
public class MainFrame extends JFrame{
private TextPanel textPanel;
private Toolbar toolbar;
public MainFrame(){
super("Hello World");
setLayout(new BorderLayout());
toolbar =new Toolbar();
textPanel=new TextPanel();
toolbar.setStringListener(new StringListener(){
public void textEmitted(String text){
textPanel.appendText(text);
}
});
add(toolbar,BorderLayout.NORTH);
add(textPanel,BorderLayout.CENTER);
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}}
public class TextPanel extends JPanel {
private JTextArea textArea;
public TextPanel(){
textArea=new JTextArea();
setLayout(new BorderLayout());
add(new JScrollPane(textArea),BorderLayout.CENTER);
}
public void appendText(String text){
textArea.append(text);
}}
public class Toolbar extends JPanel implements ActionListener {
private JButton helloButton;
private JButton goodbyeButton;
private StringListener textListener;
public Toolbar(){
helloButton=new JButton("Hello");
goodbyeButton=new JButton("Goodbye");
helloButton.addActionListener(this);
goodbyeButton.addActionListener(this);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(helloButton);
add(goodbyeButton);
}
public void setStringListener(StringListener listener){
this.textListener=listener;
}
public void actionPerformed(ActionEvent e) {
JButton clicked=(JButton)e.getSource();
if (clicked==helloButton){
if (textListener!=null){
textListener.textEmitted("Hello\n");
}
}
else if(clicked==goodbyeButton){
if (textListener!=null){
textListener.textEmitted("goodBye\n");
}
}
}}
接口是StringListener
public interface StringListener {
public void textEmitted(String text);
}
答案 0 :(得分:0)
由于您实际上是在new
方法中创建setStringListener()
接口,因此您需要实现。
您可以想象您已经使用textEmitted()
方法的实现定义了一个接口:
public class MyImplementation implements StringListener {
@Override
public void textEmitted(String text) {
// Do stuff here
}
}
现在,您可以在StringListener
类中创建新的MainFrame
,而不是单独定义此界面:
StringListener myImplementation = new StringListener() {
@Override
public void textEmitted(String text) {
// Do stuff here
}
};
toolbar.setStringListener(myImplementation);
那么你正在做什么与上面的代码基本相同,但在你的方法中创建StringListener
而不是单独定义它:
toolbar.setStringListener(new StringListener() {
@Override
public void textEmitted(String text) {
// Do stuff here
}
});
我希望这些例子有所帮助。
如果您仍然不确定,我强烈建议您阅读Java tutorial for Anonymous Classes。