SQL statement to JTable - java

I'd like to show all data out of a sqlite3 database inside of a JTable.
My result statement function looks like this:
public void getCustomerData()
{
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ArrStrResult[][] = null;;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:database.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT * FROM kunden");
ResultSetMetaData metadata = rs.getMetaData();
int numberOfColumns = metadata.getColumnCount();
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String vorname = rs.getString("vorname");
String gebdatum = rs.getString("gebdatum");
String strasse = rs.getString("strasse");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "VORNAME = " + vorname );
System.out.println( "Geb.-Datum = " + gebdatum );
System.out.println( "Straße = " + strasse );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
In my MainWindow - class I'd like to have the result of the sql statement inside of a JTable which looks like this:
private void updateCustomerTable()
{
// Tabellengrundgerüst erstellen
tableCustomer = new JTable();
tableCustomer.setEnabled(false);
tableCustomer.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableCustomer.setModel(new DefaultTableModel(
new Object[][] {,
},
new String[] {
"Name:", "Vorname:", "Kd.-Nr.:", "Geb.-Datum:", "Stra\u00DFe:", "PLZ:", "Stadt:", "Email:", "Telefon:", "Handy:", "Termin:", "Bemerkung:"
}
));
scrollPaneCustomer.setViewportView(tableCustomer);
What is the best way to get all values of the sql statement inside the JTable?

I'll leave you with an example that shows how you can fill the table. It's all wrapped in one MCVE, things like the Person class and the PersonModel class should exist as top-level classes.
Look at the readData method and see it as the method you have that reads the data. It should return the data as a list that can be set as the data container of the table model. In this case the PersonModel stores the data in a generic List<Person>. The readData method in this example is lazy in that it returns a simple Arrays.asList which returns a List<> wrapper around an array (i.e. it's fixed size). You will probably want to return an ArrayList from your data-reading method if you want to add/remove rows from the UI.
You can find more details on this way of working in #camickr's article he already posted as a comment, here.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.AbstractTableModel;
public class JTableFillExample {
private static class Person {
int id;
String firstName;
String surName;
Date birthDate;
String address;
public Person( int id, String firstName, String surName, Date birthDate, String address ) {
this.id = id;
this.firstName = firstName;
this.surName = surName;
this.birthDate = birthDate;
this.address = address;
}
}
#SuppressWarnings("serial")
private static class PersonModel extends AbstractTableModel {
private List<Person> dataContainer;
private static String[] columnNames = {
"ID",
"First Name",
"Surname",
"Birth Date",
"Address"
};
public PersonModel() {
dataContainer = new ArrayList<>();
}
#SuppressWarnings("unused")
public PersonModel(List<Person> dataContainer) {
this.dataContainer = dataContainer;
}
public void setDataContainer(List<Person> dataContainer) {
this.dataContainer = dataContainer;
fireTableDataChanged();
}
#Override
public int getRowCount() {
return dataContainer.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person p = dataContainer.get(rowIndex);
switch(columnIndex) {
case 0: return p.id;
case 1: return p.firstName;
case 2: return p.surName;
case 3: return p.birthDate;
case 4: return p.address;
default: return null;
}
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0: return Integer.class;
case 3: return Date.class;
default: return String.class;
}
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Person p = dataContainer.get(rowIndex);
switch(columnIndex) {
case 0: p.id = (Integer) aValue; break;
case 1: p.firstName = (String) aValue; break;
case 2: p.surName = (String) aValue; break;
case 3: p.birthDate = (Date) aValue; break;
case 4: p.address = (String) aValue; break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
}
private static Component createTable() {
return new JTable( new PersonModel() );
}
protected static JFrame createFrame() {
JPanel p = new JPanel( );
p.setLayout( new BorderLayout( ) );
p.add( new JScrollPane( createTable( ) ), BorderLayout.CENTER );
p.setPreferredSize( new Dimension( 400, 100 ) );
JFrame f = new JFrame( );
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setContentPane( p );
f.pack( );
return f;
}
private static List<Person> readData() {
return Arrays.asList (
new Person( 1, "Tom", "T", new GregorianCalendar(1975,7,15).getTime(), "Somewhere in Ghent City"),
new Person( 2, "Jack", "N", new GregorianCalendar(1951,5,13).getTime(), "Somewhere in the States"),
new Person( 3, "Madonna", "H", new GregorianCalendar(1960,1,19).getTime(), "Somewhere in the States as well")
);
}
private static void readDataAndFillTable(JTable tbl) {
((PersonModel) tbl.getModel()).setDataContainer(readData());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = createFrame();
f.setVisible(true);
final JTable tbl = (JTable) ((JScrollPane) f.getContentPane().getComponent(0)).getViewport().getView();
Timer t = new Timer(1000, new ActionListener() { // fill the table after a second
#Override
public void actionPerformed(ActionEvent e) {
readDataAndFillTable(tbl);
}
});
t.setRepeats(false);
t.start();
}
});
}
}

