import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JFrm extends JFrame{ public JFrm(){ Container c=this.getContentPane(); JButton btn=new JButton("Button"); //Left JPanel JPanel p=new JPanel(); p.setBackground(Color.pink); //Right JPanel PanelB pb=new PanelB(); pb.setBackground(Color.BLUE); p.add(btn,BorderLayout.CENTER); c.add(p,BorderLayout.WEST); c.add(pb); //Add Listener ButtonListener bl=new ButtonListener(pb); btn.addActionListener(bl); this.setSize(400,300); this.setVisible(true); } public static void main(String[] args) { new JFrm(); } } class PanelB extends JPanel{ public JTextField txt; public PanelB( ){ txt=new JTextField(20); this.add(txt); } } //class ButtonListener implements ActionListener{ PanelB p; public ButtonListener(PanelB p){ this.p=p; }//这个是用到的什么机制? public void actionPerformed(ActionEvent e){ p.txt.setText(e.getActionCommand()); } } |
----------------解决方案--------------------------------------------------------
//class ButtonListener implements ActionListener{
PanelB p;
public ButtonListener(PanelB p){
this.p=p;
} //这个通过一个Constructor 将外部的变量与其自身的变量联系了起来,写得很巧妙,其实没有这个必要
----------------解决方案--------------------------------------------------------
程序改写如下, 我将这个ButtonListener class 改名为MyActionListener , 并将他置于JFrm 中
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class PanelB extends JPanel
{
public JTextField txt;
public PanelB( )
{
txt=new JTextField(20);
this.add(txt);
}
public void setText(String text)
{
txt.setText(text);
}
}
public class JFrm extends JFrame
{
JButton btn = new JButton("Button");
PanelB pb=new PanelB();
public JFrm()
{
Container c=this.getContentPane();
btn.addActionListener(new MyActionListener());
//Left JPanel
JPanel p=new JPanel();
p.setBackground(Color.pink);
p.add(btn,BorderLayout.CENTER);
//Right JPanel
pb.setBackground(Color.BLUE);
c.add(p,BorderLayout.WEST);
c.add(pb);
this.setSize(400,300);
this.setVisible(true);
}
class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
pb.setText(ae.getActionCommand());
}
}
public static void main(String[] args)
{
new JFrm();
}
}
----------------解决方案--------------------------------------------------------
Container c=this.getContentPane();
高手们这句是什么意思?
----------------解决方案--------------------------------------------------------
在这里 this 呢就是那个 JFrame Object,
然后其调用 getContentPane(); 这样呢他就得到了那个Container
这个Container 呢用于装载那些 JFrame 的 Components
不知这样的解释,是不是可以让人理解?
----------------解决方案--------------------------------------------------------
还是不明白
----------------解决方案--------------------------------------------------------