How to Design a Gradient ComboBox In Java Netbeans
In this Java Tutorial we will see How To Create a custom JComboBox with a gradient background and customized item rendering 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.Component;
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.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
/**
*
* @author 1BestCsharp
*/
public class GradientComboBox extends JComboBox<String>{
public GradientComboBox(String[] items){
super(items);
setPreferredSize(new Dimension(150, 50));
setRenderer(new GradientComboBoxRenderer());
//setOpaque(false);
}
// Define a custom cell renderer for the JComboBox items
private static class GradientComboBoxRenderer extends DefaultListCellRenderer{
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean hasFocus){
// Get the default rendering component
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, hasFocus);
// Change the label foreground on selection
label.setOpaque(false);
if(isSelected){ label.setForeground(Color.YELLOW); }
else{ label.setForeground(list.getForeground()); }
// Return the component
return label;
}
// Override method to paint the background gradient of the JComboBox
@Override
public void paint(Graphics g){
// Create a Graphics2D object
Graphics2D g2d = (Graphics2D) g.create();
// Get width and height of the rendering component
int width = getWidth();
int height = getHeight();
// Create a gradient paint for the background
GradientPaint gradientPaint = new GradientPaint(
new Point2D.Float(0, 0), Color.YELLOW,
new Point2D.Float(0, getHeight()), Color.RED
);
// Set the paint and fill the background
g2d.setPaint(gradientPaint);
g2d.fillRect(0, 0, width, height);
// Dispose of the Graphics2D object
g2d.dispose();
// Call the superclass paint method
super.paint(g);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Gradient ComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] items = {"Option 1","Option 2","Option 3","Option 4","Option 5"};
GradientComboBox gradientCombobox = new GradientComboBox(items);
frame.setLayout(new FlowLayout());
frame.add(gradientCombobox);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The Final Result:
More Java Projects:
Download Projects Source Code