如何在Swing中的JTable列中添加不同的JComboBox项

时间:2011-06-07 05:39:56

标签: java swing jtable jcombobox tablecellrenderer

我想在第1列的JTable(3,3)中添加JComboBox。但在第1列中,每行都有自己的ComboBox元素集。 当我尝试使用

table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(comboBox_Custom));

每一行都被设置为同一组ComboBox值。 但我希望每一行ComboBox都有不同的项目。

2 个答案:

答案 0 :(得分:6)

示例在java2s.com看起来像是正常工作,然后例如(我为JComboBoxes编写了快速示例,并为今天的Swing添加/更改)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.*;

public class EachRowEditorExample extends JFrame {

    private static final long serialVersionUID = 1L;

    public EachRowEditorExample() {
        super("EachRow Editor Example");
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                System.out.println(info.getName());
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        DefaultTableModel dm = new DefaultTableModel();
        dm.setDataVector(new Object[][]{{"Name", "MyName"}, {"Gender", "Male"}, {"Color", "Fruit"}}, new Object[]{"Column1", "Column2"});
        JTable table = new JTable(dm);
        table.setRowHeight(20);
        JComboBox comboBox = new JComboBox();
        comboBox.addItem("Male");
        comboBox.addItem("Female");
        comboBox.addComponentListener(new ComponentAdapter() {

            @Override
            public void componentShown(ComponentEvent e) {
                final JComponent c = (JComponent) e.getSource();
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        c.requestFocus();
                        System.out.println(c);
                        if (c instanceof JComboBox) {
                            System.out.println("a");
                        }
                    }
                });
            }
        });


        JComboBox comboBox1 = new JComboBox();
        comboBox1.addItem("Name");
        comboBox1.addItem("MyName");
        comboBox1.addComponentListener(new ComponentAdapter() {

            @Override
            public void componentShown(ComponentEvent e) {
                final JComponent c = (JComponent) e.getSource();
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        c.requestFocus();
                        System.out.println(c);
                        if (c instanceof JComboBox) {
                            System.out.println("a");
                        }
                    }
                });
            }
        });

        JComboBox comboBox2 = new JComboBox();
        comboBox2.addItem("Banana");
        comboBox2.addItem("Apple");
        comboBox2.addComponentListener(new ComponentAdapter() {

            @Override
            public void componentShown(ComponentEvent e) {
                final JComponent c = (JComponent) e.getSource();
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        c.requestFocus();
                        System.out.println(c);
                        if (c instanceof JComboBox) {
                            System.out.println("a");
                        }
                    }
                });
            }
        });
        EachRowEditor rowEditor = new EachRowEditor(table);
        rowEditor.setEditorAt(0, new DefaultCellEditor(comboBox1));
        rowEditor.setEditorAt(1, new DefaultCellEditor(comboBox));
        rowEditor.setEditorAt(2, new DefaultCellEditor(comboBox2));
        table.getColumn("Column2").setCellEditor(rowEditor);
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll, BorderLayout.CENTER);
        setPreferredSize(new Dimension(400, 120));
        setLocation(150, 100);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        EachRowEditorExample frame = new EachRowEditorExample();
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

只需添加EachRowEditor类

答案 1 :(得分:0)

package com.atos.table.classes;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

public class PartCustomerWindow2 {
    public static final Object[][] DATA = { { 1, 2,3, 4,false }, { 5, 6,7, 8 ,true},{ 9, 10,11, 12,true }, { 13, 14,15, 16,true } };

    public static final String[] COL_NAMES = { "One", "Two", "Three", "Four",MyTableModel1.SELECT };

    JButton but = new JButton("Add");
    private JComboBox jcomboBox = null;
    private JTextField jTextField = null;

    static Object[][] rowData = null;
    private JTable table=null;
    static   JFrame frame = null;
    HashMap mp = null;
    static int count = 0;
    String content = null;


    public JTextField getjTextField() {
        if(jTextField == null)
        {
            jTextField =  new FMORestrictedTextField(FMORestrictedTextField.JUST_ALPHANUMERIC, 8);
        }

    mp = new HashMap();
        mp.put("arif",2);
        mp.put("8",6);
        mp.put("12",10);
        mp.put("14",16);
        mp.put("pk1",22);
        mp.put("pk3",23);

             jTextField.addKeyListener(new KeyAdapter() {

             public void keyReleased(KeyEvent event) {


                 if(count == 0)
                 content = jTextField.getText();
                // System.out.println(content);

                 if(mp.containsKey(content))
                 {
                     JFrame parent = new JFrame();

                     JOptionPane.showMessageDialog(parent, "Already Assigned"); 
                 }
                 }

         });
        return jTextField;
    }


    public void setjTextField(JTextField jTextField) {
        this.jTextField = jTextField;
    }


   public JComboBox getJcomboBox() {
       if(jcomboBox == null)
       {
           jcomboBox = new JComboBox();
       }
        return jcomboBox;
    }


