Java 如何根据jTable中的jComboBox选择更新相邻字段?

Java 如何根据jTable中的jComboBox选择更新相邻字段?,java,jtable,jcombobox,Java,Jtable,Jcombobox,我有一个场景,jTable中有一个颜色选择的jComboBox使用所选颜色的名称更改jTable同一行中的另一个字段 当选中jComboBox时,相邻字段会相应地更改,但当我单击另一个jComboBox而不是更改相邻字段时,它会更改先前选中的行 这是我目前掌握的代码: import javax.swing.DefaultCellEditor; import javax.swing.table.*; public class TestJTable extends javax.swing.JF

我有一个场景,jTable中有一个颜色选择的jComboBox使用所选颜色的名称更改jTable同一行中的另一个字段

当选中jComboBox时,相邻字段会相应地更改,但当我单击另一个jComboBox而不是更改相邻字段时,它会更改先前选中的行

这是我目前掌握的代码:

import javax.swing.DefaultCellEditor;
import javax.swing.table.*;

public class TestJTable extends javax.swing.JFrame {

    public TestJTable() {
        initComponents();

        String[] columnNames = {"Choose Colour", "Colour Chosen"};
        Object[][] data =
        {
            {"Red",    new String("Red Colour")},
            {"Blue",  new String("Blue Colour")},
            {"Green",    new String("Green Colour")},
            {"Yellow", new String("Yellow  Colour")}
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames);

        jTable.setModel(model);

        jTable.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(jCBColour));



    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jCBColour = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable = new javax.swing.JTable();

