开发者

Why is addSeparator() not working with my JToolBar?

I am having trouble getting a JSeparator to show u开发者_运维问答p 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 >(


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.


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.


I met the same problem. I found that the root cause was caused from the maximum size.

After adjusting it, it became normal.

    // ---------------------------------------
    // debug below:
    // ---------------------------------------
    JSeparator separator = new JSeparator(JSeparator.VERTICAL);
    System.err.println("getMaximumSize(): " + separator.getMaximumSize());
    System.err.println("getMinimumSize(): " + separator.getMinimumSize());
    separator.setMaximumSize(new Dimension(2, separator.getMaximumSize().height));


    // ---------------------------------------
    // real sample below
    // ---------------------------------------
    // adds a vertical space bar
    toolBar.add(Box.createHorizontalStrut(5));

    // adds a vertical separator
    JSeparator separator = new JSeparator(JSeparator.VERTICAL);
    Dimension maximumSize = separator.getMaximumSize();
    maximumSize.width = 2;
    separator.setMaximumSize(maximumSize); // Important! Update it!
    toolBar.add(separator);

    // adds a vertical space bar
    toolBar.add(Box.createHorizontalStrut(5));

by TJ Tsai (tsungjung411@yahoo.com.tw)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