在 Java 中连接 2 个不同的程序(每个程序都有其主要方法)

Connecting 2 different programs in Java (each one has its main method)

我使用 Java GUI 创建了 2 个程序(Background 和 NrLojtareve),其中每个程序都创建了游戏的一个步骤。每个程序都有自己的main方法。

我想做的就是在执行第一个程序 (NrLojtareve) 之后,它包含 4 个单选按钮来显示另一个页面,我用另一个程序(背景)创建的。

所以从游戏的第一步到第二步。所以 NrLojtareve class 的处理程序调用后台 class.

谁能告诉我如何从第一个程序调用第二个程序,或者如何在从第一个程序选择单选按钮后显示第二个 GUI?


这是代码。

Nrlojtareve.java

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

public class Nrlojtareve extends JFrame {

    private JRadioButton a;
    private JRadioButton b;
    private JRadioButton c;
    private JRadioButton d;
    private ButtonGroup group ;
    private JLabel e;

    public Nrlojtareve() {
        setLayout(new FlowLayout());
        a=new JRadioButton("1");
        b=new JRadioButton("2");
        c=new JRadioButton("3");
        d=new JRadioButton("4");
        e=new JLabel("Choose the number of players!");
        add(a);
        add(b);
        add(c);
        add(d);
        add(e);
        group = new ButtonGroup();
        group.add(a);
        group.add(b);
        group.add(c);
        group.add(d);

        thehandler hand = new thehandler();
        a.addItemListener(hand);
        b.addItemListener(hand);
        c.addItemListener(hand);
        d.addItemListener(hand);
    }

    private class thehandler implements ItemListener {
        public void itemStateChanged(ItemEvent event) {

        }
    }

    public static void main(String[] args) {

        Nrlojtareve elda = new Nrlojtareve();
        elda.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        elda.setSize(300,400);
        elda.setVisible(true);
    }

}


Back.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;

public class Back extends JFrame {

private Container pane;
    public Back() {
        super("title");
        setLayout(null);

        Icon i=new ImageIcon(getClass().getResource("1.png"));
        pane=new Container();

        //konstruktori i handler merr nje instance te Background
        thehandler hand = new thehandler();

    }

     private class thehandler implements ActionListener {

         public void actionPerformed(ActionEvent event) {

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

         Back  d = new Back() ;

         d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         d.getContentPane().setBackground(Color.GREEN);
         d.setSize(700,500);

         d.setVisible(true);    
    }
}

建议:

  • 避免创建扩展 JFrame 的 classes。这样做会使您陷入困境并迫使您将 class 用作 JFrame。
  • 而是将您的 Swing GUI 用于创建 JPanel。如果您想将 JPanel 作为独立的 GUI 或在 JDialogs 或 JOptionPanes 或其他 JPanel 中显示,那么您可以将 JPanel 放入 JFrames 中,这将为您提供更大的灵活性。
  • 对上述代码执行此操作后,创建使用 CardLayout 的第三个 JPanel,并使用 JPanel 将上述 JPanel GUI 添加到此 "master" CardLayout。然后,您可以使用 CardLayout 的 show(...) 方法轻松交换 "views"。
  • 然后创建另一个class,里面只有一个main方法,在main方法中创建你的JFrame,添加主CardLayout-using JPanel到JFrame,并显示它。
  • CardLayout Tutorial link

其他建议:

