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

时间:2016-11-01 23:44:32

标签: java swing jframe textfield transfer

好的,在我的代码中,我要求用户输入他们的名字,并要求他们点击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 ();
    }

}

3 个答案:

答案 0 :(得分:1)

您描述的行为实际上并不是“在Java中将int和字符串从一个程序传递到另一个程序”,而是更简单地将数据从一个对象传输到另外,这里的对象由GUI组件表示。不要创建两个单独的程序,而是创建以有意义的方式交互的单独对象。这是使用Java的OOP的本质。最简单的解决方案是让主应用程序在模式对话框(如模态JDialog)中显示子应用程序的GUI,然后一旦对话框被处理(即,不再可见),则主程序/对象查询其组件状态的对话框 - 输入的数据。

此外,您通过让您的类扩展JFrame来强迫您创建和显示JFrame,并且通常需要更多灵活性,从而在角落里绘画。事实上,我冒昧地说,我创建的大部分Swing GUI代码和我见过的扩展了JFrame,事实上你很少想做这个。更常见的是,您的GUI类将面向创建JPanels,然后可以将其放置到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();
    }
}

答案 1 :(得分:0)

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

  1. 客户端 - 服务器应用程序
  2. 这要求您让第三个应用程序通过套接字接受来自其他两个应用程序(客户端)的信息。有关详细信息,请参阅Google“Java中的客户端 - 服务器应用程序”

    1. 有一个文本文件传递信息
    2. 要做到这一点,你应该有一个文件文件,一个应用程序存储信息,另一个应用程序只是简单地读取它...这是一个更容易的解决方案,但不是一个学习经验。这是示例代码。

      申请1:

      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;
       }
      

      申请2:

      df

      希望这有帮助

答案 2 :(得分:0)

嗯......我真的需要做的就是调用我想要存储数据的变量然后存储它。这是在底部的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 ();
    }

}