0

I have a jTable which is populating according to my requirement . I want to add two comboboxes into all the cells in one column. So can anyone help me on this... ![here is my table ][1]

[1]: https://i.stack.imgur.com/nC9RL.jpg I need to add two comboboxes into all the rows of 1 st column. I did my coding into CREATE TABLE button which u can see in the image. here is my code so far : | |

  int row=0;
  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)     
  {                                         
      row=Integer.parseInt(jTextField2.getText());
      row=row-1;
      DefaultTableModel dtm =(DefaultTableModel) jTable1.getModel();
      TableColumn sportColumn = jTable1.getColumnModel().getColumn(1);
      JComboBox subject= new JComboBox();
      box.addItem("DDD");
      box.addItem("CCC");
      JComboBox teacher= new JComboBox();
      box1.addItem("AAA");
      box1.addItem("FFF");
      JPanel jPanel = new JPanel();
      GroupLayout gl= new GroupLayout(jPanel);
      jPanel.setLayout(gl);
      jPanel.add(box);
      jPanel.add(box1);
      dtm.setRowCount(0);
      dtm.setRowCount(Integer.parseInt(jTextField1.getText()));

      for (int i = 0; i < dtm.getRowCount(); i++) {
          row++;                                                 
          dtm.setValueAt(String.valueOf(row), i, 0);
          sportColumn.setCellRenderer(
               (TableCellRenderer) new DefaultTableCellRenderer()
                             .getTableCellRendererComponent(
                                           jTable1, jPanel, true, true, i, 1));
      }
  }   

jButton1===> create table Button / jTextField2===> number starts with / jTextField1===>number of rows

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 1
    Take a look at [How to use tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html), pay attention to the cell editor and renderer sections... – MadProgrammer Nov 15 '13 at 03:43
  • I did... But I couldn't find a solution... I have put cellRenderer into my code ... but it is not working properly... everything works fine except cellRenderer . –  Nov 15 '13 at 03:50
  • 1
    Read them again, because you're doing it wrong... – MadProgrammer Nov 15 '13 at 03:52
  • You don't have any rendering code at all. All you do is create a DefaultTableCellRenderer. You will want to relook at the tutorial, study it, play with the sample program. – Hovercraft Full Of Eels Nov 15 '13 at 03:52
  • It'd also question the need to use two combo boxes in a single column. A column should represent a single state or property – MadProgrammer Nov 15 '13 at 03:57
  • 1
    Yep. And it is unusual to render a combobox. Rather the selected value is usually rendered and the combo displayed only in the editor when the user wishes to change values. – Hovercraft Full Of Eels Nov 15 '13 at 03:58
  • here.. I want to add two combo boxes to select teacher and subject user wishes to continue with. I added one combo box into required cell by replacing sportColumn.setCellRenderer((TableCellRenderer) new DefaultTableCellRenderer().getTableCellRendererComponent(jTable1, jPanel, true, true, i, 1)); code line to sportColumn.setCellEditor(new DefaultCellEditor(box)); but I need two combo boxes to overcome with my requirement. –  Nov 15 '13 at 04:06
  • 2
    `sportColumn.setCellRenderer((TableCellRenderer) new DefaultTableCellRenderer().getTableCellRendererComponent(jTable1, jPanel, true, true, i, 1));` this doesn't set a cell renderer, in fact I'd be surprised if it compiled. I would start by allowing the user to select the subject in the first column and the teacher in the second... – MadProgrammer Nov 15 '13 at 04:09
  • yes. It would be possible. But very next column name is Monday. I have named the 8 columns "GRADE","Sunday","Monday","Tuesday","Wednesday","Thursday"..etc. Actually I need to put two combo boxes into other columns also. To select teacher & subject. –  Nov 15 '13 at 04:18
  • A better solution might be to use a dialog to gather the details and apply the result back to the table... – MadProgrammer Nov 15 '13 at 04:21
  • Kind of crazy requirements. I'd change those. – Hovercraft Full Of Eels Nov 15 '13 at 04:22
  • Sorry if I m annoying you. but What I wanted to do is to populate the jTable according to users requirement. Which means if user need to add 5 different grades, teacher and subject details, user only has to type the number of grades he is expecting to add in jTextField1 and the grade starting with is typed on jTextField2. If you look at my Image you will figure it out. Thanks. –  Nov 15 '13 at 04:29

1 Answers1

1

Caverts:

I think this is a crazy idea, personally. If your cell represents a compound object, then I'd be thinking about using a dialog or some other means, but that's me.

Personally, I think this is going to blow up in your face...

Example

The concepts presented are all based on the information from How to use Tables

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractCellEditor;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumnModel;

public class Enrolement {

    public static void main(String[] args) {
        new Enrolement();
    }

    public Enrolement() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                DefaultTableModel model = new DefaultTableModel(new Object[]{"Subject"}, 10);

                JTable tbl = new JTable(model);
                TableColumnModel columnModel = tbl.getColumnModel();
                columnModel.getColumn(0).setCellEditor(new SubjectTableCellEditor());

                tbl.setRowHeight(columnModel.getColumn(0).getCellEditor().getTableCellEditorComponent(tbl, "Astronomy/Aurora Sinistra", true, 0, 0).getPreferredSize().height);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(tbl));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class SubjectTableCellEditor extends AbstractCellEditor implements TableCellEditor {

        private JComboBox subject;
        private JComboBox teacher;

        private JPanel editor;

        private Map<String, String[]> subjectTeachers = new HashMap<>(25);

        public SubjectTableCellEditor() {

            subjectTeachers.put("Astronomy", new String[]{"Aurora Sinistra"});
            subjectTeachers.put("Charms", new String[]{"Filius Flitwick"});
            subjectTeachers.put("Dark Arts", new String[]{"Igor Karkaroff", "Amycus Carrow"});
            subjectTeachers.put("Defence Against the Dark Arts", new String[]{"Defence Against the Dark Arts",
                "Quirinus Quirrell",
                "Gilderoy Lockhart",
                "Remus Lupin",
                "Bartemius Crouch Jr.",
                "Dolores Umbridge",
                "Severus Snape",
                "Amycus Carrow"});
            subjectTeachers.put("Flying", new String[]{"Rolanda Hooch"});
            subjectTeachers.put("Herbology", new String[]{"Herbert Beery",
                "Pomona Sprout",
                "Neville Longbottom"});
            subjectTeachers.put("History of Magic", new String[]{"Professor Cuthbert Binns"});
            subjectTeachers.put("Potions", new String[]{"Severus Snape",
                "Horace Slughorn"});
            subjectTeachers.put("Transfiguration", new String[]{"Minerva McGonagall",
                "Albus Dumbledore"});

            subject = new JComboBox(new String[]{
                "Astronomy",
                "Charms",
                "Dark Arts",
                "Defence Against the Dark Arts",
                "Flying",
                "Herbology",
                "History of Magic",
                "Potions",
                "Transfiguration"
            });
            teacher = new JComboBox();

            editor = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            editor.add(subject, gbc);
            editor.add(teacher, gbc);

            subject.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    teacher.setModel(new DefaultComboBoxModel(subjectTeachers.get(subject.getSelectedItem())));
                }
            });

        }

        @Override
        public Object getCellEditorValue() {
            return subject.getSelectedItem() + "/" + teacher.getSelectedItem();
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            if (value instanceof String) {
                String parts[] = value.toString().split("/");
                subject.setSelectedItem(parts[0]);
                teacher.setSelectedItem(parts[1]);
            }
            editor.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
            return editor;
        }
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366