LDAdams
LDAdams

Reputation: 682

Java Swing and Component Positioning

I am creating a base class for the JFrames of my application. I would like to inject a JXSearchField in the top right and corner of all frames that inherit from this class. I have a web background and know CSS fairly well. The effect I am going for is a float:right; or Fixed position, where other elements are not effected by the height of this component.

An example of what I am talking about would be a JFrame with a JTabbedPane aligned at the top. My tab pane only has three tabs but my frame is 800px wide. This gives me plenty of space for my top right aligned search box but my tabbedpane is reserving that space for additional tabs. I want to float in or fix position my searchbox to overlay that space.

Upvotes: 3

Views: 1609

Answers (2)

oliholz
oliholz

Reputation: 7507

if I understand correctly, you want to paint the TextField over the JTabbedPane beside the Tabs?

There is no easy way in swing doing this. You can use a glassPane-Component which draw the TextField on top right. And set it to the Frame.

UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );

JFrame frame = new JFrame();
frame.setBounds( 50, 50, 800, 600 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

JPanel glasspane = new JPanel(new FlowLayout(FlowLayout.RIGHT));

frame.setGlassPane( glasspane );

glasspane.setOpaque( false );
JTextField textField = new JTextField("Search");
glasspane.add(textField);
glasspane.setVisible( true );

JTabbedPane tabs = new JTabbedPane();
tabs.setBorder( BorderFactory.createEmptyBorder( 10, 5, 5, 5 ) );
tabs.addTab( "Lorem", null );
tabs.addTab( "Ipsum", null );
tabs.addTab( "Dolor", null );
frame.setContentPane( tabs );
frame.setVisible( true );

Upvotes: 4

RMT
RMT

Reputation: 7070

A Good Layout that a lot of people use for organizing SWING components is the GridBagLayout

GridBagLayout

Upvotes: 0

Related Questions