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

Posted

技术标签:

【中文标题】如何在 Swing 中的 JTable 的列中添加不同的 JComboBox 项【英文标题】:how to add different JComboBox items in a Column of a JTable in Swing 【发布时间】:2011-09-09 19:13:15 【问题描述】:

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

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

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

【问题讨论】:

【参考方案1】:

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 类

【讨论】:

【参考方案2】:
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;
          


      

   






【讨论】:

这篇文章将帮助您在 JTable 中添加一个选择复选框,并在选择它时启用该行的特定列,并且每行的组合框也具有不同的项目值 请在答案中解释一下您的代码,因为它有点长,社区更容易理解它 此代码可帮助您在每一行中添加不同的 ComboBox 项目,因为我正在传递 Hashmap,如果第一个 col 作为 hashmap 中的键,我将根据第一个值分配项目。 MyTableModel 是具有单元格可编辑功能的 TableModel

以上是关于如何在 Swing 中的 JTable 的列中添加不同的 JComboBox 项的主要内容,如果未能解决你的问题,请参考以下文章

如何从.csv文件向JTable中的列添加标头

Jtable-专栏

自定义 TableModel Swing 中的 removeRow() 方法

java的swing编程,Jtable的单元格如何赋值

JTable 更改列字体

为啥 JTable 列中没有显示动画 .gif 图标?