javaswingjbuttonjtoolbar

Changing the dimensions of Jbuttons within a JToolBar


I have a JToolBar with several Jbuttons on it which act as Icons in my program. I wanted to implement a button that, when pressed, increases the size of all my icons in the toolbar. For example:

Here I create my toolbar:

private JToolBar toolBar = new JToolBar();

Here I create some of my icons:

private JButton openButton = new JButton(am.getToolbarOpenFileAction());
private JButton closeButton = new JButton(am.getToolbarCloseFileAction());
private JButton undoButton = new JButton(am.getToolbarUndoAction());
private JButton redoButton = new JButton (am.getToolbarRedoAction());
private JButton cutButton = new JButton(am.getToolbarEditCutAction());

And then I have a method which creates the toolbar:

public void createToolbar() throws Exception {
    toolBar.setFloatable(false);
    toolBar.add(openButton);
    toolBar.add(closeButton);
 statusButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    statusButton.setFocusable(false);
    statusButton.setBorderPainted(false);
    statusButton.setContentAreaFilled(false);
    statusButton.setText("Status");
    statusButton.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
    setCompileStatus(1);
}

However no matter what I do I can't seem to find a way to alter the JButton sizes in the toolbar. Does anyone have any suggestions for how I can implement a method to alter the button size? Would it be better to alter the size of the toolbar or the buttons itself?

Thanks in advance.


Solution

  • Try adding the buttons to a JPanel and then finally add the JPanel to the toolbar. For setting the size of the button,try the setPreferredSize() method. Check the below and see:

    openButton.setPreferredSize(new Dimension(100, 20));
            panel.add(openButton); //add button to panel
            toolBar.add(panel);//add panel to toolbar
            add(toolBar);//add toolbar to frame