    public void setJcomboBox(JComboBox jcomboBox) {
        this.jcomboBox = jcomboBox;
    }


private void createAndShowGui(PartCustomerWindow2 ob)
   {
     /*rowData  = new Object[DATA.length][];
      for (int i = 0; i < rowData.length; i++) {
         rowData[i] = new Object[DATA[i].length + 1];
         for (int j = 0; j < DATA[i].length; j++) {
            rowData[i][j] = DATA[i][j];
         }
         rowData[i][DATA[i].length] = Boolean.TRUE;
         if(i == 2 || i ==3)
             rowData[i][DATA[i].length] = Boolean.FALSE;
      }*/

      MyTableModel3 tableModel = new MyTableModel3(DATA, COL_NAMES, "My Table", ob);


      table = new JTable(tableModel);

      //table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

      /*table.addFocusListener(new java.awt.event.FocusAdapter() {
          public void focusLost(java.awt.event.FocusEvent evt) {
            table.getSelectionModel().clearSelection();
          }
        });*/

      TableColumnModel cm = table.getColumnModel();


      /*cm.getColumn(2).setCellEditor(new DefaultCellEditor(

                new JComboBox(new DefaultComboBoxModel(new String[] {
                 "Yes",
                  "No",
                  "Maybe"
                }))));*/
     /* String ar1[]= {"aa","aaa","aaaa"};
      ob.getJcomboBox().setModel(new DefaultComboBoxModel(ar1));*/
      cm.getColumn(2).setCellEditor(new DefaultCellEditor(

              ob.getJcomboBox()));


      cm.getColumn(3).setCellEditor(new DefaultCellEditor(

              ob.getjTextField()));


      JScrollPane scrollPane = new JScrollPane();
     /* scrollPane.add("Table",table);
      scrollPane.add("Button",but);*/

      JFrame frame2 =  new JFrame();
     /* jcomboBox.setPreferredSize(new Dimension(100,20));
      textField.setPreferredSize(new Dimension(100,20));
      jcomboBox.setEnabled(false);
      textField.setEnabled(false);
      */
      JScrollPane scrollPane2 = new JScrollPane(but);

      but.addActionListener(new ActionListener() {


        @Override
        public void actionPerformed(ActionEvent e) {
            if(table.getCellEditor() != null)
            table.getCellEditor().stopCellEditing();
            // TODO Auto-generated method stub
            String[][] ar = new String[table.getRowCount()][5];


            for(int i =0;i<table.getRowCount();i++)
            {
                for(int j=0;j<5;j++)
                {
                    DATA[i][j] = table.getValueAt(i,j);
                }

                System.out.print(table.getValueAt(i,0)+" ");
                System.out.print(table.getValueAt(i,1)+" ");
                System.out.print(table.getValueAt(i,2)+" ");
                System.out.print(table.getValueAt(i,3)+" ");
                System.out.println(table.getValueAt(i,4)+" ");
            }

        System.out.println("*******************");
        /*
            for(int i=0;i<DATA.length;i++)
            {
                System.out.print(DATA[i][0]);
                System.out.print(DATA[i][1]);
                System.out.print(DATA[i][2]);
                System.out.print(DATA[i][3]);
                boolean check =(Boolean) DATA[i][4];
                System.out.println(check);
            }*/

    }});


      frame = new JFrame("PartCustomerWindow2");
      //
      //JFrame frame = new JFrame();
      Container contentPane = frame.getContentPane();
      contentPane.setLayout(new BorderLayout());
      contentPane.add(new JScrollPane(table), BorderLayout.NORTH);
      contentPane.add(but);


      //
      //frame.setLayout(new FlowLayout());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     /* frame.getContentPane().add(scrollPane2);
      frame.getContentPane().add(scrollPane3);
      frame.getContentPane().add(scrollPane4);*/
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);


   }





public static void main(String[] args) {
       PartCustomerWindow2 ob = new PartCustomerWindow2();

       ob.createAndShowGui(ob);

   }
}



































@SuppressWarnings("serial")
class MyTableModel3 extends DefaultTableModel {
   public static final String SELECT = "select";
   String tablename;
   PartCustomerWindow2 ob = null;



   public MyTableModel3(Object[][] rowData, Object[] columnNames, String tableName,PartCustomerWindow2 ob) {
      super(rowData, columnNames);
      this.tablename = tableName;
      this.ob = ob;

   }

   @Override
   public Class<?> getColumnClass(int columnIndex) {
      if (getColumnName(columnIndex).equalsIgnoreCase(SELECT)) {

         return Boolean.class;
      }
      else

      return super.getColumnClass(columnIndex);
   }

   @Override
   public boolean isCellEditable(int row, int col) {
       JComboBox jb = ob.getJcomboBox();
       JTextField jt = ob.getjTextField();

       if(((Boolean) getValueAt(row, getColumnCount() - 1)).booleanValue())
       {

         //  jb.setEnabled(false);

          jb.removeAllItems();
          // System.out.println(jb.getItemCount());
          if(row == 0)
          {
             jb.addItem("arif");
              jb.addItem("asif");
               jb.addItem("ashik");
               jb.addItem("farooq");
               jb.addItem("adkh");

          }

          if(row > 0)
          {
             jb.addItem("kjhds");
               jb.addItem("sdds");
               jb.addItem("asdfsdk");
               jb.addItem("sdfsdf");
               jb.addItem("sdf");
          }

        /*HashMap mp = new HashMap();
        mp.put("arif",2);
        mp.put("8",6);
        mp.put("12",10);
        mp.put("14",16);
        mp.put("pk1",22);
        mp.put("pk3",23);
          */
        /* if(col == 3){

        if(mp.containsKey(jt.getText()))
          {
            System.out.println("Sorry..!! already assigned");
            jt.setFocusable(true);
          }

           jt.setText("");
           jt.setEnabled(false);
       }*/
       }
       else
       {
          // jb.setEnabled(true);
           //jt.setEnabled(true);
       }

       if (col == getColumnCount()-1 ) {

         return true;
       }
      else{
          if (getColumnName(4).equalsIgnoreCase(SELECT) && ((Boolean) getValueAt(row, getColumnCount() - 1)).booleanValue())
          {  
            //  jb.setEnabled(true);


             // jt.setEnabled(true);
              return (col == 2 || col == 3);

          }
          else{
             // jb.setEnabled(false);
              //jt.setEnabled(false);
              return false;
          }


      }

   }





}