Java Swing JToolbar with panels: look & feel

后端 未结 1 1709
天涯浪人
天涯浪人 2021-01-16 19:59

I have a JToolbar that contains multiple JPanels (needed as I would like to have specific borders for each of them). Unfortunately the Look&Fee

相关标签:
1条回答
  • 2021-01-16 20:42

    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.

    test image

    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();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题