JLabel,FlowLayout。以JLabel为中心?

时间:2014-06-12 19:48:03

标签: java text jframe center jlabel

所以我创造了这个"彩票"我已经尝试了各种各样的东西来将文本集中在我的JLabel上,但它只是从屏幕中间的右边开始。这是我的代码和我的意思的图片。

这是我第一次在此表单上发帖,如果我错过了某些内容,请随时纠正我。

The Lottery

代码:

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.HeadlessException;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
 * Author Samy
 */
public class Game extends JFrame {
    public Game() throws HeadlessException{

        int width = 720;
        int height = width/16*9;

        setSize(width,height);
        setTitle("The Lottery - V1.0");
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        setLayout(new FlowLayout());

        String winnings;
        double lotteryChance = Math.random()*100;

        if (lotteryChance > 50) {
            winnings = ("You've won $100!");
        } else if (lotteryChance < 50 && lotteryChance > 20) {
            winnings = ("You've won $500!");
        } else if (lotteryChance < 20 && lotteryChance > 5) {
            winnings = ("You've won $2,000!");
        } else if (lotteryChance < 5 && lotteryChance > 1) {
            winnings = ("You've won $5,000!");
        } else if (lotteryChance < 1 && lotteryChance > 0.1) {
            winnings = ("You've won $25,000!");
        } else if (lotteryChance < 0.1 && lotteryChance > 0.01) {
            winnings = ("You've won $50,000!");
        } else if (lotteryChance < 0.01 && lotteryChance > 0.001) {
            winnings = ("You've won $250,000!");
        } else if (lotteryChance < 0.001 && lotteryChance > 0) {
            winnings = ("YOU'VE WON THE JACKPOT! $1,000,000!!!");
        } else winnings = ("Something went wrong, no winnings this round.");

        int number = 74;
        JLabel label = new JLabel("<HTML>The Lottery<BR>Authored by: Samy<BR><BR>-=Prize Board=-<BR><BR>100  - 50:     $100<BR>50   - 20:     $500<BR>20   - 5:      $2,000<BR>5    - 1:      $5,000<BR>1    - 0.1:    $25,000<BR>0.1  - 0.01:   $50,000<BR>0.01 - 0.001:  $250,000<BR>0.001 - 0.0001: $1,000,000<BR><BR>Your number is: "+lotteryChance+"<BR><BR>"+winnings+"</HTML>");


        getContentPane().add(label);


    }
    public static void main(String args[]){
        new Game().setVisible(true);
    }
}

2 个答案:

答案 0 :(得分:1)

这是我使用Swing组件的彩票游戏的一个版本,以展示Java Swing应用程序的外观。

enter image description here

我将所有Java类放在一起,以便于复制和粘贴。这些类应该在单独的文件中。

