Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class Main extends JFrame {
    public Main() {
        Object[] items = { Color.red, Color.green, Color.blue };
        JComboBox comboBox = new JComboBox(items);
        comboBox.setRenderer(new ColorRenderer(comboBox));
        getContentPane().add(comboBox, BorderLayout.NORTH);
        add(new JTextField(), BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        Main frame = new Main();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class ColorRenderer extends BasicComboBoxRenderer {
    JComboBox comboBox;
    Border border;

    public ColorRenderer(JComboBox comboBox) {
        this.comboBox = comboBox;
        border = new LineBorder(Color.WHITE);
    }

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
            boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        setText(value.toString());
        if (!isSelected)
            setBackground((Color) value);
        return this;
    }
}