Creating a Custom Button in Java With Jbutton

Creating a custom button in Java with JButton

You will have to extend JButton class not AbstractButton. Try the following things and you will get idea.

The first move is to subclass JButton.

Then, in your subclass, start by redefining the paintComponent(Graphics) method. If you want any changes.

Then, override paintBorder(Graphics) to give it a shape of hexagon.

Creating a custom JButton in Java

When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.

Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.

alt text

alt text

alt text

Here are the basic steps:

  1. Create a class that extends JComponent
  2. Call parent constructor super() in your constructors
  3. Make sure you class implements MouseListener
  4. Put this in the constructor:

    enableInputMethods(true);   
    addMouseListener(this);
  5. Override these methods:

    public Dimension getPreferredSize()  
    public Dimension getMinimumSize()
    public Dimension getMaximumSize()
  6. Override this method:

    public void paintComponent(Graphics g)

The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

And finally, the source code. In case I missed anything.

How to create a custom JButton class in Java?

create a class and extend it to JButton like below and there you can change all sort of things that has to do with JButton.

import javax.swing.JButton;

public class CustomJButton extends JButton {

public CustomJButton() {
this.setText("Custom JButton");
// initialize
}

// add your own methods or override JButton methods
public void myFunc(){

}
}

How to create a button without importing JButton in JAVA

libraries are meant to save your additional efforts and time. But it is good you are thinking in this way. One thing you can do is to download a decompiler and use it to open the jar file containing the JButton class file and read its code and get an idea.

Also you can refer to this link for custom button creation. :-)

Link: Creating a custom button in Java

Is there a standard way for creating custom buttons?

You may want to write a custom Button UI, you can extend javax.swing.plaf.ComponentUI.

You can apply a custom UI to only one button, or a few buttons, or you create your custom Look and Feel, so all Button use your UI.

The advanced of creating a custom UI class instead of using images is

  • Scalable
  • You are able to translate texts
  • Less memory usage, you don't have to load a big image per button

For UI Examples see e.g. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/plaf/metal/MetalButtonUI.java

If you only need one or two buttons, using an image is may the best solution for you.

Need help to create a custom button in swing

You can use this option, that paints a transparent color gradient on a component:

@Override
public void paintComponent(Graphics g){
super.paintComponent( g );

Graphics2D g2=(Graphics2D)g.create();
int h = getHeight();
int w = getWidth();

g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .5f));
g2.setPaint(new GradientPaint(0, 0, Color.yellow, 0, h, Color.red));
g2.fillRect(0, 0, w, h);

g2.dispose();
}

Sample Image

Other pretty good example with fading in (as requested). I used RadialGradientPaint. You can play with AlphaComposite

g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .4f));

where 4f represent transparent level 40%

@Override
public void paintComponent(Graphics g){
super.paintComponent( g );

Graphics2D g2=(Graphics2D)g.create();
int h = getHeight();
int w = getWidth();

g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));


Point2D center = new Point2D.Float(100, 50);
float radius = 150;
float[] dist = {0.0f, 1.0f};

Color[] colors = {Color.yellow, Color.red};
RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, colors);
g2.setPaint(p);

g2.fillRect(0, 0, w, h);

g2.dispose();

}

Sample Image

Finally we can play with alpha dynamically. Her is the full code. I created simple thread that change me alpha from 0 to 9 and vise versa. Here we go:

public class Fader extends JFrame{
private static final long serialVersionUID = 1L;
static JButton button;

public static float mTransparent = .0f;

Fader(){
super("A fading button");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setSize(400,400);

JButton button = new CustomButton("Submit");

add(button);
setVisible(true);

Blink blink = new Blink(this);
blink.start();
}

public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){public void run(){new Fader();}});
}

public static float getTransparentLevel() {
return mTransparent;
}

public void setTransparentLevel(float newVal) {
mTransparent = newVal;

if(button != null){
button.repaint();

}
repaint();


}
}


class Blink extends Thread{

Fader fader;

public Blink(Fader fader) {
this.fader = fader;
}

@Override
public void run(){

while(true){

if(Fader.getTransparentLevel() == 0.0f){
//increase to 1f
for(int i=1; i<10; i++){
fader.setTransparentLevel((float)i/10);

try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
else if(Fader.getTransparentLevel() == 0.9f){
//increase to 1f
for(int i=10; i>=0; i--){
fader.setTransparentLevel((float)i/10);

try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}


class CustomButton extends JButton {

private static final long serialVersionUID = 1L;
public CustomButton(String s) {
super(s);
}

@Override
public void paintComponent(Graphics g){
super.paintComponent( g );

Graphics2D g2=(Graphics2D)g.create();
int h = getHeight();
int w = getWidth();

g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, Fader.getTransparentLevel()));


Point2D center = new Point2D.Float(100, 50);
float radius = 150;
float[] dist = {0.0f, 1.0f};

Color[] colors = {Color.yellow, Color.red};
RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, colors);
g2.setPaint(p);
g2.fillRect(0, 0, w, h);
g2.dispose();

}

public Dimension getPreferredSize(){
return new Dimension(200,100);
}
}

It blinks with sleep 300 ms from .0 to .9 of transparent and back from .9 to .0:

Sample Image -->
Sample Image

Creating JButton with customized look

I googled the Facebook blue RGB: 59, 89, 182/Hex Code is #3B5998 and Font family: Tahoma.

using that here is what I got with a few calls like setFocusPainted(false),setBackground(new Color(59, 89, 182)) and setFont(new Font("Tahoma", Font.BOLD, 12)):

Sample Image

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Test {

public Test() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JButton b = new JButton("Log In");//http://www.chacha.com/question/what-are-the-rgb-values-for-the-background-color-of-comments-on-facebook
b.setBackground(new Color(59, 89, 182));
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setFont(new Font("Tahoma", Font.BOLD, 12));//http://answers.yahoo.com/question/index?qid=20070906133202AAOvnIP
frame.add(b);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
}

unless you are looking for identical (which IMO this is about as best as it gets without using actual image)... than setting the image of the button would be the best way



Related Topics



Leave a reply



Submit