Interchangeable JComponent skins for JButton

I am trying to create a custom JButton that has interchangeable skin components. Using CardLayout as a switching mechanism, I am having difficulty with a JComponent (i.e. a skin component) imposing a reset on 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(); } } } 

enter image description here


This is a really rude example, but I think it clearly conveys my intentions.

And this JButton will listen for property change events from the domain object and update its display accordingly.

+4
source share
1 answer

In your JSkinnableButton space runs through the marker and button border.

 protected JSkinnableButton(){ super(); setLayout(new CardLayout()); // for interchangeability setMargin(new Insets(0,0,0,0)); setBorder(BorderFactory.createEmptyBorder()); add(new JSkinComponent(), "Skin"); } 

Now the border, in particular, is part of what makes the button look like a button, but I assume you already have a plan for this ...

+2
source

Source: https://habr.com/ru/post/1382287/


All Articles