如何将JLabel添加到JFrame?

时间:2015-02-11 07:48:40

标签: java swing jframe jlabel

我非常确定我必须制作一个容器,并在win()lose()方法中将标签添加到容器中。但是我该怎么做呢?此外,如果您有任何其他提示,可以使代码更具可读性和连贯性。

P.S。这是我第一次使用Java Swing编程图形,所以我知道代码非常混乱。我大多只关心程序是否按照我想要的方式工作......

P.P.S有一些类变量,但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
            }});
    }
}

1 个答案:

答案 0 :(得分:3)

  

如何将JLabel添加到JFrame?

     

我非常确定我必须制作一个容器并在win()和lose()方法中将标签添加到容器中。

我不会使用这种方法。没有文字或图标的标签是不可见的(除非它有可见的边框)。因此,在启动时创建并添加标签,不带文本。当实现胜负时,请设置一些文字。

如果布局拒绝为没有任何文字的标签添加空间(例如PAGE_START BorderLayout中没有任何高度),请在pack()之前添加一些文字。被调用,然后将其设置为无文本。