tags:

views:

287

answers:

3

I have created a JFrame, and now I want to add a JLabel and textfields in it. Please tell me how to do that. I have used the following code but its not working.

JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);

Problem is this code is showing frame window but it is not showing label in it. Please help.

+1  A: 
OscarRyz
+1 for OSX frames with alpha background
willcodejavaforfood
A: 

The main issue is the layout being used by the content pane (most likely JRootPane.RootLayout, A custom layout manager that is responsible for the layout of layeredPane, glassPane, and menuBar ) is not the best. This code should work;

JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
i_frame.getContentPane().setLayout(new FlowLayout());
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);

setting a different layout does the trick

n002213f
thanks for helping.. now i have tried this layout but even then it is not working.. what shall i do now?
@S.A.: Whatever you want. Continue adding components to your form. If I were you I would use a visual form editor instead of manually placing things as you seem to be a beginner in Java.
kd304
A: 

The problem is that you are adding a second component (Box.createRigidArea) in the same layout position (BorderLayout.CENTER) as the Label.
JFrame.add() results in the same as JFrame.getContentPane().add()...
So the label is being replaced by the RigidArea.
Try this:

    JFrame i_frame = new JFrame("Select Locations");
    i_from = new JLabel("From");
    i_frame.getContentPane().add(i_from);
    // i_frame.add(Box.createRigidArea(new Dimension(2,0)));
    i_frame.setLocationRelativeTo(null);
    i_frame.setSize(200,200);
    i_frame.setVisible(true);

to add more components, change the LayoutManager:

    JFrame i_frame = new JFrame("Select Locations");
    JLabel i_from = new JLabel("From");
    Container pane = i_frame.getContentPane();
    pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS));  // any LayoutManager you need
    pane.add(i_from);
    pane.add(Box.createRigidArea(new Dimension(2,0)));  // space after JLabel ?
    i_frame.setSize(200,200);  // better done before setLocationRelativeTo
    i_frame.setLocationRelativeTo(null);
    i_frame.setVisible(true);

Note: if you "just" want to add an empty border to your label, use a setBorder() instead of the RigidArea:

    i_from.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

[]]

Carlos Heuberger