        jCBColour.setEditable(true);
        jCBColour.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Red", "Blue", "Green", "Yellow" }));
        jCBColour.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBColourActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Choose Colour", "Colour Chosen"
            }
        ));
        jScrollPane1.setViewportView(jTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(89, 89, 89)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(113, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(178, 178, 178))
        );

        pack();
    }// </editor-fold>                        

    private void jCBColourActionPerformed(java.awt.event.ActionEvent evt) {                                          

        System.out.println(evt.getActionCommand());
        System.out.println(jCBColour.getSelectedIndex());

        if (jCBColour.getSelectedIndex() != -1) {

        switch (jCBColour.getSelectedIndex()){
           case 0: jTable.setValueAt("Red Colour", jTable.getSelectedRow(), 1);
                    break;
           case 1: jTable.setValueAt("Blue Colour", jTable.getSelectedRow(), 1);
                    break;
           case 2: jTable.setValueAt("Green Colour", jTable.getSelectedRow(), 1);
                    break;
           case 3: jTable.setValueAt("Yellow Colour", jTable.getSelectedRow(), 1);
                    break;
           default:
                   break;
       }
       }

    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestJTable().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox jCBColour;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable;
    // End of variables declaration                   
}
import javax.swing.DefaultCellEditor;
导入javax.swing.table.*;
公共类TestJTable扩展了javax.swing.JFrame{
公共TestJTable(){
初始化组件();
String[]columnNames={“选择颜色”,“选择颜色”};
对象[][]数据=
{
{“红色”,新字符串(“红色”)},
{“蓝色”,新字符串(“蓝色”)},
{“绿色”,新字符串(“绿色”)},
{“黄色”,新字符串(“黄色”)}
};
DefaultTableModel=新的DefaultTableModel(数据、列名称);
jTable.setModel(model);
jTable.getColumnModel().getColumn(0).setCellEditor(新的DefaultCellEditor(jCBColour));
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
jCBColour=newjavax.swing.JComboBox();
jScrollPane1=newjavax.swing.JScrollPane();
jTable=newjavax.swing.jTable();
jCBColour.setEditable(true);
jCBColour.setModel(新的javax.swing.DefaultComboxModel(新字符串[]{“红色”、“蓝色”、“绿色”、“黄色”}));
jCBColour.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jcbcoloruactionperformed(evt);
}
});
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setModel(新的javax.swing.table.DefaultTableModel(
新对象[][]{
{null,null},
{null,null},
{null,null},
{null,null}
},
新字符串[]{
“选择颜色”,“选择颜色”
}
));
jScrollPane1.setViewportView(jTable);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(89,89,89)
.addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED\u SIZE,452,javax.swing.GroupLayout.PREFERRED\u SIZE)
.addContainerGap(113,简称最大值))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addContainerGap(14,简称最大值)
.addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED_SIZE,115,javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(178178178)
);
包装();
}//                         
private void jCBColourActionPerformed(java.awt.event.ActionEvent evt){
System.out.println(evt.getActionCommand());
System.out.println(jCBColour.getSelectedIndex());
如果(jcbcolor.getSelectedIndex()!=-1){
开关(jcbcolor.getSelectedIndex()){
案例0:jTable.setValueAt(“红色”,jTable.getSelectedRow(),1);
打破
案例1:jTable.setValueAt(“蓝色”,jTable.getSelectedRow(),1);
打破
案例2:jTable.setValueAt(“绿色”,jTable.getSelectedRow(),1);
打破
案例3:jTable.setValueAt(“黄色”,jTable.getSelectedRow(),1);
打破
违约:
打破
}
}
}                                         
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*创建并显示表单*/
invokeLater(new Runnable()){
公开募捐{
新的TestJTable().setVisible(true);
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
    @Override
    public void setValueAt(Object value, int row, int column)
    {
        super.setValueAt(value, row, column);

        if (column == 0)
        {
            String color = value.toString();

            switch (column)
            {
                case "Red": setValueAt("Red Color", row, 1); break;
                case "Blue": setValueAt("Blue Color", row, 1); break;
                ...
            }

        }
    }
};
import java.util.ArrayList;
import javax.swing.DefaultCellEditor;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;

public class TestJTable extends javax.swing.JFrame {

    private TableModelListener tableModelListener;

    public TestJTable() {
        initComponents();

        String[] columnNames = {"Choose Colour", "Colour Chosen"};
        Object[][] data =
        {
            {"Red",    new String("Red Colour")},
            {"Blue",  new String("Blue Colour")},
            {"Green",    new String("Green Colour")},
            {"Yellow", new String("Yellow  Colour")}
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames);

        jTable.setModel(model);

        jTable.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(jCBColour));

        setTableModelListener();

    }

 private void setTableModelListener() {
    tableModelListener = new TableModelListener() {

        @Override
        public void tableChanged(TableModelEvent e) {
            if (e.getType() == TableModelEvent.UPDATE) {

                int row = e.getFirstRow();
                int column = e.getColumn();
                if (column == 0) {
                    TableModel model = jTable.getModel();
                    //ArrayList<String> itemRow = itemCodes.get(jTable.getSelectedIndex());
                    //String itemDescription = itemRow.get(1);
                    String colourChosen = "";
                    switch (jCBColour.getSelectedIndex()) {
                        case 0: colourChosen = "Red Colour";break;
                        case 1: colourChosen = "Blue Colour";break;
                        case 2: colourChosen = "Green Colour";break;
                        case 3: colourChosen = "Yellow Colour";break;
                }

                model.setValueAt(colourChosen,row,1);

                }
            }
        }
    };
    jTable.getModel().addTableModelListener(tableModelListener);
    }    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jCBColour = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable = new javax.swing.JTable();

        jCBColour.setEditable(true);
        jCBColour.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Red", "Blue", "Green", "Yellow" }));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Choose Colour", "Colour Chosen"
            }
        ));
        jScrollPane1.setViewportView(jTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(89, 89, 89)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(113, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(178, 178, 178))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestJTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestJTable().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox jCBColour;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable;
    // End of variables declaration                   
}
    private void jCBColourActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            if (jCBColour.getSelectedIndex() != -1) {
                jTable.setValueAt(jCBColour.getItemAt(jCBColour.getSelectedIndex()), jTable.getSelectedRow(), 1);
                jTable.repaint();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }