简体   繁体   中英

how to Put JLabel text over a JTextField

how to add a JLabel simple text over/above a JTextField. I tried many commands as you can see in my code but nothings works.

this is a snapshot of my code

private JPanel createTextPanel() {
        int panelWidth = PANEL_SIZE.width;
        int panelHeight =  PANEL_SIZE.height/3;
        Dimension panelSize = new Dimension(panelWidth,panelHeight);
        JPanel textPanel = new JPanel();
        textPanel.setPreferredSize(panelSize);
        //textPanel.setLayout(null);
        /* Add text */
        JLabel Text_RED = new JLabel();
        Text_RED.setText("Red");
        //Text_RED = new JLabel("\nRED\n");
        //Text_RED.setHorizontalTextPosition(SwingConstants.TOP);
        //Text_RED.setVerticalAlignment(SwingConstants.TOP);
        Red = new JTextField(3);
        //Red.setVerticalAlignment(JTextField.TRAILING );
        Red.setLocation(100,100);

        //Red.setLocation(50, 50);
        JLabel Text_Green = new JLabel("Green");
        Green = new JTextField(3);

        JLabel Text_Blue = new JLabel("Blue");
        Blue = new JTextField(3);

        //setLayout(new GridLayout(2,2,10,10));
        textPanel.add(Text_RED);
        textPanel.add(Red);

        textPanel.add(Text_Green);
        textPanel.add(Green);

        textPanel.add(Text_Blue);
        textPanel.add(Blue);

        return textPanel;
    }

Suggestions:

  • Don't use null layouts and absolute positioning. While it seems initially that using these tools is the easiest way to create complex GUI's, it's really a newbie fallacy, as the more you understand and use the layout managers, the more you'll find that they make the job of creating GUI's much easier, and the results much more attractive.
  • Learn about and use the layout managers. Tutorial link .
  • Consider using a BorderLayout and adding your JLabel BorderLayout.CENTER and the JTextField at BorderLayout.PAGE_END. As a side note, I generally avoid placing JTextFields in a BorderLayout.CENTER position since this will cause horizontal stretching of the field if the GUI changes size, which I don't think is aesthetically pleasing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM