Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is addSeparator() not working with my JToolBar?

I am having trouble getting a JSeparator to show up inside of a JToolBar. My toolbar is created as follows :

public class ToolBar extends JToolBar {
    super();

    FlowLayout layout = new FlowLayout(FlowLayout.LEFT, 10, 5);
    setLayout(layout);

    add(new JButton("Button 1"));
    addSeparator();
    add(new JButton("Button 2"));
    add(new JButton("Button 3"));
    addSeparator();

    // Show
    setVisible(true);
    setFloatable(false);

}

Any thoughts would be really appreciated, I have been trying to get this to work for way too long now >(

like image 899
Hamy Avatar asked Dec 06 '25 00:12

Hamy


2 Answers

Trying your code there, when I call the addSeparator() method it creates a space between the buttons but no visible separation line.

But if I change the method to addSeparator(new Dimension(20,20)) it then creates the visible separation line.

The problem could be that the default look and feel creates a separator of height 1 so you would be unable to see it.

I am running it on Mac OSX.

like image 162
Gordon Avatar answered Dec 07 '25 16:12

Gordon


The biggest problem you have is that there is no need to sub-class JToolBar and set layout on it. Just create an instance of it and start adding buttons and separators.

In general Swing team does not recommend sub-classing Swing components.

You code should look like:

JToolBar t = new JToolbar();

t.add(new JButton("Button 1"));
t.addSeparator();
t.add(new JButton("Button 2"));
t.add(new JButton("Button 3"));
t.addSeparator();

// Show
t.setVisible(true);
t.setFloatable(false);

The last advice would be not to use buttons. Use actions. This way same actions can be used on toolbar, menus ect. More info at http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html

UPDATE: The way the toolbar separator looks depends on LAF you're using.

like image 37
Eugene Ryzhikov Avatar answered Dec 07 '25 16:12

Eugene Ryzhikov