Centering a JLabel in a JPanel

后端 未结 6 2153
情歌与酒
情歌与酒 2020-12-05 14:26

I have a panel derived from JPanel. I have a custom control derived from JLabel. I am attempting to center this custom JLabel on my pa

相关标签:
6条回答
  • 2020-12-05 14:56

    Forget all the LayoutManagers in the Java Standard Library and use MigLayout. In my experience it's much easier to work with an usually does exactly what you expect it to do.

    Here's how to accomplish what you're after using MigLayout.

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    import net.miginfocom.swing.MigLayout;
    
    public class Test
    {
        public static void main( String[] args )
        {
            JFrame frame = new JFrame( );
            JPanel panel = new JPanel( );
    
            // use MigLayout
            panel.setLayout( new MigLayout( ) );
    
            // add the panel to the frame
            frame.add( panel );
    
            // create the label
            JLabel label = new JLabel( "Text" );
    
            // give the label MigLayout constraints
            panel.add( label, "push, align center" );
    
            // show the frame
            frame.setSize( 400, 400 );
            frame.setVisible( true );
        }
    }
    

    Most of that is just boilerplate. The key is the layout constraint: "push, align center":

    align center tells MigLayout to place the JLabel in the center of its grid cell.

    push tells MigLayout to expand the grid cell to fill available space.

    0 讨论(0)
  • 2020-12-05 14:57

    Set GridBagLayout for JPanel, put JLabel without any GridBagConstraints to the JPanel, JLabel will be centered

    enter image description here

    example

    import java.awt.*;
    import javax.swing.*;
    
    public class CenteredJLabel {
    
        private JFrame frame = new JFrame("Test");
        private JPanel panel = new JPanel();
        private JLabel label = new JLabel("CenteredJLabel");
    
        public CenteredJLabel() {
            panel.setLayout(new GridBagLayout());
            panel.add(label);
            panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.add(panel);
            frame.setSize(400, 300);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    CenteredJLabel centeredJLabel = new CenteredJLabel();
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-05 14:57

    BoxLayout is the way to go. If you set up a X_AXIS BoxLayout, try adding horizontal glues before and after the component:

    panel.add(Box.createHorizontalGlue());
    panel.add(label);
    panel.add(Box.createHorizontalGlue());
    
    0 讨论(0)
  • 2020-12-05 14:57

    I don't like the answers here.

    I've never seen a valid use of a GridBagLayout ever in my career. Not saying there isn't one, just saying I haven't seen [a valid] one, and there might be correlation there. Moreover, adding a single JLabel to the middle of a Container might make it center for demonstrational purposes, but you're going to have a lot harder of a time later on if you try to continue to work with that over some other layouts.

    I do like the suggestion about the BoxLayout, because that is actually a great way to do it. That said, that answer is only part of the puzzle, hence why I'm dredging up a 7 year old question.

    My 'Answer'

    Really there is no short answer to your question. There is an exact answer to your question based on what you asked, but StackOverflow is about a community learning from each other, and I suspect you're trying to learn how to use layouts in general (or you were 7 years ago) and telling you to type a combination of keys to do exactly your demo case is not going to teach you the answer.

    I'm going to try not to explain any layouts that you can't web-search the answer for on your own (with a link to the Oracle tutorial at the end, because I think it explains the different layouts fairly well).

    BoxLayout

    BoxLayout is one way to do it, and there is already a code snippet to demo it above so I won't provide one. I'll expand on it to say that, just as mentioned, that only answers your question exactly, but doesn't really teach you anything. Glue, as the BoxLayout refers to it, basically gives you an equal amount of remaining real-estate between all the 'glue' currently in the Container. So, if you were to do something like

    panel.add(Box.createHorizontalGlue());
    panel.add(label);
    panel.add(Box.createHorizontalGlue());
    panel.add(otherLabel);
    

    You would find that your JLabel is no longer centered, because the 'glue' is only the remaining real-estate left, after two JLabels were added to the Container which will be equally divided between the two 'slots' (two calls to Container#add(Component) with a glue parameter) in theContainer`.

    BorderLayout

    BorderLayout is another way to go about this. BorderLayout is broken down into 5 regions. BorderLayout#CENTER, as you might guess, is the center region. The important note about this layout and how it centers things is how it obeys sizes of the Component that is in the center. That I won't detail though; the Oracle tutorial at the end covers it well enough if you're interested, I think.

    Worth Noting

    I suppose you could use a GridLayout, but it's a more simple way to do it over a GridBagLayout, which I already said even that I think is not a good approach. So I won't detail this one either.

    The Point of it All

    Now all that said, I think all LayoutManagers are worth a look. Just like anything else with relation to programming - use the tool that fits the job. Don't just assume because you used X layout before, that you should always use X layout and no other layout is viable. Figure out what you want your display to look like, and how you think it should behave with respect to resizing components, and then pick what you think would work best.

    Another dual meaning of picking the right tool, is that you don't have to just fit all of your components into one single Container and make one layout do everything. There is nothing stopping you (and I strongly encourage you to) use multiple Containers and group them all together. Control each Container with a layout that is appropriate for that section of the display, and a different layout for a different Container.

    Important!!

    The reason why this is very important is because each layout has rules and things that they obey, and other things that they respect, and then others that are effectively ignored (i.e. preferred, maximum, and minimum sizes, for instance). If you use different layouts [correctly], you will find your display accepts dynamically being resized while still obeying the shape that you wanted it to hold. This is a very important key difference between doing it the right way, and just settling with GridBagLayout.

    JPanel outer = new JPanel(new BorderLayout());
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
    JPanel southPanel = new JPanel(new CardLayout());
    
    outer.add(centerPanel, BorderLayout.CENTER);
    outer.add(southPanel, BorderLayout.SOUTH);
    

    Figure out what is appropriate to your scenario, and go with that. There is no one-size-fits-all unless you want something overly cumbersome and made redundant by other layouts (i.e. GridBagLayout).

    Oracle's Tutorial

    If you've made it this far, then I think you're looking for as much information as you can get. In which case, I strongly encourage you to read Oracle's tutorial on layout managers because it lays out general details of them all very well: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

    0 讨论(0)
  • 2020-12-05 15:02

    Supose your JLabel is called label, then use:

    label.setHorizontalAlignment(JLabel.CENTER);
    
    0 讨论(0)
  • 2020-12-05 15:04

    Use this.

    labelName.setHorizontalAlignment(SwingConstants.CENTER);
    

    or

    labelName.setHorizontalAlignment(JPanel.CENTER);
    

    Both of them must work.

    0 讨论(0)
提交回复
热议问题