【问题标题】:Referencing JPanel components from a JFrame从 JFrame 引用 JPanel 组件
【发布时间】:2011-12-08 23:12:37
【问题描述】:

我有一个应用程序在 JFrame 中创建 JPanel,如下所示:

public class Frame1{
    public Frame1(){
        Frame2 f2 = new Frame2();
        f2.pack();
        f2.setVisible(true);
    }

    class Frame2 extends JFrame{
        public Frame2(){
            JPanel p1 = new JPanel();
            JTextField txt1 = new JTextField("Test",12);
            p1.add(txt1);
            JButton btn1 = new JButton("Click Me!");
            p1.add(btn1);
            add(p1);
            btn1.addActionListener(this);
        }
        public void actionPerformed(ActionEvent e){
            JOptionPane.showDialog(null,text of the textbox);
        }
    }
}

有没有办法引用文本字段,即使它不是字段变量并且它只是在构造函数中声明(this.getRootPane().getParent() 会给我我相信的框架,但我从那里去哪里)?

【问题讨论】:

  • 如果需要引用,为什么不将其设为非静态类字段呢?或者找到其他一些干净的方法来获取它的引用,例如将它放在一个非静态字段的 Map 或 Collection 中?

标签: java swing jframe jpanel


【解决方案1】:

如果您想获得对仅在构造函数中声明的 JTextField 的引用,那么您唯一的选择是使用主 JFrame 获得它,如下所示:

JTextField textField = (JTextField) ((JPanel) getContentPane().getComponents()[0]).getComponents()[0];
JOptionPane.showMessageDialog(null, textField.getText());

或者对于一般解决方案:

private JTextField textField;

getJTextField(this); // Call this from inside the constructor

// ...

private boolean getJTextField(Container c)
{
    Component[] cmps = c.getComponents();
    for (Component cmp : cmps)
    {
        if (cmp instanceof JTextField)
        {
            textField = (JTextField) cmp;
            return true;
        }
        if (cmp instanceof Container)
        {
            if(getJTextField((Container) cmp)) return true;
        }
    }
    return false;
}

但是,将 JTextField 声明为类文件会使您的生活更轻松。

【讨论】:

    【解决方案2】:

    再次重申,为什么不将 JTextField 设为类的私有非静态字段:

    import java.awt.event.*;
    import javax.swing.*;
    
    public class Frame1 {
       public Frame1() {
          Frame2 f2 = new Frame2();
          f2.pack();
          f2.setVisible(true);
       }
    
       class Frame2 extends JFrame implements ActionListener {
          private JTextField txt1;
    
          public Frame2() {
             JPanel p1 = new JPanel();
    
             // JTextField txt1 = new JTextField("Test", 12);
             txt1 = new JTextField("Test", 12);
    
             p1.add(txt1);
             JButton btn1 = new JButton("Click Me!");
             p1.add(btn1);
             add(p1);
             btn1.addActionListener(this);
          }
    
          // if outside classes need to see the text
          public String getTxt1Text() {
             return txt1.getText();
          }
    
          public void actionPerformed(ActionEvent e) {
             JOptionPane.showMessageDialog(this, txt1.getText());
          }
       }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2012-03-19
    • 1970-01-01
    相关资源
    最近更新 更多