将 jpanel 中的所有组件居中

Centering all the components in jpanel

我在将面板内的所有复选框居中时遇到问题我已经尝试过对面板使用一些布局,但是它与我想要的输出不匹配。正如您在输出中看到的那样,它在两边都重叠了。

这是我的代码

            total = new JLabel("Total: 0");
        compute = new JButton("Compute");
        exit = new JButton("exit");
        panel = new JPanel();
        panel.setBackground(Color.gray);
        panel2 = new JPanel();
        panel2.setBackground(Color.blue);
        panel3 = new JPanel();
        panel3.setBackground(Color.gray);
        panel4 = new JPanel();
        panel4.setBackground(Color.blue);
        panel5 = new JPanel();
        panel5.setBackground(Color.gray);
        
        panel.add(beverages);
        panel.add(a1);panel.add(a2);panel.add(a3);panel.add(a4);panel.add(a5);
        panel.add(a6);panel.add(a7);panel.add(a8);panel.add(a9);panel.add(a10);
        add(panel);
        panel2.add(snacks);
        panel2.add(b1);panel2.add(b2);panel2.add(b3);panel2.add(b4);panel2.add(b5);
        panel2.add(b6);panel2.add(b7);panel2.add(b8);panel2.add(b9);panel2.add(b10);
        add(panel2);
        panel3.add(burger);
        panel3.add(c1);panel3.add(c2);panel3.add(c3);panel3.add(c4);panel3.add(c5);
        panel3.add(c6);panel3.add(c7);panel3.add(c8);panel3.add(c9);panel3.add(c10);
        add(panel3);
        panel4.add(dessert);
        panel4.add(d1);panel4.add(d2);panel4.add(d3);panel4.add(d4);panel4.add(d5);
        panel4.add(d6);panel4.add(d7);panel4.add(d8);panel4.add(d9);panel4.add(d10);
        add(panel4);
        panel5.add(total);panel5.add(compute);panel5.add(exit);
        add(panel5);
        
        setLayout(new GridLayout(1,5,0,0));
        pack();
        setVisible(true);
        setSize(550,400);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Restaurant Menu");

Output

