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

前端 未结 4 827
孤城傲影
孤城傲影 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: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

提交回复
热议问题