Centering JLabels inside JPanels

前端 未结 1 969
北海茫月
北海茫月 2021-01-14 06:41

I\'m making a score-keeping program, but I\'m running into a problem. What I\'ve tried to do is have a JPanel at the top that contains two JPanels, which, in turn, contains

相关标签:
1条回答
  • 2021-01-14 07:16

    Invoking pack() is a critical step in using layouts. This example uses JLabel.CENTER and GridLayout to center the labels equally as the frame is resized. For simplicity, the center panel is simply a placeholder. This somewhat more complex example uses a similar approach along with java.text.MessageFormat.

    Addendum: But how would I apply pack() to my code?

    Simply invoke pack() as shown in the examples cited. I don't see an easy way to salvage your current approach of setting sizes extrinsically. Instead, override getPreferredSize() in a JPanel for your main content. No matter the screen size, your implementation of paintComponent() should adapt to the current size, for example.

    image

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    /** @see https://stackoverflow.com/a/14422016/230513 */
    public class Scores {
    
        private final JLabel[] nameLabel = new JLabel[]{
            new JLabel("Team 1", JLabel.CENTER),
            new JLabel("Team 2", JLabel.CENTER)};
    
        private void display() {
            JFrame f = new JFrame("Scores");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel teamPanel = new JPanel(new GridLayout(1, 0));
            teamPanel.add(nameLabel[0]);
            teamPanel.add(nameLabel[1]);
            f.add(teamPanel, BorderLayout.NORTH);
            f.add(new JPanel() {
    
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(320, 240);
                }
            }, BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new Scores().display();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题