printing just 1 label [ newbie ]

Hi all,

I'm a beginner at Java programming, and I'm trying to draw a panel with 2 labels beside each other, but for some reason just theLabelTwo is appreaing on the screen. This is the code I have written. Does anyone know what's wrong with it?

Thanks a lot,

Andre

import java.awt.*;

import javax.swing.*;

public class TfoMessageHeaderWindow

{

public TfoMessageHeaderWindow()

{

}

public TfoMessageHeaderWindow( String paramLabelOne, String paramLabelTwo )

{

theLabelOne = new JLabel( paramLabelOne );

theLabelTwo = new JLabel( paramLabelTwo );

thePanel = new JPanel( new GridLayout( 1, 2 ) );

thePanel.add( theLabelOne );

thePanel.add( theLabelTwo );

JFrame.setDefaultLookAndFeelDecorated( true );

theFrame = new JFrame( "Tfo Message Header" );

theFrame.getContentPane().add( thePanel );

}

public void drawWindow()

{

theFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

theFrame.getContentPane().add( theLabelOne );

theFrame.getContentPane().add( theLabelTwo );

theFrame.pack();

theFrame.setVisible(true);

}

private JFrame theFrame;

private JPanel thePanel;

private JLabel theLabelOne;

private JLabel theLabelTwo;

}

[1343 byte] By [sieg1974] at [2007-9-30 21:06:12]
# 1

This is bad:

theFrame.getContentPane().add( theLabelOne );

theFrame.getContentPane().add( theLabelTwo );

you have already added those labels to your panel, you may not add them to that content pane, too.

Just remove those two lines and it should work.

BTW - please use [code][/code] tags when posting code samples ...

thomas.behr at 2007-7-7 2:37:54 > top of Java-index,Desktop,Core GUI APIs...
# 2

Well your code is very confusing. You have two different methods that are attempting to built the GUI.

In one method you have:

theFrame.getContentPane().add( thePanel );

in another method you have:

theFrame.getContentPane().add( theLabelOne );

theFrame.getContentPane().add( theLabelTwo );

So you are actually replacing previously added components.

I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Using Layout Managers[/url] for an explanation of how Layout Managers work and a better example of keeping the GUI building in a single method.

camickr at 2007-7-7 2:37:54 > top of Java-index,Desktop,Core GUI APIs...