简体   繁体   中英

text field not appearing or not reacting on location code

strange thing, i want to add text field next to the label. When i'm doing that it's not reacting on .setLocation command and background color does not change. Dont know why. But when i set frame Layout to null , than background command working and changing the color , but text field are not showing. Strange. i tried with adding text field through panel, not working, by simple frame.add(textField) , not working.

public class EcrWindow extends JFrame {

    JFrame ecrFrame;
    JLabel ecr;
    static JTextField ecrTitle;

    public static void main(String[] args)
    {
        new EcrWindow();
    }

    EcrWindow()
    {
        JPanel p = new JPanel();

    ecrFrame = new JFrame ("ECR WINDOW");
    ecrFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    ecrFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    ecrFrame.setResizable(true);
    ecrFrame.getContentPane().setBackground(Color.RED);
    //ecrFrame.setLayout(null);

    ecr = new JLabel("Emergancy Change title");
    ecr.setSize(ecr.getPreferredSize());
    ecr.setLocation(100,50);
    ecrFrame.add(ecr);


    ecrTitle = new JTextField();
    ecrTitle.setColumns(30);
    //ecrTitle.setSize(ecrTitle.getPreferredSize());
    ecrTitle.setLocation(150,50);
    p.add(ecrTitle);                                // adding text field to the panel, and panel adding to the frame
    ecrFrame.add(p);
   // ecrFrame.add(ecrTitle);


    ecrFrame.setVisible(true);

    }
}

The ContentPane of the Frame is not visible as soon as you add the Panel p to the frame. The content pane will be hidden by the panel which will consume the whole available space in the frame.

When you set the Layout to null, you do not see the Panel p any more as there is no information where it is rendered in the frame (the TextBox should also disappear when you set the Layout to null). This is why the red background is visible then.

Please try to add the following line to your code before you add the Panel p to the frame:

p.setBackground(Color.RED);

Then you should see a red background which is actually the Panel p .

Regarding the layout, you shouldn't use setLocation(). It is much better to use a different layout mechanism with a proper LayoutManager. See also this answer .

You can use setLocation() if you use absolute positioning . But that would mean that you effectively write a layout manager by hand. I would advise you to read the guide Laying Out Components Within a Container - there are various explanations and examples you can build up upon.

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