Use the JToolBar's own layout, but add a horizontal glue between the last two buttons. This will space things out for you. For example:

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
@SuppressWarnings("serial")
public class BoxLayoutEg extends JPanel {
public BoxLayoutEg() {
String[] btnTexts = {"One", "Two", "Three", "Four", "Five", "Exit"};
JToolBar toolBar = new JToolBar();
for (int i = 0; i < btnTexts.length; i++) {
JButton button = new JButton(btnTexts[i]);
if (i != btnTexts.length - 1) {
toolBar.add(button);
toolBar.addSeparator();
} else {
toolBar.add(Box.createHorizontalGlue());
toolBar.add(button);
}
}
setLayout(new BorderLayout());
add(toolBar, BorderLayout.PAGE_START);
setPreferredSize(new Dimension(400, 300));
}
private static void createAndShowGui() {
BoxLayoutEg mainPanel = new BoxLayoutEg();
JFrame frame = new JFrame("BoxLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
As per VGR's comment:
It’s better to use createGlue(), so the stretched layout is preserved even if the JToolBar is floatable and is floated and re-docked vertically by the user.
and he's right. So change this:
} else {
toolBar.add(Box.createHorizontalGlue());
toolBar.add(button);
}
to this:
} else {
toolBar.add(Box.createGlue());
toolBar.add(button);
}
so that the separation persists even if the toolbar is placed in a vertical position
Also note that if you need to limit the size of the JTextField, you could set its maximal size to its preferred size, e.g.,
} else {
int columns = 10;
JTextField time = new JTextField(columns);
time.setMaximumSize(time.getPreferredSize());
toolBar.add(time);
toolBar.add(Box.createHorizontalGlue());
toolBar.add(button);
}