【发布时间】:2012-08-19 15:47:21
【问题描述】:
我有一个主类,其中有一个 Editor 类(带有 JTextPane)和一个 Toolbar 类(带有 JList 和 Jbutton,我不想使用 JToolBar)。这两个类由许多组件组成,我不想将它们混合到同一个类中。我希望编辑器和工具栏进行通信。 假设我在工具栏中写了“Hello”,然后单击提交。我希望文本窗格显示“你好”。 我以这种方式构建类:
public class Main{
public MainGUI(){
initComponents();
}
private void initComponents(){
JFrame mainframe=new JFrame("Main Frame");
Editor editor=new Editor();
Toolbar toolbar=new Toolbar();
mainframe.getContentPane().setLayout(new BorderLayout());
mainframe.getContentPane().add(editor, BorderLayout.CENTER);
mainframe.getContentPane().add(toolbar, BorderLayout.NORTH);
mainframe.setVisible(true);
}
}
public class Editor extends JPanel{
public Editor(){
super();
initComponents();
}
private void initComponents(){
JTextPane textpane=new JTextPane();
this.setLayout(new BorderLayout());
this.add(textpane, BorderLayout.CENTER);
}
}
public class Toolbar extends JPanel{
public Toolbar(){
super();
initComponents();
}
private void initComponents(){
JTextField textfield=new JTextField();
JButton submitbutton=new JButton("Submit");
this.setLayout(newFlowLayout());
this.add(textfield);
this.add(submitbutton);
}
}
我应该如何实现工具栏和编辑器之间的事件处理?
【问题讨论】:
-
为事件处理创建一个单独的类并将这两个类的引用传递给该类,然后简单地做你的魔术开始:-)虽然你需要让你的字段实例字段,而不是将它们单独作为函数的本地。由于您要在外部访问的内容的范围仅限于
initComponents()方法。
标签: java swing class events communication