2015-02-11 2 views
0

Я уверен, что мне нужно сделать контейнер и добавить метки в контейнер в методах win() и lose(). Но как мне это сделать? Кроме того, если у вас есть другие советы, чтобы сделать код более читаемым и последовательным.Как добавить JLabels в JFrame?

P.S. Это мой первый опыт использования Java Swing для программирования графики, поэтому я знаю, что код очень грязный. Я в основном только волнует, если программа работает так, как я хочу, чтобы это ...

PPS Были несколько переменных класса, но StackOverflow не позволил бы мне опубликовать их

public class TwoDBettingGame extends JFrame { 

    /** Constructor to setup the UI components */ 
    public TwoDBettingGame() { 
     Container cp = this.getContentPane(); 
     cp.setLayout(new FlowLayout(FlowLayout.CENTER)); 
     if (money == 0) { 
      money = 1000; 
     } 

     // Define the UI components 
     JLabel label1 = new JLabel("Your money: $"+String.valueOf(money)); 
     JLabel label2 = new JLabel("How much would you like to bet?"); 
     JLabel label3 = new JLabel("$"); 
     JTextArea textarea1 = new JTextArea(1, 3); 
     Icon heads = new ImageIcon(getClass().getResource("heads.png")); 
     Icon tails = new ImageIcon(getClass().getResource("tails.png")); 
     JButton buttonheads = new JButton(" Heads", heads); 
     JButton buttontails = new JButton(" Tails", tails); 

     // Define preferred characteristics 
     label1.setFont(new Font("Times New Roman", 1, 50)); 
     label2.setFont(new Font("Times New Roman", 1, 33)); 
     label3.setFont(new Font("Times New Roman", 1, 70)); 
     textarea1.setEditable(true); 
     textarea1.setFont(new Font("Times New Roman", 1, 60)); 
     buttonheads.setPreferredSize(new Dimension(200, 75)); 
     buttontails.setPreferredSize(new Dimension(200, 75)); 
     buttonheads.setFont(new Font("Times New Roman", 1, 30)); 
     buttontails.setFont(new Font("Times New Roman", 1, 30)); 

     // Create new panel with buttons 1 and 2 
     JPanel panel2 = new JPanel(); 
     panel2.add(buttonheads); 
     ((FlowLayout)panel2.getLayout()).setHgap(40); 
     panel2.add(buttontails); 

     // Add all UI components 
     cp.add(label1); 
     cp.add(label2); 
     cp.add(label3); 
     cp.add(textarea1); 
     cp.add(panel2); 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked 
     setTitle("Betting Game"); // "this" JFrame sets title 
     setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // or pack() the components 
     setResizable(false); // window can't be resized 
     setLocationRelativeTo(null); // puts window in center of screen 
     setVisible(true); // show it 

     // Add action listeners to buttons 
     buttonheads.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       sideBetOn = "heads"; 
       // Get TextArea text 
       String betString = textarea1.getText(); 
       try{ 
        bet = Integer.parseInt(betString); 
       } catch (NumberFormatException n) { 
        bet = 0; 
       } 
       buttonClicked(); 
      } 
     }); 
     buttontails.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       sideBetOn = "tails"; 
       // Get TextArea text 
       String betString = textarea1.getText(); 
       try{ 
        bet = Integer.parseInt(betString); 
       } catch (NumberFormatException n) { 
        bet = 0; 
       } 
       buttonClicked(); 
      } 
     }); 
    } 

    public void buttonClicked() { 
     if (bet > 0 && bet <= money) { 
      int x = rand.nextInt(2); 
      if (x == 0) { 
       coinOutcome = "heads"; 
      } else { 
       coinOutcome = "tails"; 
      } if (coinOutcome.equals(sideBetOn)) { 
       money = money + bet; 
       dispose(); 
       win(); 
       Wait(); 
      } else { 
       money = money - bet; 
       dispose(); 
       lose(); 
       Wait(); 
       if (money <= 0) { 
        System.exit(0); 
       } else { 
        dispose(); 
        main(null); 
       } 
      } 
     } 
    } 
    public void Wait() { 
     try { 
      Thread.sleep((long) (secs*1000)); //1000 milliseconds is one second. 
     } catch(InterruptedException ex) { 
      Thread.currentThread().interrupt(); 
     } 
    } 
    public void win() { 
     JFrame frame = new JFrame(); 
     frame.setLayout(new FlowLayout(FlowLayout.CENTER)); 

     // Define the UI components 
     JLabel label4 = new JLabel("The coin flip was " + coinOutcome + "."); 
     JLabel label5 = new JLabel("You won $" + bet + "!"); 

     // Define preferred characteristics 
     label4.setFont(new Font("Times New Roman", 1, 20)); 
     label5.setFont(new Font("Times New Roman", 1, 20)); 

     // Add all UI components 
     frame.add(label4); 
     frame.add(label5); 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked 
     setTitle("You Win!!!"); // "this" JFrame sets title 
     setSize(WINDOW_WIDTH2, WINDOW_HEIGHT2); // or pack() the components 
     setResizable(false); // window can't be resized 
     setLocationRelativeTo(null); // puts window in center of screen 
     setVisible(true); // show it 
    } 
    public void lose() { 
     JFrame frame = new JFrame(); 
     frame.setLayout(new FlowLayout(FlowLayout.CENTER)); 

     // Define the UI components 
     JLabel label4 = new JLabel("The coin flip was " + coinOutcome + "."); 
     JLabel label5 = new JLabel("You lost $" + bet + "!"); 

     // Define preferred characteristics 
     label4.setFont(new Font("Times New Roman", 1, 20)); 
     label5.setFont(new Font("Times New Roman", 1, 20)); 

     // Add all UI components 
     frame.add(label4); 
     frame.add(label5); 

     if (money <= 0) { 
      JLabel label6 = new JLabel("I'm sorry, you lost. Better luck next time..."); 
      label6.setFont(new Font("Times New Roman", 1, 12)); 
      frame.add(label6); 
     } 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked 
     setTitle("You Lose :("); // "this" JFrame sets title 
     setSize(WINDOW_WIDTH2, WINDOW_HEIGHT2); // or pack() the components 
     setResizable(false); // window can't be resized 
     setLocationRelativeTo(null); // puts window in center of screen 
     setVisible(true); // show it 
    } 

    /** The entry main() method */ 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       new TwoDBettingGame(); // Let the constructor do the job 
      }}); 
    } 
} 
+0

