I'm attempting to create a custom JButton
that has interchangeable skin components. Using CardLayout
as the switching mechanism, I'm having difficulty with the JComponent
(i.e. skin component) laying flush across the JButton
.
For instance,
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public final class SkinsDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new JSkinnableButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class JSkinnableButton extends JButton{
private static final long serialVersionUID = -5167346969674067012L;
protected JSkinnableButton(){
super();
setLayout(new CardLayout()); // for interchangeability
add(new JSkinComponent(), "Skin");
}
}
private static final class JSkinComponent extends JComponent{
private static final long serialVersionUID = 2172542865655802012L;
protected JSkinComponent(){
super();
setOpaque(true);
setLayout(new FlowLayout()); // need layout manager
setBackground(Color.CYAN);
add(new JLabel("Skin"));
}
@Override
protected void paintComponent(Graphics g){
Graphics gCopy = g.create();
gCopy.setColor(getBackground());
gCopy.fillRect(0, 0, getWidth(), getHeight());
gCopy.dispose();
}
}
}
That's a really crude example, but I think it conveys my intentions clearly.
And this JButton
will be listening for property change events from a domain object and will update it's display accordingly.