Adding an Icon to the Label of a JCheckBox Component
Unlike a button, setIcon() does not add an icon to the text
label. Rather, in a checkbox, the method is used to customize the
icons used to depict its state. However, by using the HTML
capabilities in a label, it is possible to add an icon to the label
without affecting the state-depicting icons. This example
demonstrates the technique.
// Define an HTML fragment with an icon on the left and text on the right.
// The elements are embedded in a 3-column table.
String label = "<html><table cellpadding=0><tr><td><img src=file:"
// The location of the icon
+ icon.gif"
+ "/></td><td width="
// The gap, in pixels, between icon and text
+ 3
+ "><td>"
// Retrieve the current label text
+ checkbox.getText()
+ "</td></tr></table></html>";
// Add the icon
checkbox.setText(label);
Post a comment