How to Create Buttons with Gradient Backgrounds In Java Netbeans
In this Java Tutorial we will see How To Create custom jbutton with a gradient background that transitions from one color to another in Java using NetBeans.
What We Are Gonna Use In This Project:
- Java Programming Language.- NetBeans Editor.
Project Source Code:
package new_tutorials;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* @author 1BestCsharp
*/
public class GradientButton extends JButton{
private Color startColor;
private Color endColor;
public GradientButton(String text, Color startColor, Color endColor){
super(text);
this.startColor = startColor;
this.endColor = endColor;
setContentAreaFilled(false);
setFocusPainted(false);
setForeground(Color.WHITE);
setPreferredSize(new Dimension(150, 70));
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
@Override
protected void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g.create();
// Create a gradient paint
GradientPaint gradientPaint = new GradientPaint(
new Point2D.Float(0,0), startColor,
new Point2D.Float(0,getHeight()), endColor
);
g2d.setPaint(gradientPaint);
// Fill the button background with the gradient
g2d.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
g2d.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Gradient Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
GradientButton button = new GradientButton("Button", Color.GREEN, Color.BLUE);
frame.add(button);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The Final Result:
More Java Projects:
Download Projects Source Code