Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;

public class Main extends JPanel {
    List<TableCellEditor> editors = new ArrayList<TableCellEditor>(3);

    public Main() {
        setLayout(new BorderLayout());

        String[] items1 = { "Red", "Blue", "Green" };
        JComboBox<String> comboBox1 = new JComboBox<String>(items1);
        DefaultCellEditor dce1 = new DefaultCellEditor(comboBox1);
        editors.add(dce1);

        String[] items2 = { "Circle", "Square", "Triangle" };
        JComboBox<String> comboBox2 = new JComboBox<String>(items2);
        DefaultCellEditor dce2 = new DefaultCellEditor(comboBox2);
        editors.add(dce2);

        String[] items3 = { "Apple", "Orange", "Banana" };
        JComboBox<String> comboBox3 = new JComboBox<String>(items3);
        DefaultCellEditor dce3 = new DefaultCellEditor(comboBox3);
        editors.add(dce3);

        Object[][] data = { { "Color", "Red" }, { "Shape", "Square" }, { "Fruit", "Banana" }, { "Plain", "Text" } };
        String[] columnNames = { "Type", "Value" };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model) {
            public TableCellEditor getCellEditor(int row, int column) {
                int modelColumn = convertColumnIndexToModel(column);

                if (modelColumn == 1 && row < 3)
                    return editors.get(row);
                else
                    return super.getCellEditor(row, column);
            }
        };

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

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