Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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.JPanel;
import javax.swing.JTextField;

public class Main extends JPanel {
    private static final MyData[] data = { new MyData("Monday", 1, false), new MyData("Tuesday", 2, false),
            new MyData("Wednesday", 3, false), new MyData("Thursday", 4, false), new MyData("Friday", 5, false),
            new MyData("Saturday", 6, true), new MyData("Sunday", 7, true), };
    JComboBox<MyData> myCombo = new JComboBox<MyData>(data);
    JTextField textField = new JTextField(10);
    JTextField valueField = new JTextField(10);
    JTextField weekendField = new JTextField(10);

    public Main() {
        add(myCombo);
        add(new JLabel("text:"));
        add(textField);
        add(new JLabel("value:"));
        add(valueField);
        add(new JLabel("weekend:"));
        add(weekendField);

        myCombo.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                String text = value == null ? "" : ((MyData) value).getText();
                return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus);
            }
        });
        myCombo.setSelectedIndex(-1);

        myCombo.addActionListener(e -> {
            MyData myData = (MyData) myCombo.getSelectedItem();
            textField.setText(myData.getText());
            valueField.setText(String.valueOf(myData.getValue()));
            weekendField.setText(String.valueOf(myData.isWeekend()));
        });
    }

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

class MyData {
    String text;
    int value;
    boolean weekend;

    MyData(String text, int value, boolean weekend) {
        this.text = text;
        this.value = value;
        this.weekend = weekend;
    }

    public String getText() {
        return text;
    }

    public int getValue() {
        return value;
    }

    public boolean isWeekend() {
        return weekend;
    }
}