如何在 Java 中将 int 和 string 的值从一个程序传输到另一个程序

How can I transfer values of an int and string from one program to another in Java

好的,所以在我的代码中,我要求用户提供他们的姓名,并要求他们单击 3 个按钮之一,这会为变量提供相应的值。现在在另一个程序中,我想调用这个程序,然后几乎显示字符串并将 int 值用于特定目的。

public class MainMenuofgame extends JFrame implements ActionListener{
    JButton slow, medium, fast;
    JLabel pic1, pic2, pic3, pic4;
    JTextField username;
    Container frame;

    static String name;
    static int xspeed = 0;          

    public MainMenuofgame() { 
            super ("Main Menu of Rocket Launch");
            frame = getContentPane ();
            frame.setLayout (null);

            pic1 = new JLabel (new ImageIcon ("welcome.png"));

            pic2  = new JLabel (new ImageIcon ("name.png"));

            pic3 = new JLabel (new ImageIcon ("speed.png"));

            pic4 = new JLabel (new ImageIcon ("backgnd.jpg"));

            username = new JTextField ();

            slow = new JButton("Slow");
            //  slow.setActionCommand("slowspeed");
            slow.addActionListener (this);

            medium = new JButton("Medium");
            // medium.setActionCommand("mediumspeed");
            medium.addActionListener (this);

            fast = new JButton("Fast");
            // fast.setActionCommand("fastspeed");
            fast.addActionListener (this);

            pic1.setBounds (30,50, 525, 173);//welcome
            pic2.setBounds (100,230,212,73);//name
            pic3.setBounds (80,350,428,84);//speed

            username.setBounds(310,255,150,30);

            slow.setBounds (100,450,100,100);
            medium.setBounds (250,450,100,100);
            fast.setBounds (400,450,100,100);
            //background bound goes in the end 
            pic4.setBounds (0,0, 600,900);

            frame.add (pic1);

            frame.add (pic2);

            frame.add (pic3);

            frame.add (username);

            frame.add (slow);

            frame.add (medium);

            frame.add (fast);    

            frame.add (pic4);


            setSize(600, 900);
            setVisible (true);
            setDefaultCloseOperation (EXIT_ON_CLOSE);

    }

    public void actionPerformed (ActionEvent evt){

            String name = username.getText();

            if (evt.getSource () == slow)
            {
                    xspeed = 1;
            }
            else if(evt.getSource () == medium)
            {
                    xspeed = 5;
            }
            else 
            {
                    xspeed = 10;
            }

    }



    public static void main(String[] args) { 
            new MainMenuofgame ();
    }

}

关于如何将信息从一个程序传输到另一个程序,有两种方法之一...

  1. 客户端-服务器应用程序

这需要您有第三个应用程序 运行 通过套接字从其他两个应用程序(客户端)中的每一个接收信息。更多信息 Google "Client-Server applications in Java"

  1. 有一个文本文件传递信息

为此,您应该有一个文本文件,一个应用程序在其中存储信息,而另一个应用程序只是简单地读取它...这是一个更简单的解决方案,但学习经验较少。这是示例代码。

应用程序 1:

private void storeMessage(String msg){
    File centralFile = new File("path to your file");
    BufferedWriter writer = new BufferedWriter(new FileWriter(centralFile));
    writer.write(msg);
    writer.close();
}

应用程序 2:

private String getMessage(){
    File centralFile = new File("path to your file");
    String msg = "";
    BufferedReader reader = new BufferedReader(new FileReader(centralFile));
    while (reader.hasNextLine()){
        msg += reader.nextLine();
    }
    reader.close();
    return msg;
 }

希望对您有所帮助

您描述的行为实际上并不是 "transfer values of an int and string from one program to another in Java",而是更简单的将数据从一个对象传输到另一个对象,这里的对象是由 GUI 组件表示。不要创建两个单独的程序,而是创建以有意义的方式交互的单独对象。这就是 Java 的 OOP 的本质。最简单的解决方案是让主应用程序在模态对话框(例如模态 JDialog)中显示子应用程序的 GUI,然后在处理完对话框(即不再可见)后,主应用程序 program/object在对话框中查询其组件的状态 -- 输入的数据。

此外,让 class 扩展 JFrame 是在逼迫自己创建和显示 JFrame,而这通常需要更大的灵活性。事实上,我敢说我创建的和看到的大部分 Swing GUI 代码 没有 扩展 JFrame,事实上,您很少会想做这个。更常见的是,您的 GUI classes 将适用于创建 JPanel,然后可以将其放入 JFrames 或 JDialogs,或 JTabbedPanes,或通过 CardLayouts 在任何需要的地方进行交换。这将大大增加您的 GUI 编码的灵活性。

例如:

