Reputation: 2671
I need to layout several components using nothing but standard Swing layout managers or Mig.
I have a control similar to that of a media players track bar & control buttons (i.e. rewind, play, fast forward below a track bar that indicates current position):
<-----------------[CURRENT POSITION]----------------------------------------->
[-------------------------------[RW][PLAY][FF]------------------------------->
The play button must remain 100% centered with the track bar. However, I need to introduce an additional check box that is right aligned without offsetting the other buttons, like this:
<-----------------[CURRENT POSITION]----------------------------------------->
[-[CB]--------------------------[RW][PLAY][FF]------------------------------->
Upvotes: 0
Views: 669
Reputation: 2671
I ended up using the following:
setLayout(new MigLayout("fillx", "[200][][200]", ""));
JPanel buttonPanel = new JPanel();
buttonPanel.add(firstButton);
buttonPanel.add(reverseButton);
buttonPanel.add(playButton);
buttonPanel.add(forwardButton);
buttonPanel.add(lastButton);
add(maintainCurrentTimeCheckBox, "grow");
add(buttonPanel, "grow");
add(currentTimeLabel, "grow");
Upvotes: 0
Reputation: 6054
You can use a GridLayout with 1 row and a couple columns; GridLayout automatically spaces out your components evenly to fit the Panel.
So you can have something like
controlsPanel.setLayout(new GridLayout(1, 5));
controlsPanel.add(checkbox);
controlsPanel.add(rewindButton);
controlsPanel.add(playButton); //in the center
controlsPanel.add(fastForwardButton);
controlsPanel.add(new JLabel()); //placeholder for the grid
and the GridLayout will automatically make all those the same size and spacing.
If you wanted the checkbox to be farther away from your play button, you can use more columns and fill the empty space in between with more placeholders.
controlsPanel.setLayout(new GridLayout(1, 7));
controlsPanel.add(checkbox);
controlsPanel.add(new JLabel); //left placeholder
controlsPanel.add(rewindButton);
controlsPanel.add(playButton); //in the center
controlsPanel.add(fastForwardButton);
controlsPanel.add(new JLabel); //right placeholder
controlsPanel.add(new JLabel()); //final placeholder
Upvotes: 1
Reputation: 324118
[-[CB]--------------------------[RW][PLAY][FF]---------------------------[DC]>
Add a "dummy component" (DC) to the right side of the panel. Set its width to be the same as the width as the check box. This will then keep your buttons centered on the screen. You should be able to use Box.createHorizontalStrut(...) for this component.
You could do the row layout using a horizontal BoxLayout. Add the check box, then some horizontal glue, then the buttons, some more horizontal glue and finally the horizontal strut.
Upvotes: 1