删除 setSize 并让 pack 完成它的工作。这将根据它们的首选布局大小和布局管理器安排,将 window 围绕其子组件“打包”,例如...

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.border.EmptyBorder;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Menu beverageMenu = new Menu("Beverages", Arrays.asList(new MenuItem[] {
                    new MenuItem("Coca-Coloa", 1),
                    new MenuItem("Mountain Dew", 1),
                    new MenuItem("Rootbeer", 1),
                    new MenuItem("Fruitsoda", 1),
                    new MenuItem("Royal", 1),
                    new MenuItem("C2", 1),
                    new MenuItem("Mango Shake", 1),
                    new MenuItem("Orange Juice", 1),
                    new MenuItem("Water", 1),
                    new MenuItem("Jack Daniels", 1),
                }));
                Menu snacksMenu = new Menu("Snacks", Arrays.asList(new MenuItem[] {
                    new MenuItem("Popcorn", 1),
                    new MenuItem("Potato chips", 1),
                    new MenuItem("Fries", 1),
                    new MenuItem("Chips 4", 1),
                    new MenuItem("Yogurt 5", 1),
                    new MenuItem("String chees 6", 1),
                    new MenuItem("Cereal 7", 1),
                    new MenuItem("Granola bars 8", 1),
                    new MenuItem("Gummy bears 9", 1),
                    new MenuItem("Pretzels 10", 1),
                }));
                Menu burgerMenu = new Menu("Burgers", Arrays.asList(new MenuItem[] {
                    new MenuItem("Double pattey burger", 1),
                    new MenuItem("Cheese burger 2", 1),
                    new MenuItem("Baacon burger", 1),
                    new MenuItem("Cheese & bacon burger", 1),
                    new MenuItem("Mushroom burger", 1),
                    new MenuItem("Pepperoni burger", 1),
                    new MenuItem("Quater-pound burger", 1),
                    new MenuItem("Spicy burger", 1),
                    new MenuItem("Chicken burger", 1),
                    new MenuItem("Pizza burger", 1),
                }));
                Menu dessertMenu = new Menu("Deserts", Arrays.asList(new MenuItem[] {
                    new MenuItem("Cacke", 1),
                    new MenuItem("Ice cream", 1),
                    new MenuItem("Cookies", 1),
                    new MenuItem("Lech flan", 1),
                    new MenuItem("Ube", 1),
                    new MenuItem("Mango graham", 1),
                    new MenuItem("Macaroons", 1),
                    new MenuItem("Brownies", 1),
                    new MenuItem("Pudding", 1),
                    new MenuItem("Meringue", 1),
                }));

                List<Menu> menus = new ArrayList<>(Arrays.asList(new Menu[] {
                    beverageMenu, snacksMenu, burgerMenu, dessertMenu
                }));

                JFrame frame = new JFrame();
                frame.add(new MainPane(menus));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MenuItem {
        private String description;
        private double price;

        public MenuItem(String description, double price) {
            this.description = description;
            this.price = price;
        }

        public String getDescription() {
            return description;
        }

        public double getPrice() {
            return price;
        }        
    }

    public class Menu {
        private String title;
        private List<MenuItem> items;

        public Menu(String title, List<MenuItem> items) {
            this.title = title;
            this.items = items;
        }

        public List<MenuItem> getItems() {
            return items;
        }

        public String getTitle() {
            return title;
        }
    }

    public class MainPane extends JPanel {
        public MainPane(List<Menu> menus) {
            setBorder(new EmptyBorder(4, 4, 4, 4));
            setLayout(new GridLayout(1, -1, 4, 0));

            for (int index = 0; index < menus.size(); index++) {
                Color backgroundColor = index % 2 == 0 ? Color.GRAY : Color.BLUE;
                MenuPane menuPane = new MenuPane(menus.get(index));
                menuPane.setBackground(backgroundColor);
                add(menuPane);
            }

            Color backgroundColor = menus.size() % 2 == 0 ? Color.GRAY : Color.BLUE;

            JPanel actionsPane = new JPanel(new GridBagLayout());
            actionsPane.setBackground(backgroundColor);
            GridBagConstraints actionGBC = new GridBagConstraints();
            actionGBC.gridwidth = GridBagConstraints.REMAINDER;

            actionsPane.add(new JLabel("Total: [=10=].00"), actionGBC);
            actionsPane.add(new JButton("Compute"), actionGBC);
            actionsPane.add(new JButton("Exit"), actionGBC);
            actionGBC.weighty = 1;
            actionsPane.add(new JLabel(), actionGBC);

            add(actionsPane);
        }
    }

    public class MenuPane extends JPanel {
        public MenuPane(Menu menu) {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = gbc.REMAINDER;
            add(new JLabel(menu.getTitle()), gbc);
            for (MenuItem menuItem : menu.getItems()) {
                JCheckBox cb = new JCheckBox(menuItem.getDescription());
                add(cb, gbc);
            }

            gbc.weighty = 1;
            add(new JLabel(), gbc);
        }
    }
}

有关详细信息,请参阅 Laying Out Components Within a Container


Last Question, How do I get the all the item price when if they click compute?