import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class MenuDemoMainPanel extends JPanel {
    private MenuPanel menuPanel = new MenuPanel();
    private JDialog menuDialog = null;
    private String name;
    private Speed speed;
    private JTextField nameField = new JTextField(10);
    private JTextField speedField = new JTextField(10);

    public MenuDemoMainPanel() {

        // these fields are for display only and should not allow user
        // interaction
        nameField.setFocusable(false);
        speedField.setFocusable(false);

        // not kosher to set this directly, per kleopatra, but oh well
        setPreferredSize(new Dimension(600, 400));

        // simple demo GUI -- add components
        add(new JLabel("Name:"));
        add(nameField);
        add(new JLabel("Speed:"));
        add(speedField);
        add(new JButton(new GetNameAndSpeedAction("Get Name And Speed")));
    }

    // action for JButton that displays the menuDialog JDialog
    private class GetNameAndSpeedAction extends AbstractAction {
        public GetNameAndSpeedAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (menuDialog == null) {
                // if the menu dialog has not been created yet -- create it
                Window win = SwingUtilities.getWindowAncestor(MenuDemoMainPanel.this);
                menuDialog = new JDialog(win, "Menu", ModalityType.APPLICATION_MODAL);
                menuDialog.add(menuPanel);
                menuDialog.pack();
                menuDialog.setLocationRelativeTo(win);
            }

            // display the menu JDialog
            menuDialog.setVisible(true);

            // this code is called only when the dialog is no longer visible
            // query the dialog for the state it holds
            name = menuPanel.getNameText();
            speed = menuPanel.getSpeed();

            // and display the state in the main GUI
            if (name != null && speed != null) {
                nameField.setText(name);
                speedField.setText(speed.getText());
            }

        }
    }

    private static void createAndShowGui() {
        // create the main GUI JPanel
        MenuDemoMainPanel mainPanel = new MenuDemoMainPanel();

        // then create an application GUI 
        JFrame frame = new JFrame("Menu Demo -- Main GUI");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel); // place the main panel into the GUI

        // and pack and display it:
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

// JPanel to hold menu dialog components
@SuppressWarnings("serial")
class MenuPanel extends JPanel {
    private JComboBox<Speed> speedCombo = new JComboBox<>(Speed.values());
    private JTextField nameField = new JTextField(10);

    public MenuPanel() {
        speedCombo.setSelectedIndex(-1);
        add(new JLabel("Name:"));
        add(nameField);
        add(new JLabel("Speed:"));
        add(speedCombo);
        add(new JButton(new SubmitAction("Submit")));
    }

    // allow outside classes to query the nameField JTextField's state
    public String getNameText() {
        return nameField.getText();
    }

    // allow outside classes to query the speedCombo JComboBox's state
    public Speed getSpeed() {
        return (Speed) speedCombo.getSelectedItem();
    }

    // Action for JButton that submits the dialog to the main GUI
    private class SubmitAction extends AbstractAction {

        public SubmitAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // if the data is not all entered or selected
            if (nameField.getText().trim().isEmpty() || speedCombo.getSelectedIndex() == -1) {
                Component comp = MenuPanel.this;
                String msg = "You must enter your name and select a speed";
                String title = "Invalid Data";
                int msgType = JOptionPane.ERROR_MESSAGE;
                // warn the user and leave this dialog still visible
                JOptionPane.showMessageDialog(comp, msg, title, msgType);
            } else {

                // otherwise dispose of this dialog and thereby pass control
                // back to the main application / GUI
                Window win = SwingUtilities.getWindowAncestor(MenuPanel.this);
                win.dispose();
            }
        }

    }
}

// an enum to encapsulate possible game speeds
enum Speed {
    SLOW("Slow"), MEDIUM("Medium"), FAST("Fast");
    private String text;

    private Speed(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return getText();
    }
}

嗯……我真正需要做的就是调用我想存储数据的变量,然后……存储它。这是在底部的 If 语句中完成的。感谢大家的帮助,但老实说,你们的大部分回答提出的问题比我回答的要多,这让我很困惑,但我想通了,所以还是谢谢 :)

public class MainMenuofgame extends JFrame implements ActionListener{
    JButton slow, medium, fast;
    JLabel pic1, pic2, pic3, pic4;
    JTextField username;
    Container frame;

    static String name;
    static int xspeed = 0;          

    public MainMenuofgame() { 
            super ("Main Menu of Rocket Launch");
            frame = getContentPane ();
            frame.setLayout (null);

            pic1 = new JLabel (new ImageIcon ("welcome.png"));

            pic2  = new JLabel (new ImageIcon ("name.png"));

            pic3 = new JLabel (new ImageIcon ("speed.png"));

            pic4 = new JLabel (new ImageIcon ("backgnd.jpg"));

            username = new JTextField ();

            slow = new JButton("Slow");
            //  slow.setActionCommand("slowspeed");
            slow.addActionListener (this);

            medium = new JButton("Medium");
            // medium.setActionCommand("mediumspeed");
            medium.addActionListener (this);

            fast = new JButton("Fast");
            // fast.setActionCommand("fastspeed");
            fast.addActionListener (this);

            pic1.setBounds (30,50, 525, 173);//welcome
            pic2.setBounds (100,230,212,73);//name
            pic3.setBounds (80,350,428,84);//speed

            username.setBounds(310,255,150,30);

            slow.setBounds (100,450,100,100);
            medium.setBounds (250,450,100,100);
            fast.setBounds (400,450,100,100);
            //background bound goes in the end 
            pic4.setBounds (0,0, 600,900);

            frame.add (pic1);

            frame.add (pic2);

            frame.add (pic3);

            frame.add (username);

            frame.add (slow);

            frame.add (medium);

            frame.add (fast);    

            frame.add (pic4);


            setSize(600, 900);
            setVisible (true);
            setDefaultCloseOperation (EXIT_ON_CLOSE);

    }

    public void actionPerformed (ActionEvent evt){

            String name = username.getText();
            Rocketlaunch.name = name;

            if (evt.getSource () == slow)
            {
                    Rocketlaunch.moveSpeed = 1;
                    Rocketlaunch.speed = "Slow";
                    setVisible (false);
            }
            else if(evt.getSource () == medium)
            {
                    Rocketlaunch.moveSpeed = 5;
                    Rocketlaunch.speed = "Medium";
                    setVisible (false);
            }
            else 
            {
                    Rocketlaunch.moveSpeed = 10;
                    Rocketlaunch.speed = "Fast";
                    setVisible (false);
            }

            new Rocketlaunch();

    }



    public static void main(String[] args) { 
            new MainMenuofgame ();
    }

}