BTW - 1) 'new Font (« Times New Roman », 1, 20)' должен быть 'new Font (Font.SERIF, Font.PLAIN, 20)' для кросс-платформенной совместимости и проверки времени компиляции. Хотя я бы установил его как атрибут класса и использовал 'deriveFont (float size)' then after..2) Пожалуйста, используйте форматирование кода для фрагментов кода и кода, структурированных документов, таких как HTML/XML или ввода/вывода. Для этого выберите текст и нажмите кнопку '{}' в верхней части формы публикации/редактирования сообщения. 3) См. [Использование нескольких JFrames, Хорошая/Плохая Практика?] (Http://stackoverflow.com/q/9554636/418556) Для победы/проигрывания подумайте 'JDialog' .. –

ответ

3

Как добавить JLabels для JFrame?

Я уверен, что я должен сделать контейнер и добавить метки к контейнеру в выигрыше() и проиграть() методы ..

Я бы не использовать этот подход. Метка без текста или значка невидима (если у нее нет видимой границы). Поэтому создайте и добавьте ярлык при запуске без текста. Когда достигнута победа или потеря, установите некоторый текст.

Если макет отказывается добавить пространство для этикетки без какого-либо текста (например, в PAGE_START в виде BorderLayout он не будет иметь высоту), добавить текст перед pack() называется, и установить его без текста впоследствии.

Смежные вопросы