简体   繁体   中英

Java JTable combobox validation

There are 3 things i am trying to do here:

  1. First i am trying to make the combo box to show "not feed" when u lanuch the program, at the moment when it launches it just shows nothing, only when i click on the combo box it shows the option "feed" and "not feed".

  2. Secondly i am trying to do a validation for the combobox, where when i click the JButton next, it will validate if the combobox are all "feed" if so you go next, else it will have a pop up saying "check again"

  3. Lastly, i would like to make the cells on the first 4 col uneditable and the last column editable.

     public class DosageTableHelper { private static JTable toDoTable; private static JScrollPane jpane; private static int counter=1; public static DefaultTableModel getElderlyFromQueryDos(String timing,String position) throws SQLException { SQLObject so = new SQLObject(); ResultSet rs = null; if(timing.equalsIgnoreCase("Morning")){ PreparedStatement stmt = so.getPreparedStatementWithKey("SELECT morningdosage FROM et_elderly WHERE name = ?"); stmt.setString(1,position); stmt.executeQuery(); System.out.println(stmt); rs = stmt.getResultSet(); } else if(timing.equalsIgnoreCase("Afternoon")){ PreparedStatement stmt = so.getPreparedStatementWithKey("SELECT afternoondosage FROM et_elderly WHERE name = ?"); stmt.setString(1,position); stmt.executeQuery(); System.out.println(stmt); rs = stmt.getResultSet(); } else if(timing.equalsIgnoreCase("Noon")){ PreparedStatement stmt = so.getPreparedStatementWithKey("SELECT noondosage FROM et_elderly WHERE name = ?"); stmt.setString(1,position); stmt.executeQuery(); System.out.println(stmt); rs = stmt.getResultSet(); } return (DefaultTableModel) buildTableModel(rs); } @SuppressWarnings("unchecked") public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { ArrayList<DosageObject> DosageList=null; System.out.println(rs); try { while(rs.next()){ ByteArrayInputStream in = new ByteArrayInputStream(rs.getBytes(1)); ObjectInputStream is = new ObjectInputStream(in); Object retrieveDosBlob =(Object) is.readObject(); if(retrieveDosBlob instanceof ArrayList<?>){ DosageList=((ArrayList<DosageObject>) retrieveDosBlob); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // storing array list in an array list for future uses Vector<String> columnNames = new Vector<String>(); columnNames.add("Description"); columnNames.add("Prescription"); columnNames.add("Medication Type"); columnNames.add("Dosage"); columnNames.add("Checked"); Vector<Vector<Object>> data = new Vector<Vector<Object>>(); for(int k=0;k<DosageList.size();k++){ Vector<Object> vector = new Vector<Object>(); vector.add(DosageList.get(k).getMedDescrip()); vector.add(DosageList.get(k).getMedPrescrip()); vector.add(DosageList.get(k).getMedType()); vector.add(DosageList.get(k).getMedDosage()); data.add(vector); } DefaultTableModel dtm = new DefaultTableModel(data, columnNames) { private static final long serialVersionUID = 4234183862785566645L; @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return !( rowIndex == 1 && columnIndex == 1 ); } }; return dtm; } // Debug-able main method public static void main(String[] args) throws SQLException { ArrayList<String> nameList= new ArrayList<String>(); nameList.add("Lee Ching Chong"); nameList.add("Lim Kuay Siak"); nameList.add("Lee Ching Chong"); toDoTable =new JTable(getElderlyFromQueryDos("morning",nameList.get(0))); String[] values = new String[] { "Not Feed", "Feed" }; TableColumn col = toDoTable.getColumnModel().getColumn(4); col.setCellEditor(new MyComboBoxEditor(values)); col.setCellRenderer(new MyComboBoxRenderer(values)); jpane = new JScrollPane(toDoTable); JPanel panel = new JPanel(); JFrame frame = new JFrame(); frame.setBounds(0, 0, 700, 543); panel.add(jpane); frame.getContentPane().add(new JScrollPane(panel)); JButton btnNext = new JButton("Next"); panel.add(btnNext); frame.setVisible(true); btnNext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { toDoTable.setModel(DosageTableHelper.getElderlyFromQueryDos("morning",nameList.get(counter))); String[] values = new String[] { "Not Feed", "Feed" }; TableColumn col = toDoTable.getColumnModel().getColumn(4); col.setCellEditor(new MyComboBoxEditor(values)); col.setCellRenderer(new MyComboBoxRenderer(values)); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } counter++; } }); } } @SuppressWarnings("rawtypes") class MyComboBoxRenderer extends JComboBox implements TableCellRenderer { private static final long serialVersionUID = 1319299961084034009L; @SuppressWarnings("unchecked") public MyComboBoxRenderer(String[] items) { super(items); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setSelectedItem(value); return this; } } class MyComboBoxEditor extends DefaultCellEditor { private static final long serialVersionUID = -1702063500403826596L; @SuppressWarnings({ "rawtypes", "unchecked" }) public MyComboBoxEditor(String[] items) { super(new JComboBox(items)); } } 

Sample Output: 在此处输入图片说明

  1. read Oracle tutorial - How to use tables - part about to use JComboBox as TableCellEditor ,

    • explanation JTable has two separate funcionalities TableCellEditor for editing the value stored in the XxxTableModel and TableCellRenderer for painting the value stored in XxxTableModel ,
    • after editing you (event, notifiers implemented in APIs) just storing selected value from TableCellEditor ( JComboBox ) to the XxxTableModel by using XxxTableModel.setValueAt , to store "feed" or "not feed" , not JComboBox as Object , TableCellRenderer just painting from model to the view

    • by default everything works automatically by using DefaultTableModel , then there is required to override reduced numbers of methods ( getColumnClass , isCellEditeble , in your case setValueAt probably too)

  2. there are two ways (1st. required to override XxxTableModel.setValueAt )

    • JButton will be disabled (programatically) untill all value will be changed from blank to "feed" or "not feed" , required to loop inside the model, note after code line super.setValueAt() is executed, value from editor is stored to the model

    • action from JButton loops inside model (primitive, easiest, but themost efficient for validations, simple and direct code, without bugs inside XxxTableModel.setValueAt )

  3. required to override XxxTableModel.setValueAt and to set, change isCellEditable(row, column) to correct value, it would be need to create separate array for isCellEditable , just for models events, don't to change this array from outside, just method XxxTableModel.setValueAt can be notifier


  • use DefaultTableModel if is possible (to avoids any missinterpretations in the code that required for override AbstractTableModel , methods, listeners and especially models notifiers - fireXxxXxx )

  • code ordering inside model is important, firstly to to store value to the model, then to call any changes, validations, additional code, just code based on value stored in model

  • I'm sure that every three points are here a few times, including working code examples in SSCCE / MCVE forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM