应用Swing组件进行图形界面编程时,经常会遇到在界面之间进行传值的情形。下面简介几个方法:
1. 如果是用到数据库的情形,可以是一界面将数据先写到数据库,然后另一界面再去读数据库;
2.采用读入文件的形式,一界面先写,令一界面再读;
3.可以通过界面之间相互传Frame句柄的方法,下面的例子说明了界面Frame1和Frame2是如何完成相互通信的。
public class Frame1 extends JFrame {
JTextArea jTextArea1 = new JTextArea();
JButton jButton1 = new JButton();
JLabel jLabel1 = new JLabel();
JButton jButton2 = new JButton();
Frame2 child;
public Frame1() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Frame1 frame1 = new
Frame1();
frame1.setVisible(true);
}
private void jbInit() throws Exception {
jTextArea1.setText("jTextArea1
");
jButton1.setText("Make Frame 2 ");
jButton1.addActionListener(new
Frame1_jButton1_actionAdapter(this));
jLabel1.setText("Frame 1 ");
jButton2.setText("jButton2
");
jButton2.addActionListener(new
Frame1_jButton2_actionAdapter(this));
this.getContentPane().add(jTextArea1,
BorderLayout.CENTER);
this.getContentPane().add(jButton1,
BorderLayout.WEST);
this.getContentPane().add(jLabel1,
BorderLayout.NORTH);
this.getContentPane().add(jButton2,
BorderLayout.SOUTH);
}
void jButton1_actionPerformed(ActionEvent e)
{
child = new
Frame2(this);
child.setVisible(true); }
void jButton2_actionPerformed(ActionEvent e)
{
this.jTextArea1.setText(child.jTextField1.getText()); }
}
class Frame1_jButton1_actionAdapter implements
java.awt.event.ActionListener {
Frame1 adaptee;
Frame1_jButton1_actionAdapter(Frame1 adaptee)
{
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e)
{
adaptee.jButton1_actionPerformed(e);
}
}
class Frame1_jButton2_actionAdapter implements
java.awt.event.ActionListener {
Frame1 adaptee;
Frame1_jButton2_actionAdapter(Frame1 adaptee)
{
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e)
{
adaptee.jButton2_actionPerformed(e);
}
}
//
public class Frame2 extends JFrame {
JLabel jLabel1 = new JLabel();
JTextField jTextField1 = new JTextField();
JButton jButton1 = new JButton();
Frame1 parent;
public Frame2(Frame1 Parent) {
parent =
Parent; try
{
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
jLabel1.setText("Frame 2 ");
jTextField1.setText("jTextField1
");
jButton1.setText("Get Frame1 Text ");
jButton1.addActionListener(new
Frame2_jButton1_actionAdapter(this));
this.getContentPane().add(jLabel1,
BorderLayout.NORTH);
this.getContentPane().add(jTextField1,
BorderLayout.CENTER);
this.getContentPane().add(jButton1,
BorderLayout.SOUTH);
}
void jButton1_actionPerformed(ActionEvent e)
{
this.jTextField1.setText(parent.jTextArea1.getText()); }
}
class Frame2_jButton1_actionAdapter implements
java.awt.event.ActionListener {
Frame2 adaptee;
Frame2_jButton1_actionAdapter(Frame2 adaptee)
{
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e)
{
adaptee.jButton1_actionPerformed(e);
}
}