  • 避免 null 布局和 setBounds(...) 就像瘟疫一样,因为它们的使用会导致创建不能在 JScrollPane 内部使用的僵化 GUI,很难扩展、增强和调试.而是学习和使用布局管理器。
  • 另一种选择是将第一个 GUI 显示为模态对话框,例如 JDialog。

例如:

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;
import javax.swing.border.Border;

public class CombinedGui {
    private static void createAndShowGui() {
        JFrame frame = new JFrame("Combined GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MainPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

@SuppressWarnings("serial")
class MainPanel extends JPanel {
    private static final int MAX_PLAYERS = 4;
    private CardLayout cardLayout = new CardLayout();
    private ChoicePanel choicePanel = new ChoicePanel(MAX_PLAYERS);
    private BackPanel backPanel = new BackPanel();

    public MainPanel() {
        setLayout(cardLayout);
        add(choicePanel, ChoicePanel.class.getName());
        add(backPanel, BackPanel.class.getName());

        choicePanel.addPropertyChangeListener(new ChoicePanelListener());
    }

    public void showView(String key) {
        cardLayout.show(this, key);
    }

    private class ChoicePanelListener implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (ChoicePanel.PLAYER_COUNT.equals(evt.getPropertyName())) {
                int playerCount = (Integer) evt.getNewValue();
                backPanel.setPlayerCount(playerCount);
                showView(BackPanel.class.getName());
            }
        }
    }

}

@SuppressWarnings("serial")
class BackPanel extends JPanel {
    private static final Color BG = Color.GREEN;
    private static final int PREF_W = 700;
    private static final int PREF_H = 500;
    private static final String PLAYER_COUNT_TEXT = "Player Count is: ";
    private JLabel playerCountLabel = new JLabel(PLAYER_COUNT_TEXT, SwingConstants.CENTER);
    private int playerCount = 0;

    public BackPanel() {
        playerCountLabel.setFont(playerCountLabel.getFont().deriveFont(Font.BOLD, 48));

        setBackground(BG);
        setLayout(new GridBagLayout());
        add(playerCountLabel);
    }

    public void setPlayerCount(int playerCount) {
        this.playerCount = playerCount;
        playerCountLabel.setText(PLAYER_COUNT_TEXT + playerCount);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    public int getPlayerCount() {
        return playerCount;
    }

}

@SuppressWarnings("serial")
class ChoicePanel extends JPanel {
    public static final String PLAYER_COUNT = "player count";
    private int playerCount = -1;

    public ChoicePanel(int maximumPlayers) {
        JPanel centralPanel = new JPanel(new GridLayout(0, 1, 5, 5));
        Border outsideBorder = BorderFactory.createTitledBorder("Choose Player Count:");
        int gap = 20;
        Border insideBorder = BorderFactory.createEmptyBorder(gap, 2 * gap, gap, 2 * gap);
        Border compoundBorder = BorderFactory.createCompoundBorder(outsideBorder, insideBorder);
        centralPanel.setBorder(compoundBorder);
        for (int i = 0; i < maximumPlayers; i++) {
            String text = "" + (i + 1) + " Player";
            if (i > 0) {
                text += "s";
            }
            JRadioButton radioButton = new JRadioButton(text);
            radioButton.addActionListener(new RadioListener(i + 1));
            centralPanel.add(radioButton);
        }
        setLayout(new GridBagLayout());
        add(centralPanel);        
    }

    public void setPlayerCount(int playerCount) {
        this.playerCount = playerCount;
        firePropertyChange(PLAYER_COUNT, -1, playerCount);
    }

    public int getPlayerCount() {
        return playerCount;
    }

    private class RadioListener implements ActionListener {
        private int count;

        public RadioListener(int count) {
            this.count = count;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            setPlayerCount(count);
        }
    }
}

或者对于模态对话框示例,请尝试:

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;

public class CombinedGui {
    private static void createAndShowGui() {
        JFrame frame = new JFrame("Combined GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // !! frame.getContentPane().add(new MainPanel());
        frame.getContentPane().add(new MainPanel2());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

@SuppressWarnings("serial")
class MainPanel2 extends JPanel {
    private static final int MAX_PLAYERS = 4;
    private CardLayout cardLayout = new CardLayout();
    private BackPanel backPanel = new BackPanel();

    public MainPanel2() {
        JButton getChoiceBtn = new JButton(new AbstractAction("Select Number of Players") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Window win = SwingUtilities.getWindowAncestor(MainPanel2.this);

                ChoicePanel choicePanel = new ChoicePanel(MAX_PLAYERS);
                final JDialog dialog = new JDialog(win, "Player Count Dialog", ModalityType.APPLICATION_MODAL);
                choicePanel.addPropertyChangeListener(new PropertyChangeListener() {

                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if (ChoicePanel.PLAYER_COUNT.equals(evt.getPropertyName())) {
                            int playerCount = (Integer) evt.getNewValue();
                            backPanel.setPlayerCount(playerCount);
                            showView(BackPanel.class.getName());
                            dialog.dispose();
                        }
                    }
                });
                dialog.add(choicePanel);
                dialog.pack();
                dialog.setLocationRelativeTo(win);
                dialog.setVisible(true);

            }
        });
        JPanel panel = new JPanel();
        panel.add(getChoiceBtn);

        setLayout(cardLayout);
        add(panel, "First Panel");
        add(backPanel, BackPanel.class.getName());

    }

