How to place JLabel on top right corner just below the title bar?

前端 未结 4 819
孤城傲影
孤城傲影 2021-01-27 12:52

Hello I read about Layouts but didn\'t get which one to use for my application. I want to add image to JPanel and place JLabel on op right corner just below the title bar.

相关标签:
4条回答
  • 2021-01-27 13:19

    Since you have a dominating feature in your layout (the image) you probably want to use a BorderLayout as your main layout.

    frame.getContentPane().setLayout(new BorderLayout(4, 4));
    

    then add the image to the BorderLayout.CENTER

    next the JLabel wants to go in the BorderLayout.NORTH

    Now, if you do that, it won't go to the far right, so create a JPanel for the north, add the JLabel to the panel, and place the panel in the north.

    Now you need a layout for the north panel. A BoxLayout will work

    northPanel.add(Box.createHorizontalGlue());
    northPanel.add(label);
    
    0 讨论(0)
  • 2021-01-27 13:23

    In above code i have set required location by setBound but it does not work.

    There is no need to do that. You should not be using setBounds(...). Use layout managers:

    JLabel label = new JLabel("Some Text");
    label.setHorizontalAlignment(JLabel.RIGHT);
    frame.add(label, BorderLayout.NORTH);
    
    0 讨论(0)
  • 2021-01-27 13:26

    A possibility with a GridBagLayout:

    import java.awt.*;
    import javax.swing.*;
    
    public class MyPanel extends JPanel {
    
        public MyPanel() {
            setLayout(new GridBagLayout());
            add(new JLabel("TOP RIGHT"), new GridBagConstraints(
                    0, // gridx
                    0, // gridy
                    1, // gridwidth
                    1, // gridheight
                    1, // weightx
                    1, // weighty
                    GridBagConstraints.NORTHEAST, // anchor <------------
                    GridBagConstraints.NONE, // fill
                    new Insets(0, // inset top
                    0, // inset left
                    0, // inset bottom
                    0), // inset right
                    0, // ipadx
                    0)); // ipady
        }
    
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setResizable(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new MyPanel());
            frame.setSize(400, 400);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }
    

    Nicolas

    0 讨论(0)
  • 2021-01-27 13:35

    Make sure you have

    panel.setLayout(null);
    

    if you wish to position the components yourself.

    But identifying and using a layout manager that would fit your needs would make things easier as the complexity of your application grows.

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