这是您要使用 observer pattern 的地方,它可用于通知相关方某些状态已更改或感兴趣的事情已发生,在这种情况下,用户已选择或取消选择 MenuItem,例如...

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.border.EmptyBorder;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Menu beverageMenu = new Menu("Beverages", Arrays.asList(new MenuItem[]{
                    new MenuItem("Coca-Coloa", 1),
                    new MenuItem("Mountain Dew", 1),
                    new MenuItem("Rootbeer", 1),
                    new MenuItem("Fruitsoda", 1),
                    new MenuItem("Royal", 1),
                    new MenuItem("C2", 1),
                    new MenuItem("Mango Shake", 1),
                    new MenuItem("Orange Juice", 1),
                    new MenuItem("Water", 1),
                    new MenuItem("Jack Daniels", 1),}));
                Menu snacksMenu = new Menu("Snacks", Arrays.asList(new MenuItem[]{
                    new MenuItem("Popcorn", 1),
                    new MenuItem("Potato chips", 1),
                    new MenuItem("Fries", 1),
                    new MenuItem("Chips 4", 1),
                    new MenuItem("Yogurt 5", 1),
                    new MenuItem("String chees 6", 1),
                    new MenuItem("Cereal 7", 1),
                    new MenuItem("Granola bars 8", 1),
                    new MenuItem("Gummy bears 9", 1),
                    new MenuItem("Pretzels 10", 1),}));
                Menu burgerMenu = new Menu("Burgers", Arrays.asList(new MenuItem[]{
                    new MenuItem("Double pattey burger", 1),
                    new MenuItem("Cheese burger 2", 1),
                    new MenuItem("Baacon burger", 1),
                    new MenuItem("Cheese & bacon burger", 1),
                    new MenuItem("Mushroom burger", 1),
                    new MenuItem("Pepperoni burger", 1),
                    new MenuItem("Quater-pound burger", 1),
                    new MenuItem("Spicy burger", 1),
                    new MenuItem("Chicken burger", 1),
                    new MenuItem("Pizza burger", 1),}));
                Menu dessertMenu = new Menu("Deserts", Arrays.asList(new MenuItem[]{
                    new MenuItem("Cacke", 1),
                    new MenuItem("Ice cream", 1),
                    new MenuItem("Cookies", 1),
                    new MenuItem("Lech flan", 1),
                    new MenuItem("Ube", 1),
                    new MenuItem("Mango graham", 1),
                    new MenuItem("Macaroons", 1),
                    new MenuItem("Brownies", 1),
                    new MenuItem("Pudding", 1),
                    new MenuItem("Meringue", 1),}));

                List<Menu> menus = new ArrayList<>(Arrays.asList(new Menu[]{
                    beverageMenu, snacksMenu, burgerMenu, dessertMenu
                }));

                JFrame frame = new JFrame();
                frame.add(new MainPane(menus));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MenuItem {
        private String description;
        private double price;

        public MenuItem(String description, double price) {
            this.description = description;
            this.price = price;
        }

        public String getDescription() {
            return description;
        }

        public double getPrice() {
            return price;
        }
    }

    public class Menu {
        private String title;
        private List<MenuItem> items;

        public Menu(String title, List<MenuItem> items) {
            this.title = title;
            this.items = items;
        }

        public List<MenuItem> getItems() {
            return items;
        }

        public String getTitle() {
            return title;
        }
    }

    public class MainPane extends JPanel {
        private CheckOutPane checkOutPane;
        public MainPane(List<Menu> menus) {
            setBorder(new EmptyBorder(4, 4, 4, 4));
            setLayout(new GridLayout(1, -1, 4, 0));

            for (int index = 0; index < menus.size(); index++) {
                Color backgroundColor = index % 2 == 0 ? Color.GRAY : Color.BLUE;
                MenuPane menuPane = new MenuPane(menus.get(index), new MenuPane.Observer() {
                    @Override
                    public void menuDidSelectItem(MenuPane source, MenuItem menuItem) {
                        checkOutPane.addMenuItem(menuItem);
                    }

                    @Override
                    public void menuDidDeselectItem(MenuPane source, MenuItem menuItem) {
                        checkOutPane.removeMenuItem(menuItem);
                    }
                });
                menuPane.setBackground(backgroundColor);
                add(menuPane);
            }

            Color backgroundColor = menus.size() % 2 == 0 ? Color.GRAY : Color.BLUE;
            checkOutPane = new CheckOutPane();
            checkOutPane.setBackground(backgroundColor);
            add(checkOutPane);
        }
    }

    public class CheckOutPane extends JPanel {
        private double runningTally = 0;
        private JLabel tallyLabel;
        private List<MenuItem> basket;

        public CheckOutPane() {
            basket = new ArrayList<>(8);
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            tallyLabel = new JLabel("Total: [=11=].00");

            add(tallyLabel, gbc);
            add(new JButton("Compute"), gbc);
            add(new JButton("Exit"), gbc);
            gbc.weighty = 1;
            add(new JLabel(), gbc);

            updateTally();
        }

        public double getOrderTotal() {
            return runningTally;
        }

        public List<MenuItem> getBasket() {
            return basket;
        }

        protected void updateTally() {
            tallyLabel.setText("Total: " + NumberFormat.getCurrencyInstance().format(getOrderTotal()));
        }

        public void addMenuItem(MenuItem menuItem) {
            basket.add(menuItem);
            runningTally += menuItem.getPrice();
            updateTally();
        }

        public void removeMenuItem(MenuItem menuItem) {
            if (basket.contains(menuItem)) {
                basket.remove(menuItem);
                runningTally -= menuItem.getPrice();
                updateTally();
            }
        }
    }

    public class MenuPane extends JPanel {
        public interface Observer {
            public void menuDidSelectItem(MenuPane source, MenuItem menuItem);
            public void menuDidDeselectItem(MenuPane source, MenuItem menuItem);
        }
        private Observer observer;
        public MenuPane(Menu menu, Observer observer) {
            this.observer = observer;
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = gbc.REMAINDER;
            add(new JLabel(menu.getTitle()), gbc);
            for (MenuItem menuItem : menu.getItems()) {
                JCheckBox cb = new JCheckBox(menuItem.getDescription());
                cb.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (cb.isSelected()) {
                            observer.menuDidSelectItem(MenuPane.this, menuItem);
                        } else {
                            observer.menuDidDeselectItem(MenuPane.this, menuItem);
                        }
                    }
                });
                add(cb, gbc);
            }

            gbc.weighty = 1;
            add(new JLabel(), gbc);
        }
    }
}