Java Swing JToolbar with panels: look & feel

。_饼干妹妹 提交于 2019-12-04 06:04:05

问题


I have a JToolbar that contains multiple JPanels (needed as I would like to have specific borders for each of them). Unfortunately the Look&Feel manager does not recognize the JPanels as belonging to a toolbar and the JButtons are thus renderer as normal buttons (i.e. without the special mouse-over effect you have on a toolbar).

Replacing the JPanels by JToolbars are not an option as the LAF renderer gives it a special background.

Any other options / hints?


回答1:


As shown below, you can change a toolbar's layout and add components as desired. You can also have an arbitrary number of toolbars. The L&F combo is shown here. Note that the addSeparator() method of JToolBar supplies a L&F-specific JToolBar.Separator.

import component.Laf;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;

/**
 * @see https://stackoverflow.com/a/16121288/230513
 */
public class JToolBarTest {

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
        // https://stackoverflow.com/a/11949899/230513
        f.add(Laf.createToolBar(f));
        f.add(createBar());
        f.add(createBar());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private JToolBar createBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.add(createPanel());
        toolBar.addSeparator();
        toolBar.add(createPanel());
        return toolBar;
    }

    private JPanel createPanel() {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder("Panel"));
        Action buttonAction = new AbstractAction("Button"){

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getActionCommand()
                    + " " + e.getSource().hashCode());
            }
        };
        panel.add(new JButton(buttonAction));
        panel.add(new JButton(buttonAction));
        return panel;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JToolBarTest().display();
            }
        });
    }
}


来源:https://stackoverflow.com/questions/16119600/java-swing-jtoolbar-with-panels-look-feel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!