当前位置: 代码迷 >> Java相关 >> 作用域的问题
  详细解决方案

作用域的问题

热度:272   发布时间:2005-08-02 12:34:00.0
作用域的问题
我想请教一个问题
比如说一个面板和另一个面板之间的是怎样控制的。
我想在一个面板上写一个事件,而事件源是另一个面板,怎样才能在一个面板里面触发另一个面板里面的事件呢?多谢
----------------解决方案--------------------------------------------------------
不理解你说什么
你指的面板是JPanel么?
----------------解决方案--------------------------------------------------------
作用域的问题
对我说的是在窗体中加几个面板,用第一个面板调用第二个面板,
还有一个事件源在第一个面板,我想用第二个面板的按钮去鉴听它
----------------解决方案--------------------------------------------------------

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()); } }


----------------解决方案--------------------------------------------------------
在 this.setVisible(true);后加上setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);来关闭.
----------------解决方案--------------------------------------------------------
  相关解决方案