以下是我对代码所做的更改。

  1. 在main方法中,我将开始代码放在SwingUtilities invokeLater方法调用中。我这样做是为了将Swing组件定义和执行放在Event Dispatch thread

  2. 在Game类中,我使用了JFrame,而不是扩展JFrame。您应该扩展Swing组件的唯一时间是覆盖其中一个组件方法。

  3. 我创建了两个JPanel来放入JFrame。顶级JPanel,WinningsPanel,包含彩票奖励表。我使用了一个JTable来分配值。底部JPanel,ButtonPanel,包含一个JButton,让应用程序生成一个数字并显示彩票奖。

  4. 我创建了两个模型类。第一个模型类LotteryLine保存彩票表中一行的值。第二个模型类GameModel持有整个彩票表并生成随机数。

  5. 我为JTable创建了一个彩票表模型。这允许我控制彩票表中值的显示。

  6. ButtonPanel包含一个控制器PickNumberActionListener,它生成一个随机抽奖号码并显示号码和奖金。

  7. 以下是代码:

    package com.ggl.testing;
    
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.HeadlessException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.NumberFormat;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.table.AbstractTableModel;
    /**
     * Author Samy
     */
    public class Game {
    
        private GameModel model;
    
        private JFrame frame;
    
        public Game() throws HeadlessException {
    
            model = new GameModel();
    
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("The Lottery - Version 1.0");
            frame.setLocationByPlatform(true);
            frame.setLayout(new BorderLayout());
    
            WinningsPanel wPanel = new WinningsPanel(model);
            frame.add(wPanel.getPanel(), BorderLayout.NORTH);
    
            ButtonPanel bPanel = new ButtonPanel(model);
            frame.add(bPanel.getPanel(), BorderLayout.SOUTH);
    
            frame.pack();
        }
    
        public JFrame getFrame() {
            return frame;
        }
    
        public static void main(String args[]){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Game().getFrame().setVisible(true);
                }
            });
        }
    
        public class LotteryLine {
    
            private double lowValue;
            private double highValue;
    
            private int prize;
    
            private NumberFormat nf = NumberFormat.getCurrencyInstance();
    
            public LotteryLine(double highValue, double lowValue, 
                    int prize) {
                this.highValue = highValue;
                this.lowValue = lowValue;
                this.prize = prize;
            }
    
            public double getLowValue() {
                return lowValue;
            }
    
            public double getHighValue() {
                return highValue;
            }
    
            public int getPrize() {
                return prize;
            }
    
            public String getFormattedPrize() {
                return nf.format(prize);
            }
    
            public String getLeftPaddedPrize() {
                StringBuilder builder = new StringBuilder();
                String s = getFormattedPrize();
    
                for (int i = s.length(); i < 16; i++) {
                    builder.append(' ');
                }
                builder.append(s);
    
                return builder.toString();
            }
    
        }
    
        public class GameModel {
    
            private double randomNumber;
    
            private List<LotteryLine> lotteryList;
    
            public GameModel() {
                this.lotteryList = new ArrayList<LotteryLine>();
                createLotteryList();
            }
    
            private void createLotteryList() {
                lotteryList.add(new LotteryLine(100D, 50D, 100));
                lotteryList.add(new LotteryLine(50D, 20D, 500));
                lotteryList.add(new LotteryLine(20D, 5D, 2000));
                lotteryList.add(new LotteryLine(5D, 1D, 5000));
                lotteryList.add(new LotteryLine(1D, 0.1D, 25000));
                lotteryList.add(new LotteryLine(0.1D, 0.01D, 50000));
                lotteryList.add(new LotteryLine(0.01D, 0.001D, 250000));
                lotteryList.add(new LotteryLine(0.001D, 0.0001D, 1000000));
            }
    
            public double generateRandomNumber() {
                this.randomNumber = Math.random() * 100D;
                return randomNumber;
            }
    
            public List<LotteryLine> getLotteryList() {
                return lotteryList;
            }
    
            public LotteryLine getLotteryLine(double randomNumber) {
                for (LotteryLine lotteryLine : lotteryList) {
                    if (randomNumber > lotteryLine.getLowValue()) {
                        return lotteryLine;
                    }
                }
                throw new IllegalArgumentException();
            }
        }
    
        public class WinningsPanel {
    
            private GameModel model;
    
            private JPanel panel;
    
            public WinningsPanel(GameModel model) {
                this.model = model;
                createPartControl();
            }
    
            private void createPartControl() {
                panel = new JPanel();
                panel.setLayout(new BorderLayout());
    
                JPanel labelPanel = new JPanel();
                labelPanel.setLayout(new BoxLayout(
                        labelPanel, BoxLayout.PAGE_AXIS));
    
                JLabel writtenLabel = new JLabel("Written by: Samy");
                writtenLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
                labelPanel.add(writtenLabel);
    
                labelPanel.add(Box.createVerticalStrut(20));
    
                JLabel prizeLabel = new JLabel("Prize Table");
                prizeLabel.setFont(new Font("default", Font.BOLD, 32));
                prizeLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
                labelPanel.add(prizeLabel);
    
                panel.add(labelPanel, BorderLayout.NORTH);
    
                LotteryTableModel tableModel = new LotteryTableModel(model);
    
                JTable lotteryTable = new JTable(tableModel);
                int height = tableModel.getRowCount() * 
                        lotteryTable.getRowHeight();
                lotteryTable.setPreferredScrollableViewportSize(
                        new Dimension(300, height));
                JScrollPane scrollPane = new JScrollPane(lotteryTable);
                panel.add(scrollPane, BorderLayout.CENTER);
            }
    
            public JPanel getPanel() {
                return panel;
            }
    
        }
    
        public class LotteryTableModel extends AbstractTableModel {
    
            private static final long   serialVersionUID    = 
                    7330112393676204265L;
    
            private GameModel model;
    
            private String[] columns = {"High Value", "Low Value", "Prize"};
    
            public LotteryTableModel(GameModel model) {
                this.model = model;
            }
    
            @Override
            public int getRowCount() {
                return model.getLotteryList().size();
            }
    
            @Override
            public int getColumnCount() {
                return columns.length;
            }
    
            @Override
            public String getColumnName(int columnIndex) {
                return columns[columnIndex];
            }
    
            @Override
            public Class<?> getColumnClass(int column) {
                switch (column) {
                    case 0:
                    case 1:
                        return Double.class;
                    case 2:
                        return String.class;
                    default:
                        return String.class;
                }
            }
    
            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                LotteryLine lotteryLine = 
                        model.getLotteryList().get(rowIndex);
                switch (columnIndex) {
                case 0: return lotteryLine.getHighValue();
                case 1: return lotteryLine.getLowValue();
                case 2: return lotteryLine.getLeftPaddedPrize();
                default: return "";
                }
            }
    
        }
    
        public class ButtonPanel {
    
            private GameModel model;
    
            private JLabel numberLabel;
            private JLabel prizeLabel;
    
            private JPanel panel;
    
            public ButtonPanel(GameModel model) {
                this.model = model;
                createPartControl();
            }
    
            private void createPartControl() {
                panel = new JPanel();
                panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    
                panel.add(Box.createVerticalStrut(10));
    
                JButton playButton = new JButton("Pick Number");
                playButton.addActionListener(new PickNumberActionListener());
                playButton.setAlignmentX(JButton.CENTER_ALIGNMENT);
                panel.add(playButton);
    
                panel.add(Box.createVerticalStrut(20));
    
                numberLabel = new JLabel(" ");
                numberLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
                panel.add(numberLabel);
    
                prizeLabel = new JLabel(" ");
                prizeLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
                panel.add(prizeLabel);
            }
    
            public void updateNumberLabel(double number) {
                StringBuilder builder = new StringBuilder();
                builder.append("Your number is ");
                builder.append(String.format("%.4f", number));
                numberLabel.setText(builder.toString());
            }
    
            public void updatePrizeLabel(String prize) {
                StringBuilder builder = new StringBuilder();
                builder.append("You've won ");
                builder.append(prize);
                prizeLabel.setText(builder.toString());
            }
    
            public JPanel getPanel() {
                return panel;
            }
    
            public class PickNumberActionListener implements ActionListener {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    double number = model.generateRandomNumber();
                    LotteryLine lotteryLine = model.getLotteryLine(number);
                    updateNumberLabel(number);
                    updatePrizeLabel(lotteryLine.getFormattedPrize());
                }
    
            }
    
        }
    }
    

答案 1 :(得分:0)

FlowLayout.CENTER传递给alignment参数的FlowLayout构造函数。

Here's the constructor doc

示例:

setLayout(new FlowLayout(FlowLayout.CENTER));

编辑:

尝试将<center> HTML标记添加到标签的HTML格式中。这应该使标签中的所有文本居中。