Yeah! Adding JCheckBox to JButton is really gonna be simple, nothing more than 4 lines of code. Yes, it is. I said it right!! You need to check out the program, to know what is written over there. Three methods in JCheckBox you shouldn't forget are setOpaque(), setIcon() and setSelectedIcon(). Of course, there are other methods too which you must not forget, but these three are what we will be using here. And the beauty JButton stores the tiny JCheckBox in stomach.
The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)
import javax.swing.*;
import java.awt.*;
class JCheckBoxOnJButton extends JFrame
{
JCheckBox jc;
JButton jb;
public JCheckBoxOnJButton()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JCheckBox on JButton");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
jc=new JCheckBox("Check me");
// Set non-opaque, so that background
// isn't visible
jc.setOpaque(false);
// Set icon, selected icon (optional)
jc.setIcon(new ImageIcon("unchecked.gif"));
jc.setSelectedIcon(new ImageIcon("checked.gif"));
// Just to remove text outline for JCheckBox
jc.setFocusPainted(false);
// Create JButton, with no text
jb=new JButton();
// Set a layout
jb.setLayout(new GridBagLayout());
// Add JCheckBox to JButton
jb.add(jc);
// Add the JButton
add(jb);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new JCheckBoxOnJButton();
}
}
The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)
“In every CHOICES that we choose, There's always a RISK; But always remember that there's also a chance” - Kent Solatorio Lopez
No comments:
Post a Comment