简体   繁体   中英

How to add JLabels to JFrame?

I'm pretty sure I have to make a container and add the labels to the container in the win() and lose() methods. But how should I do this? Also, if you have any other tips to make the code more readable and coherent.

PS This is my first time using Java Swing to program graphics, so I know the code is very messy. I mostly just care if the program works the way I want it to...

PPS There were a few class variables, but StackOverflow wouldn't let me post them

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

How to add JLabels to JFrame?

I'm pretty sure I have to make a container and add the labels to the container in the win() and lose() methods..

I wouldn't use that approach. A label without text or icon is invisible (unless it has a visible border). So create and add the label at start-up with no text. When a win or loss is achieved, set some text.

If the layout refuses to add space for the label without any text (eg in the PAGE_START of a BorderLayout it would have no height), add some text to it before pack() is called, and set it to no text afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM