How to Check Jtable Values in IF Condition With For Loop - java

My code only works for the 1st row. I want to add a row if it is not in the JTable. Class_assing_tb is my JTable.
I want to add values, which I get from JCombobox, to JTable when I click "Add Item" button. It can only input a maximum of 4 items. I want to do it like this, if I add an item that is already in the JTable I want to give a message "Denied" else add the item to JTable.
int count = Class_assing_tb.getRowCount();
if (count == 0) {
addrow(); //this is to Command For Add new Row
} else if (count == 4) {
System.out.println("maximum Row Count");
// msg ****** Maximum Classes
} else {
int a = Class_assing_tb.getRowCount();
DefaultTableModel tm2 = (DefaultTableModel) Class_assing_tb.getModel();
loop:
for (int i = 0; i < a; i++) {
//System.out.println("Row Count is" + a);
// System.out.println("Sttate is"+i);
if (tm2.getValueAt(i, 0).equals(mng_stu_classatnd.getSelectedItem()) & tm2.getValueAt(i, 2).equals(mng_stu_batch.getSelectedItem()) & tm2.getValueAt(i, 3).equals(mng_stu_type.getSelectedItem())) {
System.out.println("Denied");
break loop;
} else {
addrow();//this is to Command For Add new Row
// continue loop;
}
}
}

Try something like this:
//Global Declaration
private Vector<Vector<String>> data; //used for data from database
private Vector<String> header; //used to store data header
//Display only header on form load
//create header for the table
header = new Vector<String>();
header.add("Column");
model=new DefaultTableModel(data,header);
table = new JTable(model);
//in actionPerformed()
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==add){
int count=table.getRowCount();
for(int i=1;i<=count;i++){
if(table.getValueAt(i,0).equals(jComboBox.getSelectedItem())){
JOptionPane.showMessageDialog((Component) null,"Duplicate...");
return;
}
}
if(count==4){
JOptionPane.showMessageDialog((Component) null,"Maximum Limit is crossed...");
}else{
Object d= jComboBox.getSelectedItem();
model.addRow(d);
}
}
}

Related

Getting old values from Jtable

I am facing a strange problem with the Jtable. I have a small standalone java application in which I have used Jtable that shows data that is retrieved from database. User can view and edit the data. Once he edit the cell and presses the update button then the edited values will be updated in the database. Now what happening is for the first time when user edit the data and click on update button then the values are properly persisted in the database and user gets out of the module. But again if he/she goes to the same module and edits some more cells and click on update button then in back end i get old value from those cells although the Jtable shows the latest updated values in the cells.
Below is the code.
private JTable jt;
private TableRowSorter<TableModel> tableSorter;
private Dao dao=new Dao();
updateDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean isSuccessful = true;
int rowCount = jt.getRowCount();
List<EmployeeMaster> empMasterList = new ArrayList<>();
int j = 0;
for (int i = 0; i < rowCount; i++) {
EmployeeMaster master = new EmployeeMaster();
j = 0;
try {
master.setEmpId(Long.parseLong((String) jt.getValueAt(i, j)));
j++;
compId.setName(Long.parseLong((String) jt.getValueAt(i, j)));
j++;
compId.setNumber((String) jt.getValueAt(i, j));
j++;
empMasterList.add(master);
}
dao.updateAllEmpDetails(empMasterList);
homePanel.setVisible(true);
UpdateEmp.setVisible(false);
}
}
});
getDataFromDBtoJtable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
List<EmployeeMaster> empMasterList = dao.getAllEmpDetails();
String data[][] = new String[empMasterList.size()][3];
int i = 0;
int j = 0;
for (EmployeeMaster employeeMaster : empMasterList) {
j = 0;
data[i][j] = String.valueOf(employeeMaster.getEmpId());
j++;
data[i][j] = String.valueOf(employeeMaster.getName());
j++;
data[i][j] = String.valueOf(employeeMaster.getNumber());
i++;
}
String column[] = { "ID", "Name", "Number"};
jt = new JTable(data, column) {
public boolean isCellEditable(int row, int column) {
if (column == 0 || column == 1 || column == 2)
return false;
else
return true;
};
};
tableSorter = new TableRowSorter<TableModel>(jt.getModel());
jt.setBounds(12, 12, 1200, 400);
jt.setRowSorter(tableSorter);
homePanel.setVisible(false);
UpdateEmp.setVisible(true);
JScrollPane pane = new JScrollPane(jt);
pane.setBounds(1, 40, 1150, 300);
setBounds(0, 0, 2000, 800);
UpdateEmp.add(pane);
}
});
updateDetails -> button to get the data from jtable and update it in database
getDataFromDBtoJtable -> button to get data from Database and show it in Jtable
Whenever user hits the updateDetails i am updating the database and forcing user to get out of the module. So everytime whenever user get into jtable module he/she gets new Jtable instance. But still unable to identify what's going wrong.

