将一个 gui 的字符串值传递给另一个

Passing string value one gui to another

Main class

Result GUI

当您点击提交按钮时,我正在尝试将主 class 中的一个字符串添加到另一个 gui。然而,当第二个 gui 出现时,它在我的名字上显示为空。

class 1 个主要

public class SubmitButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        
        
        first_name = firstText.getText();
        last_name = lastText.getText();
        firstText.setText(first_name);
        lastText.setText(last_name);
        
        
        frame.setVisible(false);
        resultGui gui1 = new resultGui();
        gui1.setName(first_name);
        
    }
    
} 

class 2 秒 gui

 public JFrame resultFrame;
    public JLabel first_name_label , last_name_label;
    private String first_name;
        
      public String getName() {
          return first_name;
      }
        
      public void setName(String name) {
          this.first_name = name;
      }

   

在您的 class 1 中,您使用 gui1.setName(first_name);,这将调用

public void setName(String name) {
    this.first_name = name;
}

in class 2. 但是没有传值给Label。该方法可能看起来像

public void setName(String name) {
    this.first_name = name;
    first_name_label.setText(name);
}

您需要做的就是将第二个 GUI(我们称之为弹出窗口)添加为第一个的组件。在下面的示例中,我选择将弹出窗口设为内部框架。然后,“显示弹出窗口”按钮的所有动作侦听器需要做的就是从文本字段中获取文本并将其设置在弹出窗口的标签上。

import javax.swing.*;
import java.awt.*;

public class MyApp {

    public static void main (String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }
    private static void createAndShowGUI () {
        JFrame frame = new JFrame();
        Form form = new Form();
        Container pane = frame.getContentPane();
        pane.add(form, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    private static class Form extends JPanel {
        private JTextField field = new JTextField();
        private Popup popup = new Popup();
        JButton btn = new JButton("Show popup");

        public Form() {
            field.setColumns(20);
            add(field);
            add(btn);
            add(popup);
            btn.addActionListener(e -> {
                popup.setLabel(field.getText());
                popup.setVisible(true);
            });
        }
    }

    private static class Popup extends JInternalFrame {
        private static final String TEXT_PREFIX = "You entered: ";
        private JLabel label = new JLabel(TEXT_PREFIX);

        public Popup () {
            super("Popup", false, true, false, false);
            add(label);
            label.setVisible(true);
            setLocation(0,0);
            setPreferredSize(new Dimension(200, 100));
        }

        public void setLabel (String text) {
            label.setText(TEXT_PREFIX + text);
        }
    }
}

我将此代码添加到 Replit。您可以从那里 运行 它。 Replit JInternalFrameDemo

查看以下结果: