Jun 30

By default menus added to a JMenuBar will be left aligned. Often we want to shift some item to the right (for example a Help menu is often displayed to the right).

To right align a JMenu you can add some ‘glue’ to push subsequently added menus to the right. The ‘glue’ component will take up any available space, effectively pushing subsequent items to the right.

JMenuBar menubar = new JMenuBar();

// These menus will be left aligned by default

menubar.add(new JMenu("File"));
menubar.add(new JMenu("Edit"));

// add some glue so subsequent menus are pushed to the right

menubar.add(Box.createHorizontalGlue());

// This Help button will be right aligned

menubar.add(new JMenu("Help"));

written by objects \\ tags: , , ,

Apr 28

By default components added to a JToolBar will be left aligned. Often we want to shift some item to the right (for example a Help button is often displayed to the right).

The JToolBar uses a BoxLayout to layout it’s components. This allows us to simply add some ‘glue’ to push subsequently added components to the right.

JToolBar toolbar = new JToolBar();

// These buttons will be left aligned by default

toolbar.add(new JButton("Open"));
toolbar.add(new JButton("Save"));

// add some glue so subsequent items are pushed to the right

toolbar.add(Box.createHorizontalGlue());

// This Help button will be right aligned

toolbar.add(new JButton("Help"));

written by objects \\ tags: , , ,