JTable select and deselect not working

I have a problem with my JTable. Firstly I selected some entries in my table. However when I deselect some of them, the table could not understand it.
Example scenario: I select job1 and 2 for the testing after that I change my mind and de-select job2. But in the result I saw job1 job1 and job2 ( job 1 seen 2 times and even though I dis-select job 2 I saw them.) Or after selected all the jobs ( choose all button) I want to deselect all of them (Clear button) when I click clear all the table seems empty. It is good but somehow the background of the program still protect the all old selection. How can I solve this?
Try:
I created the row of my table by read csv file.
public class JobSelectionListPanel extends JPanel {
private static final long serialVersionUID = 5198916547962359735L;
private static JobSelectionListPanel INSTANCE = new JobSelectionListPanel();
public static JobSelectionListPanel getInstance() {
return INSTANCE;
}
private JTable table;
private JButton next, back, btnClear, btnNewButton, btnChooseAll;
private JobList fnnJobList = new JobList();
private JobSelectionListPanel() {
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
table.setBorder(new CompoundBorder());
// Read all FNN jobs from file
try {
fnnJobList.readFromFile("rules.csv");
} catch (IOException e1) {
System.out.println("You are not able to read the rules.csv file");
}
// Create ArrayList of JobNames
Object[][] initialData = new Object[fnnJobList.size()][1];
int i = 0;
for (Job jobDes : fnnJobList) {
initialData[i][0] = (Object) jobDes.getJobname();
i++;
}
String[] columnNames = new String[] { "", "Your preferences" };
table.setModel(new DefaultTableModel(initialData, columnNames) {
private static final long serialVersionUID = 1L;
#SuppressWarnings("rawtypes")
Class[] columnTypes = new Class[] { Object.class, Boolean.class };
#SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
table.getColumnModel().getColumn(1).setPreferredWidth(80);
table.getColumnModel().getColumn(1).setMinWidth(40);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setCellSelectionEnabled(true);
I user want to choose all rows then I implemented this.
btnChooseAll = new JButton("Choose all");
btnChooseAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel chooseAllData = (DefaultTableModel) table.getModel();
if (DeviceGroups.DeviceAList.size() == 0 || DeviceGroups.DeviceBList.size() == 0
|| DeviceGroups.DeviceCList.size() == 0 || DeviceGroups.DeviceDList.size() == 0)
JOptionPane.showMessageDialog(null,
"You should choose at least 1 device for each test device to apply this test case", "Invalid OPTION",
JOptionPane.ERROR_MESSAGE);
else
for (int i = 0; i < chooseAllData.getRowCount(); i++) {
for (int j = 1; j < chooseAllData.getColumnCount(); j++) {
chooseAllData.setValueAt(true, i, j);
}
}
}
});
For clear all preferences :
btnClear = new JButton("Clear all");
// Clear button create a model of JTable and delete all the rows of table!!
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel clearTableData = (DefaultTableModel) table.getModel();
for (int i = 0; i < clearTableData.getRowCount(); i++) {
for (int j = 1; j < clearTableData.getColumnCount(); j++) {
clearTableData.setValueAt(null, i, j);
}
}
}
});
I see the following problem in your code: mixing up view indexes and model indexes. This is the offending snippet:
for (int i = 0; i < table.getRowCount(); i++) {
if (table.getValueAt(i, 1) != null) {
if (((Boolean) table.getValueAt(i, 1)).booleanValue()) {
String jobName = (((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString());
You are using the i variable to denote view row indices, since you are checking values in this statement: table.getValueAt(i, 1) != null.
But then a bit further you are using i to index the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString();
If i is to be a view index, you need to convert it to a model index before indexing the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(table.convertRowIndexToModel(i), 0).toString();
Also, when columns would be switched around in the view (ie on screen in your GUI), the following will probably not work as intended:
table.getValueAt(i, 1) != null
You most likely mean to say, get the second column value in the model, not the view. Best rewrite then as
table.getValueAt(i, table.convertColumnIndexToView(1)) != null

Getting value of selected row in AbstractTableModel Java

I am looking to get the value of the selected row in an AbstractTableModel and I am noticing some things. It is correctly reporting what sell (row) I am on, when it is selected, but as soon as I click my button to remove, the selected row value goes to 0. Resulting in the 0 row always being removed. I want to get the value int selectedRow and use it to remove it from the table and my ArrayLists.
ListSelectionModel rsm = table.getSelectionModel();
ListSelectionModel csm = table.getColumnModel().getSelectionModel();
csm.addListSelectionListener(new SelectionDebugger(columnCounter,csm));
columnCounter = new JLabel("(Selected Column Indices Go Here)");
columnCounter.setBounds(133, 62, 214, 14);
csm.addListSelectionListener(new SelectionDebugger(columnCounter,csm));
contentPane1.add(columnCounter);
rowCounter = new JLabel("(Selected Column Indices Go Here)");
rowCounter.setBounds(133, 36, 214, 14);
rsm.addListSelectionListener(new SelectionDebugger(rowCounter, rsm));
contentPane1.add(rowCounter);
SelectionDebugger:
public class SelectionDebugger implements ListSelectionListener {
JLabel debugger;
ListSelectionModel model;
public SelectionDebugger(JLabel target, ListSelectionModel lsm) {
debugger = target;
model = lsm;
}
public void valueChanged(ListSelectionEvent lse) {
if (!lse.getValueIsAdjusting()) {
// skip all the intermediate events . . .
StringBuffer buf = new StringBuffer();
int[] selection = getSelectedIndices(model.getMinSelectionIndex(),
model.getMaxSelectionIndex());
if (selection.length == 0) {
buf.append("none");
//selectedRow = buf.toString();
}
else {
for (int i = 0; i < selection.length -1; i++) {
buf.append(selection[i]);
buf.append(", ");
}
buf.append(selection[selection.length - 1]);
}
debugger.setText(buf.toString());
System.out.println("CampaignConfiguration: Selected Row: " + selection[selection.length - 1]);
// Set the selected row for removal;
selectedRow = selection[selection.length - 1];
}
}
// This method returns an array of selected indices. It's guaranteed to
// return a nonnull value.
protected int[] getSelectedIndices(int start, int stop) {
if ((start == -1) || (stop == -1)) {
// no selection, so return an empty array
return new int[0];
}
int guesses[] = new int[stop - start + 1];
int index = 0;
// manually walk through these . . .
for (int i = start; i <= stop; i++) {
if (model.isSelectedIndex(i)) {
guesses[index++] = i;
}
}
// ok, pare down the guess array to the real thing
int realthing[] = new int[index];
System.arraycopy(guesses, 0, realthing, 0, index);
return realthing;
}
}
}
The TableModel has nothing to do with selection. The View(JTable) is responsible for the selection.
I want to get the value int selectedRow and use it to remove it from the table and my ArrayLists.
You should NOT have separate ArrayLists. The data should only be contained in the TableModel.
If you want to delete a row from the table (and the TableModel) then you can use the getSelectedIndex() method of the table in your ActionListener added to the "Delete" button. Something like:
int row = table.getSelectedIndex();
if (row != -1)
{
int modelRow = table.convertRowIndexToModel( row );
tableModel.removeRow( modelRow );
}
If you are not using the DefaultTableModel, then your custom TableModel will need to implement the "removeRow(...)" method.

Validate if jtable is empty?

I need to know how to check if there is data in a JTable something like
if(jTextField1.getText().isEmpty()):
then (if jTable1.isEmpty())
...
how I do that?
JTables are not simple components like the jtextfield, like other swing components they have an underlying Data Model, check this example from the javadoc:
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
Like in every UI object that follows the MVC pattern, you don't use the graphical component to understand the values it has, you use the data model. In you case, save a reference to the Data Model of the JTable you created and call getRowCount to know how much data you have previously loaded.
Also, check the official docs here.
I validate if the jtable is empty with
this code.
private int calculate() {
Vector<Integer> myvector = new Vector();
TableModel mode = new DefaultTableModel();
mode = jTable2.getModel();
int n = mode.getRowCount();
for (int i = 0; i < n; i++) {
if (mode.getValueAt(i, 3) != null) {
myvector.add((Integer) mode.getValueAt(i, 3));
}
}
return myvector.size();
}
//then I validate with a button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int numofvalidrows;
numofvalidrows = calculate();
if (numofvalidrows == 0) //if the size of the vector is 0 then the jtable is empty
{
System.out.println("You need to add people to the jtable, because the table is empty");
} else {
// I get the values of the jtable with
for (int i = 0; i < n; i++) {
if (model.getValueAt(i, 3) != null) { //whith this "if" I print only data, not print null of the empty cells in jtable
System.out.print(model.getValueAt(i, 3))
}
}
}
}

how to avoid duplicating JTable columns in java?

i want to add a cloumn to a jtable when a radio button is being clicked. but when i click it twice two columns are being added to the table. here's my code
dtm = (DefaultTableModel) viewTable.getModel();
dtm.setRowCount(0);
TableColumnModel model=viewTable.getColumnModel();
boolean found=false;
for (int i = 0; i < viewTable.getColumnCount(); i++) {
if (model.getColumn(i).getIdentifier().equals("customer Id")) {
found=true;
break;
}
if (found==false) {
dtm.addColumn("customer Id");
}
don't know how to fix it..
This code would help you. Call the below method on actionPerformed of the check box and if it is true. Validating it based on the column header.
private static void addColumn( final JTable table, final String newColumnHeader )
{
final JTableHeader header = table.getTableHeader();
final int columnCount = header.getColumnModel().getColumnCount();
boolean addColumn = true;
for( int index = 0; index < columnCount; index ++ )
{
final Object headerValue = header.getColumnModel().getColumn(index).getHeaderValue();
if( newColumnHeader.equals( headerValue ) )
{
JOptionPane.showMessageDialog(null, "Column already exists" );
addColumn = false;
break;
}
}
if( addColumn )
{
final TableColumn newCol = new TableColumn();
newCol.setHeaderValue(newColumnHeader);
table.getColumnModel().addColumn(newCol);
}
}
It is good to disable the checkbox if it is already clicked ;) if you do not want a huge code.
This is a clumsy solution but it will work.
You can create a new boolean variable in your class and this variable represents if a column was set or not.
Like:
class MyClass{
boolean isColumnAdded
public MyClass(){
isColumnAdded = false;
}
private void radioButtonActionPerformed(java.awt.event.ActionEvent evt){
if(!isColumnAdded){
//add column
isColumnAdded = true;
}
}
}
To start with, JRadioButton has a selected property. You should be checking this state to determine if the column needs to be removed or added...
Assume that each column name is unique, you could use something like...
TableColumnModel model = viewTable.getColumnModel();
int index = -1;
try {
index = model.getColumnIndex("customer Id");
} catch (IllegalArgumentException e) {
// I know, sucks...
}
if (index < 0) {
// Add new column, if JRadioButton.isSelected
} else {
// Remove old column...
// JRadioButton.isSelected is false...
}
To find and add/remove the column.
Have a look at How to Use Buttons, Check Boxes, and Radio Buttons for some more details

Categories

Resources