Get and set gap between text and icon for a JButton in Java

Description

The following code shows how to get and set gap between text and icon for a JButton.

Example


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
//  w  w  w.  j a va2  s .  c  o m
public class Main {
  public static void main(String[] argv) throws Exception {
    JFrame frame = new JFrame("DefaultButton");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
    JButton button = new JButton();
    // Add rollover icon
    Icon rolloverIcon = new ImageIcon("r.gif");
    button.setRolloverIcon(rolloverIcon);

    // Add pressed icon
    Icon pressedIcon = new ImageIcon("p.gif");
    button.setPressedIcon(pressedIcon);

    // To remove rollover icon, set to null
    button.setRolloverIcon(null);

    // To remove pressed icon, set to null
    button.setPressedIcon(null);
    
    // Get gap size; default is 4
    int gapSize = button.getIconTextGap();

    // Set gap size
    button.setIconTextGap(8);
    
    frame.add(button);
    frame.setSize(300, 200);
    frame.setVisible(true);

  }
}

The code above generates the following result.

Get and set gap between text and icon for a JButton in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer