簡體   English   中英

如何將JLabels添加到JFrame?

[英]How to add JLabels to JFrame?

我很確定我必須制作一個容器,並在win()lose()方法中將標簽添加到容器中。 但是我應該怎么做呢? 另外,如果您還有其他技巧可以使代碼更具可讀性和連貫性。

PS:這是我第一次使用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
            }});
    }
}

如何將JLabels添加到JFrame?

我很確定我必須制作一個容器並將標簽添加到win()和loss()方法中的容器中。

我不會使用那種方法。 沒有文本或圖標的標簽是不可見的(除非它具有可見的邊框)。 因此,在啟動時創建並添加沒有文本的標簽。 當獲勝或失敗時,設置一些文字。

如果布局拒絕為標簽添加空間而沒有任何文本(例如,在BorderLayoutPAGE_START中沒有高度),請在調用pack()之前向其中添加一些文本,然后再將其設置為沒有文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM