将JTable中的JComboBox重置为JComboBox的第

将JTable中的JComboBox重置为JComboBox的第

本文介绍了如何将JTable中的JComboBox重置为JComboBox的第一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java Swing中的代码进行开发.我已经在JTable中创建了一个JComboBox.它正在工作:).但是,一旦我选择一个值并单击保存"或取消"按钮,它就必须重置为默认值(组合框中的第一个值).我尝试了很多类似combobox.setSelectedIndex(0)的方法.这不起作用.代码:

I'm working on a code in Java Swing. I have created a JComboBox in JTable. It's working :). But once I select a value and click on the save or cancel button, it has to reset to the default value (1st value in the combo box). I tried a lot of ways like combobox.setSelectedIndex(0). This isn't working.Code:

String[] manTimeHr = { "00","01", "02", "03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
        String[] manTimeMin = {"00","01", "02", "03","04","05","06","07","08","09","10","11","12","13", "14", "15","16","17","18","19","20","21","22","23","24","25", "26", "27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
        String[][] data = {{"-select-","-select-"}};
        String[] cols = {"Hrs","Mins"};
        String[][] data1 = {{"-select-","-select-"}};
        String[] cols1 = {"Hrs","Mins"};
        JLabel manTimeStart = new JLabel("Start From",JLabel.LEFT);
        STimeTbl = new JTable(data,cols);
        hrsColumn=STimeTbl.getColumnModel().getColumn(0);
        minsColumn=STimeTbl.getColumnModel().getColumn(1);
        manSiteStimeHrCBx = new JComboBox(manTimeHr);
        manSiteStimeHrCBx.setSelectedIndex(0);
        hrsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeHrCBx));
        manSiteStimeMinCBx = new JComboBox(manTimeMin);
        manSiteStimeMinCBx.setSelectedIndex(0);
        minsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeMinCBx));
        JLabel manTimeEnd = new JLabel("End To",JLabel.LEFT);
        ETimeTbl = new JTable(data1,cols1);
        hrsColumn1=ETimeTbl.getColumnModel().getColumn(0);
        minsColumn1=ETimeTbl.getColumnModel().getColumn(1);
        manSiteEtimeHrCBx = new JComboBox(manTimeHr);
        manSiteEtimeHrCBx.setSelectedIndex(0);
        hrsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeHrCBx));
        manSiteEtimeMinCBx = new JComboBox(manTimeMin);
        manSiteEtimeMinCBx.setSelectedIndex(0);
        minsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeMinCBx));
        .
        .
        .
        .
        if("Save".equals(e.getActionCommand())) {
        try{
                    mSHr = Integer.parseInt((String)manSiteStimeHrCBx.getSelectedItem());
                    mEHr=Integer.parseInt((String)manSiteEtimeHrCBx.getSelectedItem());
                    mSMin=Integer.parseInt((String)manSiteStimeMinCBx.getSelectedItem());
                    mEMin=Integer.parseInt((String)manServEtimeMinCBx.getSelectedItem());
                }catch (Exception en){
                System.out.println("Main Exception : "+ en);
                    return;
                }
                if(validateBlockTime(mSHr,mEHr,mSMin,mEMin) != true)
                {
                    System.out.println("Enter valid Time");
                    return;
                }
                manSiteStimeHrCBx.setSelectedIndex(0);
                manSiteStimeMinCBx.setSelectedIndex(0);
                manSiteEtimeHrCBx.setSelectedIndex(0);
                manSiteEtimeMinCBx.setSelectedIndex(0);
        .
        .
        .
        private static boolean validateBlockTime(int val3, int val4, int val5, int val6){
        if(val4 > val3)
            return true;
        else if((val4 == val3) && (val6 > val5))
            return true;
        else
            return false;
        }

推荐答案

  • JTable教程包含有关组合框作为编辑器

    • JTable tutorial contains description about Combo Box as an Editor

      所有数据都存储在 XxxTableModel

      概念:编辑器和渲染器

      然后您必须知道在XxxTableModel中仅存储了

      then you have to know that in the XxxTableModel is stored only String value (or Double or Long or Integer or Icon, depends of value stored in ComboBoxModel) for Combo Box as an Editor

      结果是

      基于教程代码的快速代码(对不起,我很懒)

      quick code (sorry I'm so lazy) based on tutorial code

      import java.awt.BorderLayout;
      import java.awt.event.ActionEvent;
      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.AbstractTableModel;
      import javax.swing.table.DefaultTableCellRenderer;
      import javax.swing.table.TableCellRenderer;
      import javax.swing.table.TableColumn;
      import java.awt.Component;
      import java.awt.Dimension;
      import java.awt.event.ActionListener;
      import javax.swing.JButton;
      
      public class TableRenderDemo extends JPanel {
      
          private static final long serialVersionUID = 1L;
          private boolean DEBUG = false;
      
          public TableRenderDemo() {
              super(new BorderLayout(5, 5));
              final JTable table = new JTable(new MyTableModel());
              table.setRowHeight(18);
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              initColumnSizes(table);
              setUpSportColumn(table, table.getColumnModel().getColumn(2));
              add(scrollPane);
              JButton resetButton = new JButton("Reset to default");
              resetButton.addActionListener(new ActionListener() {
      
                  public void actionPerformed(ActionEvent e) {
                     for (int i = 0; i < table.getRowCount(); i++) {
                          table.getModel().setValueAt("None of the above", i, 2);
                     }
                  }
              });
              add(resetButton, BorderLayout.SOUTH);
          }
      
          private void initColumnSizes(JTable table) {
              MyTableModel model = (MyTableModel) table.getModel();
              TableColumn column = null;
              Component comp = null;
              int headerWidth = 0;
              int cellWidth = 0;
              Object[] longValues = model.longValues;
              TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
              for (int i = 0; i < 5; i++) {
                  column = table.getColumnModel().getColumn(i);
                  comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
                  headerWidth = comp.getPreferredSize().width;
                  comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
                  cellWidth = comp.getPreferredSize().width;
                  if (DEBUG) {
                      System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
                  }
                  column.setPreferredWidth(Math.max(headerWidth, cellWidth));
              }
          }
      
          private void setUpSportColumn(JTable table, TableColumn sportColumn) {
              JComboBox comboBox = new JComboBox();
              comboBox.addItem("Snowboarding");
              comboBox.addItem("Rowing");
              comboBox.addItem("Knitting");
              comboBox.addItem("Speed reading");
              comboBox.addItem("Pool");
              comboBox.addItem("None of the above");
              sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for combo box");
              sportColumn.setCellRenderer(renderer);
          }
      
          private class MyTableModel extends AbstractTableModel {
      
              private static final long serialVersionUID = 1L;
              private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
              private Object[][] data = {
                  {"Kathy", "Smith", "Snowboarding", new Integer(5), false},
                  {"John", "Doe", "Rowing", new Integer(3), true},
                  {"Sue", "Black", "Knitting", new Integer(2), false},
                  {"Jane", "White", "Speed reading", new Integer(20), true},
                  {"Joe", "Brown", "Pool", new Integer(10), false}
              };
              public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
      
              public int getColumnCount() {
                  return columnNames.length;
              }
      
              public int getRowCount() {
                  return data.length;
              }
      
              @Override
              public String getColumnName(int col) {
                  return columnNames[col];
              }
      
              public Object getValueAt(int row, int col) {
                  return data[row][col];
              }
      
              @Override
              public Class<?> getColumnClass(int c) {
                  return getValueAt(0, c).getClass();
              }
      
              @Override
              public boolean isCellEditable(int row, int col) {
                  if (col < 2) {
                      return false;
                  } else {
                      return true;
                  }
              }
      
              @Override
              public void setValueAt(Object value, int row, int col) {
                  data[row][col] = value;
                  fireTableCellUpdated(row, col);
                  System.out.println(getValueAt(row, col));
              }
          }
      
          private static void createAndShowGUI() {
              JFrame frame = new JFrame("TableRenderDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              TableRenderDemo newContentPane = new TableRenderDemo();
              newContentPane.setOpaque(true); //content panes must be opaque
              frame.setContentPane(newContentPane);
              frame.pack();
              frame.setVisible(true);
          }
      
          public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
      
                  public void run() {
                      createAndShowGUI();
                  }
              });
          }
      }
      

      AbstractTableModel的输出,代码行135th.

      run:
      None of the above
      None of the above
      None of the above
      None of the above
      None of the above
      BUILD SUCCESSFUL (total time: 37 seconds)
      

      这篇关于如何将JTable中的JComboBox重置为JComboBox的第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:41