Java Swing and component positioning

I am creating a base class for the JFrames of my application. I would like to add a JXSearchField in the upper right corner and in the corner of all frames that inherit from this class. I have a web background and know CSS well. The effect I'm going to do is float: right; or a fixed position where other elements do not affect the height of this component.

An example of what I'm talking about would be a JFrame with a JTabbedPane aligned at the top. My tab bar has only three tabs, but my frame is 800 pixels wide. This gives me a lot of space for my window located in the upper right, but my tab reserves this space for additional tabs. I want to swim or fix the position of my search query to overlay this space.

+3
source share
2 answers

If I understand correctly, do you want to draw a TextField over the JTabbedPane next to the tabs?

There is no easy way to do this in swing. You can use glassPane-Componentthat draw a TextField in the upper right corner. And set it in a 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 );
+4
source

The good layout that many use to organize SWING components is GridBagLayout

GridBagLayout

0
source

All Articles