下面的示例向您展示了如何自定义JButton摇摆组件的图标。
package org.nhooo.example.swing;
import javax.swing.*;
import java.awt.*;
public class JButtonCustomIcon extends JFrame {
public JButtonCustomIcon() throws HeadlessException {
initialize();
}
private void initialize() {
setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
JButton button = new JButton("Press Me!");
// 下面是我们如何为JButton摆动设置各种图标
//零件。有默认图标,已选中,已禁用,已显示
// 和翻转图标。
button.setIcon(new ImageIcon("default.png"));
button.setSelectedIcon(new ImageIcon("selected.png"));
button.setDisabledIcon(new ImageIcon("disabled.png"));
button.setDisabledSelectedIcon(new ImageIcon("disabledSelected.png"));
button.setPressedIcon(new ImageIcon("pressed.png"));
button.setRolloverIcon(new ImageIcon("rollover.png"));
button.setRolloverSelectedIcon(new ImageIcon("rolloverSelected.png"));
getContentPane().add(button);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JButtonCustomIcon().setVisible(true);
}
});
}
}