    public void showView(String key) {
        cardLayout.show(this, key);
    }
}

@SuppressWarnings("serial")
class MainPanel extends JPanel {
    private static final int MAX_PLAYERS = 4;
    private CardLayout cardLayout = new CardLayout();
    private ChoicePanel choicePanel = new ChoicePanel(MAX_PLAYERS);
    private BackPanel backPanel = new BackPanel();

    public MainPanel() {
        setLayout(cardLayout);
        add(choicePanel, ChoicePanel.class.getName());
        add(backPanel, BackPanel.class.getName());

        choicePanel.addPropertyChangeListener(new ChoicePanelListener());
    }

    public void showView(String key) {
        cardLayout.show(this, key);
    }

    private class ChoicePanelListener implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (ChoicePanel.PLAYER_COUNT.equals(evt.getPropertyName())) {
                int playerCount = (Integer) evt.getNewValue();
                backPanel.setPlayerCount(playerCount);
                showView(BackPanel.class.getName());
            }
        }
    }

}

@SuppressWarnings("serial")
class BackPanel extends JPanel {
    private static final Color BG = Color.GREEN;
    private static final int PREF_W = 700;
    private static final int PREF_H = 500;
    private static final String PLAYER_COUNT_TEXT = "Player Count is: ";
    private JLabel playerCountLabel = new JLabel(PLAYER_COUNT_TEXT, SwingConstants.CENTER);
    private int playerCount = 0;

    public BackPanel() {
        playerCountLabel.setFont(playerCountLabel.getFont().deriveFont(Font.BOLD, 48));

        setBackground(BG);
        setLayout(new GridBagLayout());
        add(playerCountLabel);
    }

    public void setPlayerCount(int playerCount) {
        this.playerCount = playerCount;
        playerCountLabel.setText(PLAYER_COUNT_TEXT + playerCount);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    public int getPlayerCount() {
        return playerCount;
    }

}

@SuppressWarnings("serial")
class ChoicePanel extends JPanel {
    public static final String PLAYER_COUNT = "player count";
    private int playerCount = -1;

    public ChoicePanel(int maximumPlayers) {
        JPanel centralPanel = new JPanel(new GridLayout(0, 1, 5, 5));
        Border outsideBorder = BorderFactory.createTitledBorder("Choose Player Count:");
        int gap = 20;
        Border insideBorder = BorderFactory.createEmptyBorder(gap, 2 * gap, gap, 2 * gap);
        Border compoundBorder = BorderFactory.createCompoundBorder(outsideBorder, insideBorder);
        centralPanel.setBorder(compoundBorder);
        for (int i = 0; i < maximumPlayers; i++) {
            String text = "" + (i + 1) + " Player";
            if (i > 0) {
                text += "s";
            }
            JRadioButton radioButton = new JRadioButton(text);
            radioButton.addActionListener(new RadioListener(i + 1));
            centralPanel.add(radioButton);
        }
        setLayout(new GridBagLayout());
        add(centralPanel);        
    }

    public void setPlayerCount(int playerCount) {
        this.playerCount = playerCount;
        firePropertyChange(PLAYER_COUNT, -1, playerCount);
    }

    public int getPlayerCount() {
        return playerCount;
    }

    private class RadioListener implements ActionListener {
        private int count;

        public RadioListener(int count) {
            this.count = count;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            setPlayerCount(count);
        }
    }
}

将这些行从 Back class 中的主要方法移动到 Back 构造函数的末尾。它应该看起来像:

public Back(){
    super("title");
    setLayout(null);

    Icon i=new ImageIcon(getClass().getResource("1.png"));
    pane=new Container();

    thehandler hand=new thehandler();//konstruktori i handler merr nje instance te Background
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setContentPane().setBackground(Color.GREEN);
    setSize(700,500);
    setVisible(true);    
}

然后在你的 Nrlojtareve class 中输入

public void itemStateChanged(ItemEvent event){
    Back back = new Back();
}

此外,您可以从 Back class.

中完全删除 main 方法