I write a code that add/delete data from database to JTable which has 3 columns when User press "Add" or "Delete" Button (JtoggleButton) and then press the buttons(JButton) that their labels are the number from 1 to 9.
Here the user interface of the code:
When I try to add data to the table in the first time, it's ok and the number of columns is still 3 columns:
But when I add data in the second or third time continuously , there are more 3 extra blank columns added into the table too which I don't need it.:
Here the code that I think the problem is occurred:
final DefaultTableModel defaultmodel2 = new DefaultTableModel();
final JToggleButton tglbtnAdd = new JToggleButton("Add");
final JToggleButton tglbtnDelete = new JToggleButton("Delete");
JButton button = new JButton("1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection dbconbt1 = DriverManager.getConnection("" +"jdbc:sqlserver://localhost;databaseName=Store;user=<>;password=<>");
Statement sqlstatement = dbconbt1.createStatement();
ResultSet dbresultset1 = sqlstatement.executeQuery("select * from Store.dbo.Product where ProductID = 'P-1'");
ResultSetMetaData rsmetadata = dbresultset1.getMetaData(); // Get metadata on them
int numcols = rsmetadata.getColumnCount(); // How many columns?
if(tglbtnAdd.isSelected() == true)
{
for (int i = 1; i <= numcols; i++)
{
defaultmodel2.addColumn( rsmetadata.getColumnName(i));
}
while (dbresultset1.next())
{ Vector<Object> row = new Vector<Object>(numcols);
for (int i = 1; i <= numcols; i++)
{
row.addElement( dbresultset1.getObject(i) );
}
defaultmodel2.addRow(row );
}
}
if(tglbtnDelete.isSelected() == true)
{
defaultmodel2.removeRow(0);
}
// Get row
dbresultset1.close();
sqlstatement.close();
dbconbt1.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Every time you call actionPerformed, you are also calling defaultmodel2.addColumn( rsmetadata.getColumnName(i));
This means, that each time an actionPerformed method is called, it is adding more columns to the column model.
You have a few choices...
Check to see if the table model already contains columns and don't add new ones
Check to see if the table model has the particular column and don't add it if it does
Uses the columns from "Product List" table instead...
Related
I'm trying to get all value from a table where the checkbox is checked, I've make codes but it only gets one output and not working if I checked randomly you have to start checking from the start to make it work.
This the Output I need:
this my current codes I've make:
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.setText(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
this codes only display is one value at the text area.
I hope you can help me with this problem.
You can try below.
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.append(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
This question already has an answer here:
Display JCheckBox in JTable
(1 answer)
Closed 6 years ago.
i am create a swing based authentication system and i have a table where i wish to print some necessary details and want the last columnn to have a checkbox. Even after giving a boolean value it is printing true or false rather than a checkbox
controlPanel.removeAll();
System.out.println("coming1");
JournalApprovalClass JAC = new JournalApprovalClass();
JournalApproval JA = new JournalApproval();
String[] columns = { "Author1", "Author2", "Author3",
"Author4", "Author5", "Author6", "Title",
"JournalName", "Scopus", "ImpactFactor",
"JournalMonth", "JournalYear", "NamePublisher",
"VolumeIssuePageNo", "BtechMtech", "OtherDetails",
"Approval" };
System.out.println("coming2");
try {
JA.adminApprovalJournalApproval();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("coming3");
DefaultTableModel model = new DefaultTableModel(
journalTable.values2, columns);
JTable journalAdminApprovalTable = new JTable(model);
journalAdminApprovalTable
.setPreferredScrollableViewportSize(new Dimension(
1200, 100));
journalAdminApprovalTable.setFillsViewportHeight(true);
TableColumn column = null;
for (int i = 0; i <= 16; i++) {
column = journalAdminApprovalTable.getColumnModel()
.getColumn(i);
column.setPreferredWidth(50);
if (i == 16) {
column.setPreferredWidth(10);
}
}
System.out.println("coming4");
JScrollPane scrollPane = new JScrollPane(
journalAdminApprovalTable);
controlPanel.add(scrollPane);
controlPanel.revalidate();
controlPanel.repaint();
System.out.println("coming5");
This is where i am trying to create to create the table the data object is created in another class
ma.values[0] = au.Author1;
ma.values[1] = au.Author2;
ma.values[2] = au.Author3;
ma.values[3] = au.Author4;
ma.values[4] = au.Author5;
ma.values[5] = au.Author6;
ma.values[6] = au.Title;
ma.values[7] = au.JournalName;
ma.values[8] = au.Scopus;
ma.values[9] = au.ImpactFactor;
ma.values[10] = au.JournalMonth;
ma.values[11] = au.JournalYear;
ma.values[12] = au.NamePublisher;
ma.values[13] = au.VolumeIssuePageNo;
ma.values[14] = au.BtechMtech;
ma.values[15] = au.OtherDetails;
ma.values[16] = new Boolean(true);
/*if (au.AdminApproval == "NO") {
ma.values[16] = new JCheckBox("Approval");
} else
ma.values[16] = new Boolean(true);*/
ma.values1[i] = new Object[17];
ma.values1[i] = ma.values;
System.out.println(ma.values1[i] + " " + ma.values[0] + " "
+ i);
i++;
}
resultSet.next();
}
journalTable.values2 = new Object[i][];
for (int j = 0; j < i; j++)
journalTable.values2[j] = journalTable.values1[j];
return;
Everything is working properly but the thing what i wish for is to have checkbox which is always checked(the reason behind giving true).
when i run the code i get the following output
last column i need a checkbox
It is because your model is operating on String rather than Object. I am not able to run your code, but if I were you I would:
Try to change String[] columns to Object[] columns.
If that
doesn't help, take a look at this
I have 5 checkboxes and I have limitted the selection to 3 only. The list values of each selected checkbox will be stored to the database and pad the list with zeroes if it has less than 3 entries. How can I pad the list with zeroes?
List < Integer > preferences = new ArrayList < Integer > ();
if (chckbxLei.isSelected()) {
preferences.add(Integer.valueOf(chckbxLei.getName()));
}
if (chckbxAdv.isSelected()) {
preferences.add(Integer.valueOf(chckbxAdv.getName()));
}
if (chckbxHis.isSelected()) {
preferences.add(Integer.valueOf(chckbxHis.getName()));
}
if (chckbxOut.isSelected()) {
preferences.add(Integer.valueOf(chckbxOut.getName()));
}
if (chckbxFAK.isSelected()) {
preferences.add(Integer.valueOf(chckbxFAK.getName()));
}
if (preferences.size() > 3) {
JOptionPane.showMessageDialog(frame,
"Please Select Only 3! ");
return;
}
Place place = new Place();
try {
place.addPre(preferences);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Place.java
public void addPre(List < Integer > preferences) throws Exception {
DatabaseConnection db = new DatabaseConnection();
Connection connect = db.getConnection();
String sql = "Insert into preferences(Pre1,Pre2,Pre3,Pre4,Pre5)VALUES (?,?,?,?,?) ";
PreparedStatement ps = connect.prepareStatement(sql);
for (int i = 0; i < 5; i++) {
ps.setInt(i + 1, preferences.get(i));
}
ps.executeUpdate();
connect.close();
ps.close();
}
try this
for(int i=preferences.size();i<3;i++)
preferences.add(0);
If I understand what you are trying to achieve then you have to create list with 5 elements with 0 values each. Then instead of adding values to the list you have to set value to exact element. Then you can iterate over 5 elements.
is there any way to retrieve database rows using component other than jTable where unique jButtons for each row can added and made to perform specific task?
Currently I'm using the following code... jTable appears in a dialog box
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
System.out.println("7");
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
public void searchb2() throws SQLException {
this.be_cgpa = be_cg.getText();
this.maj_proj = Major.getText();
this.h_percent = hss_percent.getText();
this.s_percent = sss_percent1.getText();
preparedStatement = con.prepareStatement("select name,age,gender,email_id,phone_num,state from resume1 where qualification='be' and be_cgpa>='" + be_cgpa + "'" + "and maj_proj_tech='" + maj_proj + "'" + "and hss_percent>='" + h_percent + "'" + "and sss_percent='" + s_percent + "'");
ResultSet rs;
rs = preparedStatement.executeQuery();
JTable table = new JTable(buildTableModel(rs));
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
Can this code be modified to add jButton in each row?
There is no reason you can't use JTable and add a column containing buttons to the table.
See Table Button Column for one way to do this. This class expects you to provide an Action that is invoked when the button is clicked. All you need to do is add another String of text to the "vector" after you have finished looping through the column data.
Also, use a PreparedStatement for your SQL. It is easier to code and understand and less error prone than your current code.
table button column is definitely the best way of achieving particular cell's value on clicking the corresponding button but seems to be 1 of the hardest thing in jtable.
another approach for implementing the above is enabling cell selection and using list selection model and list selection listener.
On clicking any cell you can get cell's data in a variable.
you can even fix a column and make an ordinary column with text as "button i" where i=row number. and on clicking this cell, you'll get only particular column's data of corresponding row and can even open a new frame or dialog box depending on your coding, this will make it work like a jbutton! (Actually due to fixed column, clicking any cell in that row will perform that task with column number same as fixed column)
Here is a sample code :
final JTable table;
table = new JTable(data, columnNames)
{
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
table.setCellSelectionEnabled(true);
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int[] selectedRow = table.getSelectedRows();
for (int i = 0; i < selectedRow.length; i++) {
selectedData = (String) table.getValueAt(selectedRow[i],2);
}
new NewJFrame().setVisible(true);
System.out.println("Selected: " + selectedData);
}
I want to display the data out of my result set into a JTable.
When I run the following code the table doesn't update.
public void getHouses(int price) {
Connection conn;
ArrayList<Integer> ID = new ArrayList<Integer>();
ArrayList<String> Price = new ArrayList<String>();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Houses");
Statement statement = conn.createStatement();
ResultSet rec = statement.executeQuery("SELECT * FROM Houses WHERE Price <= " + price + "");
while (rec.next()) {
ID.add(rec.getInt("ID"));
Price.add(rec.getString("Price"));
}
String[] columnNames = {"House ID", "House Price"};
Object[][] rows = new Object[ID.size()][2];
for (int i = 0; i < ID.size(); i++) {
rows[i][0] = ID.get(i);
rows[i][1] = Price.get(i);
}
jTable1 = new JTable(rows, columnNames);
statement.close();
} catch (SQLException se) {
} catch (ClassNotFoundException cnf) {}
}
NOTE!
I added the JTable to the gui by drag and drop.
I also tested that my resultset has the data in it.
You need to learn about OP Swing MVC pattern, you need to declare a TableModel which your data store then set it to your table, like:
TableModel myData = new DefaultTableModel(columnVector, dataVector);
jTable1.setModel(myData);
Read more about DefaultTableModel