Yes it is possible. One of the main benefits of using Swing is the ease with which abstract controls can be created and manipulated.
Here's a quick and dirty way to extend an existing JButton class to draw a circle to the right of the text.
package test; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; public class MyButton extends JButton { private static final long serialVersionUID = 1L; private Color circleColor = Color.BLACK; public MyButton(String label) { super(label); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Dimension originalSize = super.getPreferredSize(); int gap = (int) (originalSize.height * 0.2); int x = originalSize.width + gap; int y = gap; int diameter = originalSize.height - (gap * 2); g.setColor(circleColor); g.fillOval(x, y, diameter, diameter); } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.width += size.height; return size; } public static void main(String[] args) { MyButton button = new MyButton("Hello, World!"); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); Container contentPane = frame.getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(button); frame.setVisible(true); } }
Note that by overriding paintComponent that the contents of the button can be changed, but so that the border is painted using the paintBorder method. The getPreferredSize method also needs to be managed to dynamically support content changes. Care must be taken when measuring metrics and image sizes.
To create a control you can rely on, the above code is not correct. Dimensions and colors are dynamic in Swing and depend on the look and feel. Even the standard look of Metal has changed in JRE versions. It would be better to implement AbstractButton and comply with the recommendations of the Swing API. A good starting point is to look at the javax.swing.LookAndFeel and javax.swing.UIManager classes.
http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html
http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html
Understanding Anatomy LookAndFeel is useful for writing controls: Creating a custom look and feel
McDowell Aug 05 '08 at 12:53 2008-08-05 12:53
source share