The way that I have done this previously is for student details, in the code below I have created a table for each class in my sql database. There are two methods below, one getting all of the details from the database and one filling the data into a JTable, I have got my connection in another method too.
public void alldet(){
JFrame frame = new JFrame("All Details");
JPanel panel = new JPanel(new MigLayout());
JButton back = new JButton("Back");
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Name");
model.addColumn("Surname");
model.addColumn("Gender");
model.addColumn("Target");
model.addColumn("Grade");
model.addColumn("Class");
JTable table = new JTable(model);
JTable table2 = new JTable(model);
JTable table3 = new JTable(model);
filldata(table, "details");
filldata(table2, "details2");
filldata(table3, "details3");
table.setPreferredScrollableViewportSize(new Dimension(519, 350));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
panel.add(back, "dock south");
frame.add(panel);
frame.setSize(519,405);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setResizable(true);
panel.repaint();
frame.setVisible(true);
back.addActionListener((ActionEvent e) -> {
frame.hide();
});
}
public void filldata(JTable table, String type){
try
{
Connection conn = Connect();
if(!Main.teachclass.equals("All")){
Query = "SELECT name,surname,gender,target,grades,class FROM "+type+" WHERE class = ?";
statement = conn.prepareStatement(Query);
statement.setString(1, Main.teachclass);
}else{
Query = "SELECT name,surname,gender,target,grades,class FROM "+type;
statement = conn.prepareStatement(Query);
}
ResultSet res = statement.executeQuery();
int columns = res.getMetaData().getColumnCount();
while(res.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = res.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(res.getRow() - 1, row);
}
res.close();
statement.close();
conn.close();
}
catch(SQLException e)
{
}

Related

Deleting rows with right click from MySql table in JTable

I have a Java class as shown below which displays my table from my database. I want to add a function that will open a pop-up menu and delete row from table. How can i do that?
import java.awt.BorderLayout;
import javax.swing.*;
import java.sql.*;
import java.util.Vector;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String s;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
int c = rsmt.getColumnCount();
Vector column = new Vector(c);
for (int i = 1; i <= c; i++) {
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (rs.next()) {
row = new Vector(c);
for (int i = 1; i <= c; i++) {
row.add(rs.getString(i));
}
data.add(row);
}
JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data, column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
} finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
}
And as a reference i looked to this page but i couldn't bind method from here.
I found an example and i took it as a reference.
I got to handle and rewrite the code as 3 classes shown below:
JTablePopupMenuExample.java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class JTablePopupMenuExample extends JFrame implements ActionListener {
private JTable table;
private DefaultTableModel tableModel;
private JPopupMenu popupMenu;
private JMenuItem menuItemAdd;
private JMenuItem menuItemRemove;
private JMenuItem menuItemRemoveAll;
List<SentMessagesTable> msgList;
public JTablePopupMenuExample() throws Exception{
super("JTable Popup Menu Example");
// sample table data
String[] columnNames = new String[] {"id", "receiver", "sender", "msg_text", "status", "x_date"};
msgList = new ArrayList<SentMessagesTable>();
ResultSet rs = getTableRows();
while (rs.next()) {
SentMessagesTable msg = new SentMessagesTable();
msg.setId(rs.getInt("id"));
msg.setReceiver(rs.getString("receiver"));
msg.setSender(rs.getString("sender"));
msg.setMsgText(rs.getString("msg_text"));
msg.setStatus(rs.getString("status"));
msg.setxDate(rs.getString("x_date"));
msgList.add(msg);
}
String[][] rowDataTable = new String[34400][6];
for(int i = 0 ; i < msgList.size();i++) {
//burda jtable listesini doldur
rowDataTable[i][0] = String.valueOf(msgList.get(i).getId());
rowDataTable[i][1] = msgList.get(i).getReceiver();
rowDataTable[i][2] = msgList.get(i).getSender();
rowDataTable[i][3] = msgList.get(i).getMsgText();
rowDataTable[i][4] = msgList.get(i).getStatus();
rowDataTable[i][5] = msgList.get(i).getxDate();
}
// constructs the table with sample data
tableModel = new DefaultTableModel(rowDataTable, columnNames);
table = new JTable(tableModel);
// constructs the popup menu
popupMenu = new JPopupMenu();
menuItemAdd = new JMenuItem("Add New Row");
menuItemRemove = new JMenuItem("Remove Current Row");
menuItemRemoveAll = new JMenuItem("Remove All Rows");
menuItemAdd.addActionListener(this);
menuItemRemove.addActionListener(this);
menuItemRemoveAll.addActionListener(this);
popupMenu.add(menuItemAdd);
popupMenu.add(menuItemRemove);
popupMenu.add(menuItemRemoveAll);
// sets the popup menu for the table
table.setComponentPopupMenu(popupMenu);
table.addMouseListener(new TableMouseListener(table));
// adds the table to the frame
add(new JScrollPane(table));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,1000);
setLocationRelativeTo(null);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new JTablePopupMenuExample().setVisible(true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent event) {
JMenuItem menu = (JMenuItem) event.getSource();
if (menu == menuItemAdd) {
addNewRow();
} else if (menu == menuItemRemove) {
removeCurrentRow();
} else if (menu == menuItemRemoveAll) {
removeAllRows();
}
}
private void addNewRow() {
tableModel.addRow(new String[0]);
}
private void removeCurrentRow(){
int selectedRow = table.getSelectedRow();
tableModel.removeRow(selectedRow);
String jdbcUrl = "jdbc:mysql://localhost/sms";
String username = "root";
String password = "";
String sql = "delete from sent_messages where id = '"+msgList.get(selectedRow).getId()+"'";
// java.sql.Statement stmt = null;
try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
java.sql.Statement stmt = conn.createStatement();) {
stmt.executeUpdate(sql);
System.out.println("Record deleted successfully");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void removeAllRows() {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(0);
}
}
private ResultSet getTableRows() throws SQLException {
Connection con = null;
java.sql.Statement st = null;
ResultSet rs = null;
String s;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = ((java.sql.Statement) st).executeQuery(s);
}catch(Exception e) {
System.out.println(e.toString());
}
finally {
//con.close();
}
return rs;
}
}
SentMessagesTable.java which involves (getters and setters)
public class SentMessagesTable {
int id;
String receiver;
String sender;
String msgText;
String status;
String xDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getMsgText() {
return msgText;
}
public void setMsgText(String msgText) {
this.msgText = msgText;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getxDate() {
return xDate;
}
public void setxDate(String xDate) {
this.xDate = xDate;
}
}
And TableMouse Listener.java
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTable;
public class TableMouseListener extends MouseAdapter {
private JTable table;
public TableMouseListener(JTable table) {
this.table = table;
}
#Override
public void mousePressed(MouseEvent event) {
// selects the row at which point the mouse is clicked
Point point = event.getPoint();
int currentRow = table.rowAtPoint(point);
table.setRowSelectionInterval(currentRow, currentRow);
}
}
With that code i was able to delete records from JTable and also from my database.

how to retrieve data from database to table using model view controller(mvc) model in swing [duplicate]

I'm making a GUI Project for database there are two classes which are for GUI's. And connector class is used to connect from user credentials. If credentials are correct than it fetch all data in the from of AbstractTableModel. When program run first GUI has a button in which we click it and it fetch all data in underlying TableModel. But i'm facing two problems. First in GUI2 class, sometimes it open like this.
and sometimes it show like this
I don't know why it's happening. And second problem is when we select any row from table and click on DeleteSelectedRow button it delete the row. This button has a ActionListener in GUI2 class. But what i want is i automatic update the table when row has been deleted. How can i do that?
class for first GUI
public class Gui extends JFrame {
private static Connector conni;
private Connection conn = null;
private JButton bt;
private JPanel panel;
public Gui() {
super("Frame");
panel = new JPanel();
bt = new JButton("Connect to Database 'World'");
panel.add(bt);
bt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
conn = conni.Connector();
if (conn != null) {
dispose();
new Gui2(conn);
} else {
System.out.println("Return false");
}
}
});
add(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Connector class
public class Connector {
private static Connection conn = null;
public static Connection Connector() {
String data = "jdbc:mysql://localhost/world";
String user = "root";
String pass = "toot";
try {
conn = DriverManager.getConnection(data, user, pass);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
if (conn != null) {
System.out.println("Connection Suceess");
return conn;
} else {
return conn;
}
}
}
class for second GUI2
public class Gui2 extends JFrame {
private Statement state = null;
private ResultSet rs = null;
private JButton bt, delete;
private JTextField text;
private JPanel panel;
private GridBagLayout layout;
private GridBagConstraints constraints;
public Gui2(Connection conn) {
layout = new GridBagLayout();
constraints = new GridBagConstraints();
panel = new JPanel();
panel.setLayout(layout);
text = new JTextField(15);
bt = new JButton("Submit Query");
delete = new JButton("Delete Selected Row");
constraints.insets = new Insets(5, 2, 5, 10);
constraints.gridy = 0;// row 0
constraints.gridx = 0;// column 0
// TextField add on JPanel with given constraints
panel.add(text, constraints);
constraints.gridx++;
panel.add(delete, constraints);
constraints.gridx++;
panel.add(bt, constraints);
// North BorderLayout
add(panel, BorderLayout.NORTH);
try {
state = conn.createStatement();
rs = state.executeQuery("select * from city");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
JTable table = new JTable();
JScrollPane spane = new JScrollPane(table);
add(spane, BorderLayout.CENTER);
table.setModel(new TableModel(rs));
delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int rowIndex = table.getSelectedRow();
Object columnIndexValue = table.getModel().getValueAt(rowIndex, 0);
String columnName = table.getModel().getColumnName(0);
String query = "delete from world.city" + " where " + columnName + "=" + columnIndexValue;
try {
PreparedStatement pre = conn.prepareStatement(query);
pre.executeUpdate();
JOptionPane.showMessageDialog(null, "Row Deleted Successfully");
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
});
setSize(817, 538);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Tablemodel Class
public class TableModel extends AbstractTableModel {
private List ColumnHeader;
private List tableData;
private List rowData;
private int totalcolumn;
public TableModel(ResultSet rs) {
try {
ResultSetMetaData meta = rs.getMetaData();
totalcolumn = meta.getColumnCount();
ColumnHeader = new ArrayList(totalcolumn);
tableData = new ArrayList();
for (int i = 1; i <= totalcolumn; i++) {
ColumnHeader.add(meta.getColumnName(i));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
SwingWorker<Boolean, List<Object>> worker = new SwingWorker<Boolean, List<Object>>() {
#Override
protected Boolean doInBackground() throws Exception {
while (rs.next()) {
rowData = new ArrayList(totalcolumn);
for (int i = 1; i <= totalcolumn; i++) {
rowData.add(rs.getObject(i));
}
publish(rowData);
}
return true;
}
#Override
protected void process(List chunks) {
tableData.add(chunks);
}
#Override
protected void done() {
try {
Boolean status = get();
JOptionPane.showMessageDialog(null, "Task is DONE");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
};
worker.execute();
}// constructor end
#Override
public int getColumnCount() {
return ColumnHeader.size();
}
public String getColumnName(int columnIndex) {
return (String) ColumnHeader.get(columnIndex);
}
#Override
public int getRowCount() {
return tableData.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
List rowData2 = (List) tableData.get(rowIndex);
return rowData2.get(columnIndex);
}
}
Because database access is inherently asynchronous, you'll surely want to retrieve rows in the background to avoid blocking the event dispatch thread; SwingWorker makes this relatively easy. Fetch rows in your implementation of doInBackground(), publish() interim results, and add them to the table model in your implementation of process(). A complete example that outlines the attendant benefits is shown here. The example loops through a file, but you can substitute your ResultSet operations.
while (rs.next()) {
//collect row data
publish(rowData);
}
Defer tableData.add() to your implementation of process().
Focusing on the interaction between the custom TableModel and its contained SwingWorker, the following complete example creates a test database having N rows and displays a JTable showing the results of a query of that table. In particular,
JDBCModel extends AbstractTableModel. For simplicity, the model's data is stored in a List<Row>, and ResultSetMetaData is used for the column names. As a more abstract alternative, see Apache Commons DbUtils, which uses Class Literals as Runtime-Type Tokens and ResultSetMetaData to safely create instances of row data.
JDBCModel delegates row retrieval to a private JDBCWorker; it invokes publish() on each row retrieved from the ResultSet; because process() runs on the EDT, the worker can optimize the number of table model events that it fires on behalf of the parent model using fireTableRowsInserted().
Similarly, your implementation of delete() should reside in JDBCModel, not the GUI; it should fireTableRowsDeleted() after the row is successfully deleted from the database and removed from data.
Add Thread.sleep() to the worker's background loop to see the effect of artificially increasing latency.
Use setProgress() and a PropertyChangeListener, shown here, to display progress; a JOptionPane when done() may be superfluous.
Override getPreferredScrollableViewportSize() to customize the size of the table's enclosing JScrollPane.
Avoid class names, e.g. TableModel, that collide with common API names.
A variation that implements live filtering in the view is examined here.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
/**
* #see https://stackoverflow.com/a/34742409/230513
* #see https://stackoverflow.com/a/24762078/230513
*/
public class WorkerTest {
private static final int N = 1_000;
private static final String URL = "jdbc:h2:mem:test";
private static final Random r = new Random();
private void display() {
JFrame f = new JFrame("WorkerTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createTestDatabase(N);
JDBCModel model = new JDBCModel(getConnection(), "select * from city");
f.add(new JScrollPane(new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(320, 240);
}
}));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class Row {
int ID;
String name;
}
private static class JDBCModel extends AbstractTableModel {
private final List<Row> data = new ArrayList<>();
private ResultSet rs = null;
private ResultSetMetaData meta;
public JDBCModel(Connection conn, String query) {
try {
Statement s = conn.createStatement();
rs = s.executeQuery(query);
meta = rs.getMetaData();
JDBCWorker worker = new JDBCWorker();
worker.execute();
} catch (SQLException e) {
e.printStackTrace(System.err);
}
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
try {
return meta.getColumnCount();
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return 0;
}
#Override
public Object getValueAt(int rowIndex, int colIndex) {
Row row = data.get(rowIndex);
switch (colIndex) {
case 0:
return row.ID;
case 1:
return row.name;
}
return null;
}
#Override
public String getColumnName(int colIndex) {
try {
return meta.getColumnName(colIndex + 1);
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return null;
}
private class JDBCWorker extends SwingWorker<List<Row>, Row> {
#Override
protected List<Row> doInBackground() {
try {
while (rs.next()) {
Row r = new Row();
r.ID = rs.getInt(1);
r.name = rs.getString(2);
publish(r);
}
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return data;
}
#Override
protected void process(List<Row> chunks) {
int n = getRowCount();
for (Row row : chunks) {
data.add(row);
}
fireTableRowsInserted(n, n + chunks.size());
}
}
}
private static void createTestDatabase(int n) {
Connection conn = getConnection();
try {
Statement st = conn.createStatement();
st.execute("create table city(id integer, name varchar2)");
PreparedStatement ps = conn.prepareStatement(
"insert into city values (?, ?)");
for (int i = 0; i < n; i++) {
ps.setInt(1, i);
ps.setString(2, (char) ('A' + r.nextInt(26))
+ String.valueOf(r.nextInt(1_000_000)));
ps.execute();
}
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
}
private static Connection getConnection() {
try {
return DriverManager.getConnection(URL, "", "");
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return null;
}
public static void main(String[] args) {
EventQueue.invokeLater(new WorkerTest()::display);
}
}

Display database table with swing (Columns names do not show up) [duplicate]

I'm making a GUI Project for database there are two classes which are for GUI's. And connector class is used to connect from user credentials. If credentials are correct than it fetch all data in the from of AbstractTableModel. When program run first GUI has a button in which we click it and it fetch all data in underlying TableModel. But i'm facing two problems. First in GUI2 class, sometimes it open like this.
and sometimes it show like this
I don't know why it's happening. And second problem is when we select any row from table and click on DeleteSelectedRow button it delete the row. This button has a ActionListener in GUI2 class. But what i want is i automatic update the table when row has been deleted. How can i do that?
class for first GUI
public class Gui extends JFrame {
private static Connector conni;
private Connection conn = null;
private JButton bt;
private JPanel panel;
public Gui() {
super("Frame");
panel = new JPanel();
bt = new JButton("Connect to Database 'World'");
panel.add(bt);
bt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
conn = conni.Connector();
if (conn != null) {
dispose();
new Gui2(conn);
} else {
System.out.println("Return false");
}
}
});
add(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Connector class
public class Connector {
private static Connection conn = null;
public static Connection Connector() {
String data = "jdbc:mysql://localhost/world";
String user = "root";
String pass = "toot";
try {
conn = DriverManager.getConnection(data, user, pass);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
if (conn != null) {
System.out.println("Connection Suceess");
return conn;
} else {
return conn;
}
}
}
class for second GUI2
public class Gui2 extends JFrame {
private Statement state = null;
private ResultSet rs = null;
private JButton bt, delete;
private JTextField text;
private JPanel panel;
private GridBagLayout layout;
private GridBagConstraints constraints;
public Gui2(Connection conn) {
layout = new GridBagLayout();
constraints = new GridBagConstraints();
panel = new JPanel();
panel.setLayout(layout);
text = new JTextField(15);
bt = new JButton("Submit Query");
delete = new JButton("Delete Selected Row");
constraints.insets = new Insets(5, 2, 5, 10);
constraints.gridy = 0;// row 0
constraints.gridx = 0;// column 0
// TextField add on JPanel with given constraints
panel.add(text, constraints);
constraints.gridx++;
panel.add(delete, constraints);
constraints.gridx++;
panel.add(bt, constraints);
// North BorderLayout
add(panel, BorderLayout.NORTH);
try {
state = conn.createStatement();
rs = state.executeQuery("select * from city");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
JTable table = new JTable();
JScrollPane spane = new JScrollPane(table);
add(spane, BorderLayout.CENTER);
table.setModel(new TableModel(rs));
delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int rowIndex = table.getSelectedRow();
Object columnIndexValue = table.getModel().getValueAt(rowIndex, 0);
String columnName = table.getModel().getColumnName(0);
String query = "delete from world.city" + " where " + columnName + "=" + columnIndexValue;
try {
PreparedStatement pre = conn.prepareStatement(query);
pre.executeUpdate();
JOptionPane.showMessageDialog(null, "Row Deleted Successfully");
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
});
setSize(817, 538);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Tablemodel Class
public class TableModel extends AbstractTableModel {
private List ColumnHeader;
private List tableData;
private List rowData;
private int totalcolumn;
public TableModel(ResultSet rs) {
try {
ResultSetMetaData meta = rs.getMetaData();
totalcolumn = meta.getColumnCount();
ColumnHeader = new ArrayList(totalcolumn);
tableData = new ArrayList();
for (int i = 1; i <= totalcolumn; i++) {
ColumnHeader.add(meta.getColumnName(i));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
SwingWorker<Boolean, List<Object>> worker = new SwingWorker<Boolean, List<Object>>() {
#Override
protected Boolean doInBackground() throws Exception {
while (rs.next()) {
rowData = new ArrayList(totalcolumn);
for (int i = 1; i <= totalcolumn; i++) {
rowData.add(rs.getObject(i));
}
publish(rowData);
}
return true;
}
#Override
protected void process(List chunks) {
tableData.add(chunks);
}
#Override
protected void done() {
try {
Boolean status = get();
JOptionPane.showMessageDialog(null, "Task is DONE");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
};
worker.execute();
}// constructor end
#Override
public int getColumnCount() {
return ColumnHeader.size();
}
public String getColumnName(int columnIndex) {
return (String) ColumnHeader.get(columnIndex);
}
#Override
public int getRowCount() {
return tableData.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
List rowData2 = (List) tableData.get(rowIndex);
return rowData2.get(columnIndex);
}
}
Because database access is inherently asynchronous, you'll surely want to retrieve rows in the background to avoid blocking the event dispatch thread; SwingWorker makes this relatively easy. Fetch rows in your implementation of doInBackground(), publish() interim results, and add them to the table model in your implementation of process(). A complete example that outlines the attendant benefits is shown here. The example loops through a file, but you can substitute your ResultSet operations.
while (rs.next()) {
//collect row data
publish(rowData);
}
Defer tableData.add() to your implementation of process().
Focusing on the interaction between the custom TableModel and its contained SwingWorker, the following complete example creates a test database having N rows and displays a JTable showing the results of a query of that table. In particular,
JDBCModel extends AbstractTableModel. For simplicity, the model's data is stored in a List<Row>, and ResultSetMetaData is used for the column names. As a more abstract alternative, see Apache Commons DbUtils, which uses Class Literals as Runtime-Type Tokens and ResultSetMetaData to safely create instances of row data.
JDBCModel delegates row retrieval to a private JDBCWorker; it invokes publish() on each row retrieved from the ResultSet; because process() runs on the EDT, the worker can optimize the number of table model events that it fires on behalf of the parent model using fireTableRowsInserted().
Similarly, your implementation of delete() should reside in JDBCModel, not the GUI; it should fireTableRowsDeleted() after the row is successfully deleted from the database and removed from data.
Add Thread.sleep() to the worker's background loop to see the effect of artificially increasing latency.
Use setProgress() and a PropertyChangeListener, shown here, to display progress; a JOptionPane when done() may be superfluous.
Override getPreferredScrollableViewportSize() to customize the size of the table's enclosing JScrollPane.
Avoid class names, e.g. TableModel, that collide with common API names.
A variation that implements live filtering in the view is examined here.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
/**
* #see https://stackoverflow.com/a/34742409/230513
* #see https://stackoverflow.com/a/24762078/230513
*/
public class WorkerTest {
private static final int N = 1_000;
private static final String URL = "jdbc:h2:mem:test";
private static final Random r = new Random();
private void display() {
JFrame f = new JFrame("WorkerTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createTestDatabase(N);
JDBCModel model = new JDBCModel(getConnection(), "select * from city");
f.add(new JScrollPane(new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(320, 240);
}
}));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class Row {
int ID;
String name;
}
private static class JDBCModel extends AbstractTableModel {
private final List<Row> data = new ArrayList<>();
private ResultSet rs = null;
private ResultSetMetaData meta;
public JDBCModel(Connection conn, String query) {
try {
Statement s = conn.createStatement();
rs = s.executeQuery(query);
meta = rs.getMetaData();
JDBCWorker worker = new JDBCWorker();
worker.execute();
} catch (SQLException e) {
e.printStackTrace(System.err);
}
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
try {
return meta.getColumnCount();
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return 0;
}
#Override
public Object getValueAt(int rowIndex, int colIndex) {
Row row = data.get(rowIndex);
switch (colIndex) {
case 0:
return row.ID;
case 1:
return row.name;
}
return null;
}
#Override
public String getColumnName(int colIndex) {
try {
return meta.getColumnName(colIndex + 1);
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return null;
}
private class JDBCWorker extends SwingWorker<List<Row>, Row> {
#Override
protected List<Row> doInBackground() {
try {
while (rs.next()) {
Row r = new Row();
r.ID = rs.getInt(1);
r.name = rs.getString(2);
publish(r);
}
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return data;
}
#Override
protected void process(List<Row> chunks) {
int n = getRowCount();
for (Row row : chunks) {
data.add(row);
}
fireTableRowsInserted(n, n + chunks.size());
}
}
}
private static void createTestDatabase(int n) {
Connection conn = getConnection();
try {
Statement st = conn.createStatement();
st.execute("create table city(id integer, name varchar2)");
PreparedStatement ps = conn.prepareStatement(
"insert into city values (?, ?)");
for (int i = 0; i < n; i++) {
ps.setInt(1, i);
ps.setString(2, (char) ('A' + r.nextInt(26))
+ String.valueOf(r.nextInt(1_000_000)));
ps.execute();
}
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
}
private static Connection getConnection() {
try {
return DriverManager.getConnection(URL, "", "");
} catch (SQLException e) {
e.printStackTrace(System.err);
}
return null;
}
public static void main(String[] args) {
EventQueue.invokeLater(new WorkerTest()::display);
}
}

Display ResultSet of a SQL query in a JTable (Java)

I'm working on a program with which I can search through a database and display the results.
I'm stuck at the displaying part at the moment. My SQL query already works and returns the results. I'm using a PreparedStatement to fill my ResultSet. However I don't know how I can return the data of the ResultSet to a JTable which I want to use to display the data. Can anyone explain to me in detail how to do this or if there is a better way instead of a JTable I'm not seeing?
I'm using the MVC model and the DAO pattern, but I'm still pretty new to programming.
So far from researching it I found the best solution to be to make a custom table class, but from there on I don't know how to progress.
My custom table class:
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class ResultSetTable {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
//Spaltennamen
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
//Alle Zeilen
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
And the relevant part of my View class:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import dbconnect.dao.impl.BTRDaoImpl;
public class View extends JFrame{
public View() {
JTable table = new JTable(new ResultSetTable(BTRDaoImpl.resultset);
this.setSize(600, 400);
setResizable(false);
}
My BTRDaoImpl class with the sql query and resultset:
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import mvc.View;
import dao.BTRbDao;
import business.BTRBean;
public class BTRDaoImpl extends AbstractDao implements BTRDao {
private Connection dbConnection = null;
private PreparedStatement preparedStatement = null;
public void sqlquery() {
try {
String btrname = View.searchbbtrname.getText();
String btrplz = View.searchbtrplz.getText();
btrname = btrname.trim().toUpperCase();
btrplz = btrplz.trim().toUpperCase();
if (btrplz.isEmpty()) {
String btrResult = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ FROM BP.TBBBST WHERE BBSTNABEG = ?";
dbConnection = AbstractDao.getConnection();
preparedStatement = dbConnection.prepareStatement(btrResult);
preparedStatement.setString(1, btrname);
} else {
String btrResult = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ FROM BP.TBBBST WHERE BBSTNABEG = ? AND BBSTPLZ = ?";
dbConnection = AbstractDao.getConnection();
preparedStatement = dbConnection.prepareStatement(btrResult);
preparedStatement.setString(1, btrname);
preparedStatement.setString(2, btrplz);
}
} catch (SQLException e1) {
System.out.println("An error with the SQL query occured: ");
e1.printStackTrace();
}
}
public Collection<BtrBean> getBTR() throws SQLException,
IOException {
sqlquery();
final Collection<BtrBean> result = new ArrayList<BtrBean>();
ResultSet resultset = null;
try {
resultset = preparedStatement.executeQuery();
// while loop to get data
while (resultset.next()) {
BtrBean btr = new BtrBean();
int btrid = resultset.getInt(1);
String btrplz = resultset.getString(3);
String btrname = resultset.getString(2);
btr.setBetriebnr(btrid);
btr.setBetriebplz(btrplz);
btr.setBetriebname(btrname);
result.add(btr);
// System.out.println("BTR-ID: " + btrid + " BTR PLZ: " + btrplz + " BTR: " + btrname);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("An error processing the SQL occured: ");
e.printStackTrace();
} catch (NullPointerException npe) {
System.out.println("NullPointerException: ");
npe.printStackTrace();
} finally {
if (preparedStatement != null) preparedStatement.close();
closeConnection(resultset);
}
return result;
}
}
My BTRBean class:
public class BetriebBean {
private String betriebname;
private int betriebnr;
private String betriebplz;
public BetriebBean() {
}
public BetriebBean(String betriebname, int betriebnr, String betriebplz) {
super();
this.betriebname = betriebname;
this.betriebnr = betriebnr;
this.betriebplz = betriebplz;
}
public String getBetriebname() {
return betriebname;
}
public void setBetriebname(String betriebname) {
this.betriebname = betriebname;
}
public int getBetriebnr() {
return betriebnr;
}
public void setBetriebnr(int betriebnr) {
this.betriebnr = betriebnr;
}
public String getBetriebplz() {
return betriebplz;
}
public void setBetriebplz(String betriebplz) {
this.betriebplz = betriebplz;
}
}
//edit:
My whole View.class:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
public class View extends JFrame{
private static final long serialVersionUID = 1L;
public static final String SEARCH = "SEARCH";
private JLabel searchbtrlabel = new JLabel("BTR name:");
public static JTextField searchbtrname = new JTextField(10);
private JLabel searchbtrlabel = new JLabel("PLZ:");
public static JTextField searchbtrplz = new JTextField(10);
private JButton searchbutton = new JButton();
public View() {
this.setTitle("BTR search TBBBST");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.add(searchbtrlabel);
this.add(searchbtrname);
this.add(searchbtrplzlabel);
this.add(searchbtrplz);
searchbutton.setText("Search");
searchbutton.setActionCommand(View.SEARCH);
this.add(searchbutton);
JTable table = new JTable();
this.add(table);
this.setSize(600, 400);
setResizable(false);
//this.pack();
}
public JTextField getSearchbtrname() {
return searchbetriebname;
}
public JTextField getSearchbbtrplz() {
return searchbetriebplz;
}
public JButton getSearchbutton() {
return searchbutton;
}
}
My Controller class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import mvc.Model;
import dbconnect.dao.impl.BTRDaoImpl;
public class Controller implements Observer, ActionListener{
private Model model;
#SuppressWarnings("unused")
private View view;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
model.addObserver(this);
view.getSearchbutton().addActionListener(this);
view.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case View.SEARCH:
model.search();
view.table.setModel(ResultSetToTable.buildTableModel(BTRDaoImpl.resultset));
break;
default:
System.out.println("Error : " + e.getActionCommand());
break;
}
}
#Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
}
}
Firstly, include rs2xml.jar in your libraries. You can find it here
In whatever action to populate your MySQL query in your JTable use following general idea:
public void sqlquery() {
try {
String btrResult = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ FROM BP.TBBBST WHERE BBSTNABEG = ?";
preparedStatement = dbConnection.prepareStatement(btrResult);
dbConnection.setString(1, btrname);
ResultSet rs =dbConnection.executeQuery();
Ur_table_name.setModel(DbUtils.resultSetToTableModel(DbUtils.resultSetToel(rs)); //this line of code will show it in your JTable
}catch(Exception e){
}
What is your question? Try being more specific than "[...] but from there on I don't know how to progress." What do you want to do? Are the results from your query visible in the table?
Using the answer from Paul Vargas over here Most simple code to populate JTable from ResultSet, you could start with something like this (using Java 8):
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
public class ResultSetToTable {
public static void main(final String[] arguments) {
SwingUtilities.invokeLater(() -> {
try {
new ResultSetToTable().createAndShowGui();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
private void createAndShowGui() throws SQLException {
final JFrame frame = new JFrame("Stack Overflow");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
final TableModel tableModel = buildTableModel(getData("Audi"));
final JTable table = new JTable(tableModel);
panel.add(new JScrollPane(table));
frame.getContentPane().add(panel);
frame.setVisible(true);
}
private ResultSet getData(final String btrName) throws SQLException {
final String url = "jdbc:h2:/Freek/TBBBST";
final Connection connection = DriverManager.getConnection(url, "me", "123");
final String sql = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ " +
"FROM BP.TBBBST " +
"WHERE BBSTNABEG = ?";
final PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, btrName);
return preparedStatement.executeQuery();
}
/**
* See https://stackoverflow.com/a/10625471/1694043
*/
public static TableModel buildTableModel(final ResultSet resultSet)
throws SQLException {
int columnCount = resultSet.getMetaData().getColumnCount();
// Column names.
Vector<String> columnNames = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
columnNames.add(resultSet.getMetaData().getColumnName(columnIndex));
}
// Data of the table.
Vector<Vector<Object>> dataVector = new Vector<>();
while (resultSet.next()) {
Vector<Object> rowVector = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
rowVector.add(resultSet.getObject(columnIndex));
}
dataVector.add(rowVector);
}
return new DefaultTableModel(dataVector, columnNames);
}
}
For older versions of Java, you should be able to use this version of the main method:
public static void main(final String[] arguments) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ResultSetToTable().createAndShowGui();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
Edit: connecting controller and table
To make the table available outside the view, you need to convert the table variable in the View() constructor into a field (like you have done with searchbtrname) and create a getTable getter method for it (like you have done with getSearchbtrname). In the Controller.actionPerformed method you can now change view.table into view.getTable().

Fetch data and image path from database and put them in Jtable

I am trying to fetch some data in a jtable (on click of button) and in the database i have the path of the images stored. so i want to put them in the cell of JTable. My code is very big, because it contains some other information, like when we give a proper information in the text field, then only it will fetch me the data from the database.
This program is running fine, and there is no error in it, I just want to insert photos in one of the column in the table.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class VCstVote extends JFrame implements ActionListener{
JFrame frame;
JTextField tauid, tphone;
JLabel label, auid, aphone;
JButton cls, ok, vote;
JCheckBox chkbx;
JPanel panel,panel1,panel2, panel3;
static JTable table,table2;
DefaultTableModel model1 = new DefaultTableModel();
VCstVote() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException{
final UIManager.LookAndFeelInfo[] plafInfos =UIManager.getInstalledLookAndFeels();
UIManager.setLookAndFeel(plafInfos[1].getClassName() );
frame = new JFrame();
frame.setSize(930, 400);
frame.setTitle("VOTE YOUR CANDIDATE");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
vote = new JButton("VOTE YOUR CANDIDATE");
label = new JLabel("CASTE YOUR VOTE");
label.setFont(new Font("Verdana", Font.BOLD, 18));
panel.add(label);
panel1 = new JPanel();
cls= new JButton("CLOSE");
panel1.add(vote);
panel1.add(cls);
panel2 = new JPanel();
auid = new JLabel("UNIQUE ID",11);
tauid = new JTextField(10);
auid.setFont(new Font("Verdana", Font.BOLD, 10));
aphone = new JLabel("PHONE", 11);
aphone.setFont(new Font("Verdana", Font.BOLD, 10));
tphone = new JTextField(10);
ok = new JButton("SUBMIT");
panel2.add(auid);
panel2.add(tauid);
panel2.add(aphone);
panel2.add(tphone);
panel3 = new JPanel( new FlowLayout(FlowLayout.LEFT, 3,3));
panel3.add(ok);
panel2.add(panel3);
String[] columnNames = {"Candidate Name", "Department Name","Year","Photo","CASTE VOTE"};
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
cls.addActionListener(this);
ok.addActionListener(this);
vote.addActionListener(this);
frame.add(scroll, BorderLayout.WEST);
frame.add(panel2,BorderLayout.EAST);
frame.add(panel,BorderLayout.NORTH);
frame.add(panel1,BorderLayout.SOUTH);
frame.validate();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String action=ae.getActionCommand();
Connection conn = null ;
String cfn= null;
String cln=null;
if(action=="SUBMIT")
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:orcl", "scott","tiger");
String query1="insert into vote (vuid,uphno) values(?,?)";
String query2 = "select uphno from accounts where vuid='"+tauid.getText()+"'";
String query3 = "select p.cfname, p.clname, p.deptname, l.dyear from potential p, leads l where p.cfname=l.cfname and p.clname=l.clname and p.deptname =l.deptname";
String query4 = "Select a.ufname, a.ulname from vote v, accounts a where a.uphno=v.uphno and v.vuid='"+tauid.getText()+"'";
chkbx = new JCheckBox();
PreparedStatement ps1 = conn.prepareStatement(query1);
PreparedStatement ps2 = conn.prepareStatement(query2);
PreparedStatement ps3 = conn.prepareStatement(query3);
PreparedStatement ps4 = conn.prepareStatement(query4);
ResultSet rs2= null;
ResultSet rs3= null;
ResultSet rs4= null;
rs2=ps2.executeQuery();
while(rs2.next())
{
ps1.setString(1, tauid.getText());
ps1.setString(2, rs2.getString(1));
ps1.executeUpdate();
conn.commit();
}
rs4= ps4.executeQuery();
while(rs4.next())
{
cfn = rs4.getString(1);
cln = rs4.getString(2);
}
JOptionPane.showMessageDialog(null, "Hii.. "+cfn+" "+cln+" Please Select Only one Candidate for voting, otherwise you vote will not be counted..");
rs3= ps3.executeQuery();
while(rs3.next())
{
String fname= rs3.getString(1);
String lname= rs3.getString(2);
String dept= rs3.getString(3);
String year= rs3.getString(4);
model1.addRow(new Object[]{fname+" "+lname,dept,year});
table.getColumn("CASTE VOTE").setCellEditor(new DefaultCellEditor(chkbx));
}
for (int i=0;i<model1.getRowCount();i++)
{
model1.setValueAt("false", i, 3);
}
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null,"Please Enter correct information");
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(action=="VOTE YOUR CANDIDATE")
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:orcl", "scott","tiger");
String query1 ="select cfname,clname,deptname,luid from potential";
String test = tphone.getText();
String query2="update vote set cfname=?, clname=?, deptname=?, luid=?, votcount=1 where uphno="+test;
ResultSet rs1 = null;
PreparedStatement ps1= conn.prepareStatement(query1);
PreparedStatement ps2 = conn.prepareStatement(query2);
rs1 =ps1.executeQuery();
for(int i=0;i<model1.getRowCount();i++)
{
Object st = model1.getValueAt(i,3);
String ss= st.toString();
if(ss.equals("true"))
{
rs1.next();
String fname = rs1.getString(1);
String lname = rs1.getString(2);
String dept = rs1.getString(3);
String uid = rs1.getString(4);
ps2.setString(1, fname);
ps2.setString(2, lname);
ps2.setString(3, dept);
ps2.setString(4, uid);
ps2.executeUpdate();
conn.commit();
JOptionPane.showMessageDialog(null,"Successfully registred Your Vote");
}
else{
rs1.next();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(action=="CLOSE")
{
frame.setVisible(false);
}
}
public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
new VCstVote();
}
}
Please help me out of this, I tried many websites and codes, but it seems they are only for a defined set of data and images, none of them has a code which indicates jtable fetching data from database and rendering an image.
i have the path of the images stored. so i want to put them in the
cell of JTable.
put Icon / ImageIcon to JTable (data are stored in TableModel)
is required to override getColumnClass to Icon / ImageIcon for rendering image in the JTables cell
EDIT
I tried this type of coding, but instead it is showing me the path
only.
is required to override getColumnClass to Icon / ImageIcon
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
//or
#Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return Integer.class;
case 1:
return Double.class;
case 2:
return Long.class;
case 3:
return Boolean.class;
case 4:
return String.class;
case 5:
return Icon.class;
/*case 6:
return Double.class;
case 7:
return Double.class;
case 8:
return Double.class;*/
default:
return String.class;
}
}
e.g. used in code
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private JTable table;
private JLabel myLabel = new JLabel("waiting");
private int pHeight = 40;
private boolean runProcess = true;
private int count = 0;
public TableIcon() {
ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
String[] columnNames = {"Picture", "Description"};
Object[][] data = {{errorIcon, "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
// Returning the Class of each column will allow different
// renderers to be used based on Class
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model);
table.setRowHeight(pHeight);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
myLabel.setPreferredSize(new Dimension(200, pHeight));
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(myLabel, BorderLayout.SOUTH);
new Thread(this).start();
}
public void run() {
while (runProcess) {
try {
Thread.sleep(1250);
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ImageIcon myIcon = (ImageIcon) table.getModel().getValueAt(count, 0);
String lbl = "JTable Row at : " + count;
myLabel.setIcon(myIcon);
myLabel.setText(lbl);
count++;
if (count > 2) {
count = 0;
}
}
});
}
}
public static void main(String[] args) {
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocation(150, 150);
frame.pack();
frame.setVisible(true);
}
}

Categories