2016-01-22 1 views
-2

Я создал 2 программы (Background и NrLojtareve) с использованием Java GUI, где каждый из них создает шаг игры. Каждая программа имеет свой собственный основной метод.Подключение 2 разных программ в Java (каждый из них имеет свой основной метод)

Все, что я хочу сделать, это выполнить первую программу (NrLojtareve), которая включает в себя 4 переключателя для отображения другой страницы, которую я создал с помощью другой программы (Background).

Итак, переходим с первого шага игры ко второму. Поэтому обработчик класса NrLojtareve вызывает класс Background.

Может ли кто-нибудь показать мне, как вызвать вторую программу с первого или как отобразить второй графический интерфейс после выбора переключателя из первой программы?


Вот код.

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);  
    } 
} 
+0

Обратите внимание, что я не являюсь вашим избирателем, но также, пожалуйста, см. Изменение моего ответа на примере игры с вашим кодом. –

+0

Хорошо спасибо @Hovercraft Full Of Eels – user5827762

+0

Добро пожаловать и удачи! –

ответ

0

Переместить эти строки из основного метода в классе Назад к концу Назад конструктор. Он должен выглядеть следующим образом:

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 класс поставил

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

Кроме того, вы можете удалить основной метод полностью из класса Назад.

+0

Спасибо, это то, о чем я просил! – user5827762

+0

Без проблем, рад помочь! – jheimbouch

+2

@ user5827762: Я рад, что у вас есть ответ, но я должен не согласиться. Я занимаюсь тяжелым кодированием Swing в течение нескольких лет, и, хотя этот совет работает, это не очень хороший дизайн, так как пользователю не понравится, что на них обменивается Windows. Намного лучше обмениваться мнениями. Извините, но я должен назвать это, как я его вижу. –

3

Предложения:

  • Избегайте создания классов, расширяющих JFra меня. Это делает вас краской и заставляет вас использовать класс как JFrame.
  • Вместо этого передайте свой Swing GUI в сторону создания JPanels. Это даст вам гораздо большую гибкость, поскольку вы можете поместить JPanels в JFrames, если вы хотите отображать их как автономные графические интерфейсы или в JDialogs или JOptionPanes или другие JPanels.
  • После выполнения этого кода создайте третий JPanel, который использует CardLayout, и добавьте вышеприведенный графический интерфейс JPanel к этому «master» CardLayout, используя JPanel. Затем вы можете легко менять свои «взгляды», используя метод CardLayout show(...).
  • Затем создайте еще один класс, в котором нет ничего, кроме основного метода, в основном методе создайте свой JFrame, добавьте мастер CardLayout - используя JPanel в JFrame и покажите его.
  • CardLayout Tutorial link

Другие советы:

  • Избегайте null макетов и setBounds(...) как чумы, поскольку их использование приведет к созданию жестких GUI, которые не могут быть использованы внутри JScrollPane, очень трудно расширять, улучшать и отлаживать. Вместо этого изучите и используйте менеджеров макетов.
  • Другой вариант - отобразить первый графический интерфейс в виде модального диалога, такого как 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); 
     } 
    } 
} 
Смежные вопросы