Increase row count in a JTable - java

I'm developing an address book for my classmates but I'm having a problem with a JTable. Here you can see a preview of the program, I'm using NetBeans [click]. If you click Add to the Address Book, the program adds a new row in that table and fills its cells with the data located in text fields below. I'm using the following code but the row count doesn't increase.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
int h;
DefaultTableModel model = new DefaultTableModel();
h=jTable1.getRowCount()+1;
model.setRowCount(h);
jTable1.setValueAt(jTextField2.getText(), h, 1);
jTable1.setValueAt(jTextField3.getText(), h, 2);
//I'll use more setValueAt() because I must fill all the cells
}
Could you give me some advice as to how to fix this problem?

You created a new model. You should take the model that is assigned to the table.
DefaultTableModel model = new DefaultTableModel();
should be:
DefaultTableModel model = jTable1.getModel();

Related

Java - Adding items from arraylist to JTable when button clicked

I was trying to write the GUI for my program. I have a Product class in which I store price and names of the products in an arraylist. I also have an Order arraylist which consists of the orders given to each waiter.I put all my products in a JComboBox and added an action listener to each to show the price of each product when clicked by updating the text of a JLable. Then there is a JSpinner to get the quantity of the products selected. And lastly there is an "Add" button that I wanted to use to update the Jtable with product name and its quantity and its total price while also adding that product to the arraylist of Orders. I have no idea how populate JTable and couldn't understand much from other answers because they were using netbeans. I thought of just using a simple JLabe but also I couldn't understand how to update the text and add a new line to the label after I select and add each product. Can you explain how I can achieve this? part of my code looks like this
box1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Product prod = (Product) box1.getSelectedItem();
price.setText(String.valueOf(prod.getSellingPrice()));
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int numbs = (Integer) spinner.getValue();
for (int i = 0; i <= numbs; i++) {
order.addProduct(prod);
}
JLabel label = new JLabel();
lists.add(label);
label.setText(prod.getName() + " " + numbs + " " + numbs * prod.getSellingPrice());
}
});
}
});
If I understand your question correctly, you want a JTable in your gui, which shows the orders (or other data possibly) if a button is clicked.
Firstable, I would advise you to check out
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html
as they explain the use of the JTable very well.
Anyway, to answer your question:
Firstable, you have to create a table and add it to your gui:
//creating a new JTable without any data and one column 'Orders'
//you might wanna declare the JTable before that, since it will be referred to in the refresh() method
JTable table = new JTable(new String[][]{{""}}, new String[]{"Orders"});
//creating a scrollpane to put the table in, in case the table data exeeds the table
JScrollPane scrollPane = new JScrollPane();
//here you would e.g. set the bounds of the scrollpane etc
scrollPane.setBounds(x,y,w,h)
//setting the table in the scrollpane
scrollPane.setViewportView(table);
//adding the scrollpane to your contentPane
contentPane.add(scrollPane);
Now you want to refresh the table, if a button is pressed, so I would put a reference to the following method in the actionlistener of the button:
//the method to refresh the table containing the orders (or possibly other data)
void refresh(List<String> orders) {
//creating a new TableModel for the table
DefaultTableModel model = new DefaultTableModel();
//set the data in the model to the data that was given, new Object[]{0} points to the 1st column
model.setDataVector(getDataVector(data), new Object[]{"Orders});
//set the model of the table to the model we just created
table.setModel(model);
}
Since model.setDataVecor() takes rows and not columns as its first parameter, you have to make the list of data fitting as a data vector, for example with the following method:
Object[][] getDataVector(List<String> data){
Object[][] vector = new Object[data.size()][1];
for(int i=0; i<data.size(); i++){
vector[i][0] = data.get(i);
}
return vector;
}

JTable sorting not the good value in the cell

I am using NetBeans to write a program. I create a JTable with the design and I add rows to the table without any problem.
When I click on the tab to sort the table it works, with setAutoCreateRowSorter(true). However when I try to get the value of the updated cell it is not the good one. Indeed, it is the value of the previous cell, when I fill my table.
This is how I add row to my table:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
for (int i = 0; i < arrayPep.size(); i++) {
model.addRow(new Object[]{arrayPep.get(i).getPeptide(), arrayPep.get(i).getStart(), arrayPep.get(i).getStop(), arrayPep.get(i).geteValue(), arrayPep.get(i).getName()});
}
This is how I try to get the value of the cell:
DefaultTableModel model = (DefaultTableModel) table.getModel();
table.getModel().getValueAt(rowSelected, 0);
How could I fix this ?
You are indexing the model with an index from the view. First convert the view index to a model index using JTable.convertRowIndexToModel(rowSelected):
int modelRowSelected = table.convertRowIndexToModel(rowSelected);
table.getModel().getValueAt(modelRowSelected, 0);
For some context regarding view indexes and model indexes, please read this answer I gave on the topic.

After sorting a jtable how can I number a column?

Hello am developing a Java Desktop result system I have succeeded in sorting my J table with respective to the column average Am still trying to give positions to the students after the J table has been sorted so that each student gets his or her position basing on his or her average this is what I have done so far..`
//Sorts j Table basing on column average
public void checkPosition(){
//Erases column s/no
jTable1.getColumnModel().getColumn(0).setMinWidth(0);
jTable1.getColumnModel().getColumn(0).setMaxWidth(0);
jTable1.getColumnModel().getColumn(0).setWidth(0);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable1.getModel());
jTable1.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<>(2000);
sortKeys.add(new RowSorter.SortKey(jTable1.getColumnCount()-2, SortOrder.DESCENDING));
//sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
positionInsert();
}
public void positionInsert(){
//Inserts position at last column "position"
int pos=1;
for(int g=0; g<jTable1.getRowCount(); g++){
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt(pos, g, jTable1.getColumnCount()-1);
pos++;
}
}
However it still doesn't work the position is still faulty Screenshot of j table
The table is seen at the link above my english is not that good but help will be much appreciated thanks
When you sort a table the data in the table model doesn't change, only the order in which the data is displayed in the table.
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt(pos, g, jTable1.getColumnCount()-1);
The above code assumes that the data in the model is in the same order as the table which is wrong when you sort of filter a table.
You need to update the data in the model via the table:
table.setValueAt(pos, g, jTable1.getColumnCount()-1);
The table will now convert the row of the table to the row of the model before updating the model.
Or if you want to update the model directly, you are responsible for converting the table row to the model row. This is done by using the convertViewToModel(...) method of the JTable.

add an image from Database into JTable

i am trying to add an image that is in my database in a column in JTable
with a number and a code special to this image the problem is i got the number and the code but the image doesn't show i don't know why here is my code
String sql="SELECT id,chiffre,image FROM symbolique WHERE id BETWEEN 200 and 205";
try{
st=connexion.prepareStatement(sql);
res=st.executeQuery();
while(res.next()){
int j=0;
String [] code= new String[1000];
String [] chiffre1=new String[100];
code [j] = res.getString("id");
chiffre1[j] = Integer.toString(res.getInt("chiffre"));
Blob blob = res.getBlob("image");
is2 = new BufferedInputStream(blob.getBinaryStream());
Image raw = ImageIO.read(is2);
ImageIcon icon =new ImageIcon(raw);
Object [][] data = new Object[200][100];
data[j][1]= code [j];
data[j][2]= chiffre1[j];
data[j][3]=icon;
j++;
String title[] = {"image", "chiffre","code"};
DefaultTableModel model = new DefaultTableModel(data, title);
table.setModel(model);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);}
}
put Icon/ImageIcon to JTable better to the TableModel directly
you have to override getColumnClass for Icon/ImageIcon in XxxTableModel for showing this Object as image in the JTables view
for detailed informations (incl. working code examples) to read official Oracle tutorial - How to use Tables
This won't help solve the image problem but right now your code recreates the TableModel for every row in the ResultSet, which means you will only ever see one row of data.
Since you have looping code you need to create an empty DefaultTableModel before the loop starts.
Inside the loop you then use the addRow(...) method to add another row of data to the TableModel for every row in the ResultSet
When you finish the loop then you use the model to create the JTable.
Did you add any debug code? Did you attempt to display the width/height of the image to confirm that you are reading the image properly? Why don't you do a simple test that tries to read and display an image in a JLabel first since using a JTable is more complicated than using a JLabel. Then once you get that working you can apply the knowledge to using a JTable.

How to add row of data to Jtable from values received from jtextfield and comboboxes

I have a JFrame Form which has JTextFields, JCombobox etc. and I am able to receive those values to variables and now I want to add the received data to JTable in new row when user clicks Add or something like that.
I have created JTable using net-beans the problem is what would be the code to add data from those variable to the rows of table. A basic example would be appreciated. I have tried numerous example and have added the code to ActionListener of the JButton but nothing Happens.
The Examples I tried are. How to add row in JTable? and How to add rows to JTable with AbstractTableModel method?
Any Help would be appreciated.
Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder
Set the table column headers
Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
Click on the ... button to the right of the property model. A dialog should appear.
Set rows to 0, set the number of columns you want, and their names.
Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row
Right-click on the button and select Events -> Action -> actionPerformed
You should see code like the following auto-generated
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
The jTable1 will have a DefaultTableModel. You can add rows to the model with your data
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
String data1 = something1.getSomething();
String data2 = something2.getSomething();
String data3 = something3.getSomething();
String data4 = something4.getSomething();
Object[] row = { data1, data2, data3, data4 };
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
// clear the entries.
}
So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.
you can use this code as template please customize it as per your requirement.
DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();
list.add(textField.getText());
list.add(comboBox.getSelectedItem());
model.addRow(list.toArray());
table.setModel(model);
here DefaultTableModel is used to add rows in JTable,
you can get more info here.
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.

Categories

Resources