从java中的另一个窗口获取值

时间:2013-08-19 16:14:13

标签: java swing jframe

我的问题与java swing frame有关。我有两个jframe。 jframe1和jframe2。在jframe1中有一个jbutton,当用户点击jbutton我要显示jframe 2. jframe2有一个文本框,jbutton用户可以输入值到文本框,当用户点击jbutton时,我想将焦点设置为1st jframe并传递用户在jrame1中输入jlable值。请帮我这样做。

1 个答案:

答案 0 :(得分:2)

在我看来,第二帧就像是一个对话框,用于输入一个值,然后返回给调用者(第一帧)。

要实现此目的,您需要创建一个模态JDialog,在那里添加控件(文本字段,确定并可能是取消按钮)并添加一个打开对话框的方法(阻止调用者)并返回输入的文本除非被取消。这样,您可以直接传递输入的文本,而不必将其临时存储到变量中(这通常是不好的做法)。

以下是这种对话框的简单实现:

public class SwingTestDialog extends JDialog {

    private JTextField text;
    private boolean cancelled = true;

    public static void main (String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run () {
                SwingTestDialog dialog = new SwingTestDialog();
                String text = dialog.selectValue();
                System.out.println("Selected: " + text);
            }
        });
    }

    public SwingTestDialog () {
        setModal(true);
        setTitle("Please enter something");
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout(10, 10));
        getContentPane().add(content);

        text = new JTextField();
        JButton ok = new JButton("Accept");
        JButton cancel = new JButton("Cancel");
        JPanel buttons = new JPanel();
        buttons.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        buttons.add(ok);
        buttons.add(cancel);

        content.add(text, BorderLayout.NORTH);
        content.add(buttons, BorderLayout.SOUTH);
        content.setBorder(new EmptyBorder(15, 15, 15, 15));
        pack();

        ok.addActionListener(new ActionListener() {

            public void actionPerformed (ActionEvent e) {
                cancelled = false;
                dispose();
            }
        });
        cancel.addActionListener(new ActionListener() {

            public void actionPerformed (ActionEvent e) {
                cancelled = true;
                dispose();
            }
        });
        // default button, allows to trigger ok when pressing enter in the text field
        getRootPane().setDefaultButton(ok);
    }

    /**
     * Open the dialog (modal, blocks caller until dialog is disposed) and returns the entered value, or null if
     * cancelled.
     */
    public String selectValue () {
        setVisible(true);
        return cancelled ? null : text.getText();
    }
}