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.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

public class Main {

    public Main() {
        JComboBox comboBox = new JComboBox();
        comboBox.addItem(new Double(1));
        comboBox.addItem(new Double(2.25));
        comboBox.addItem(new Double(3.5));
        comboBox.setRenderer(new TwoDecimalRenderer(comboBox.getRenderer()));
        comboBox.setEditable(true);

        JFrame frame = new JFrame();
        frame.add(comboBox, BorderLayout.NORTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        new Main();
    }
}

class TwoDecimalRenderer extends DefaultListCellRenderer {

    private ListCellRenderer defaultRenderer;

    public TwoDecimalRenderer(ListCellRenderer defaultRenderer) {
        this.defaultRenderer = defaultRenderer;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
            boolean cellHasFocus) {
        Component c = defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (c instanceof JLabel) {
            if (isSelected) {
                c.setBackground(Color.blue);
            } else {
                c.setBackground(Color.red);
            }
        } else {
            c.setBackground(Color.red);
            c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
        return c;
    }
}