Add ResultSet into Jtable (between two classes) - java

My application throws NullPointerException. I created connection between MySQL database and my second class.
I can't call DefaultTableModel by method in my second class.
How can I solve this problem?
public class MySQL extends javax.swing.JFrame {
private DefaultTableModel modelTabeli;
public MySQL(){
initComponents();
BazaDana bd = new BazaDana();
try{
modelTabeli = bd.map();
jTable1.setModel(modelTabeli);
}
catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String args[]) throws Exception{
BazaDana bd = new BazaDana();
bd.readDataBase();
}
}
Second class
import java.sql.*;
import javax.swing.table.DefaultTableModel;
public class BazaDana{
public DefaultTableModel map() throws SQLException
{
defaultTableModel = new DefaultTableModel();
int numberOfColumns = resultSetMetaData.getColumnCount();
while (resultSet.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = resultSet.getObject(i+1);
}
defaultTableModel.addRow(rowData);
}
return defaultTableModel;
}
}

Ok, may I give you an alternative solution if your goal is to separate GUI class from class which queries database. Don't return DefaultTableModel, return just values from ResultSet through some collection, like this:
Create MySql GUI class:
import java.awt.EventQueue;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MySql extends JFrame{
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"First column","Second column"});
public MySql(){
table.setModel(model);
add(new JScrollPane(table));
//Populate table
BazaDana bd = new BazaDana();
List<Value> values = bd.selectAll();
for(Value v : values){
model.addRow(new Object[]{v.getFirstValue(),v.getSecondValue()});
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
MySql ms = new MySql();
ms.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ms.pack();
ms.setVisible(true);
}});
}
}
Then create Java bean class:
public class Value {
private int id;
private String firstValue;
private String secondValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstValue() {
return firstValue;
}
public void setFirstValue(String firstValue) {
this.firstValue = firstValue;
}
public String getSecondValue() {
return secondValue;
}
public void setSecondValue(String secondValue) {
this.secondValue = secondValue;
}
}
And finally your BazaDana class which queries database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class BazaDana {
public List<Value> selectAll(){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
//Create list of values
List<Value> values = new ArrayList<Value>();
try{
Class.forName("com.mysql.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nameofdb","user","pass");
st = conn.createStatement();
rs = st.executeQuery("SELECT * FROM mytable");
while(rs.next()){
Value v = new Value();
v.setFirstValue(rs.getString("first_column"));
v.setSecondValue(rs.getString("second_column"));
values.add(v);
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return values;
}
}

Related

How to display Column Headers from a Mysql database in JavaFX TableView?

Let me clarify the question. So I decided to create a TreeView just like in PhpMyAdmin (xampp) that shows all Databases. I successfully managed to get the Databases and Tables in the Treeview, but not the content of the Tables in the TableView. So basically the first thing I want to do is, that if I click on a Table, the column headers should show up in the Table next to the Treeview. I managed to write some code, but it does not do what it is supposed to do. Please help me I am trying to learn this programming language (JavaFX).
This is the Controller class
package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class Controller implements Initializable {
Statement statement;
Statement statementDatabase;
Statement stmntTables;
Statement stmntUse;
Statement stmntCols;
ResultSet resultDatabase;
ResultSet resultTables;
ResultSet resultUse;
ResultSet resultCols;
#FXML
TreeView <String> treeView;
#FXML
TableView<String> tableView;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
try {
statement = DatabaseConnection.getInstance().getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet result = statement.executeQuery("SHOW DATABASES");
TreeItem<String> root = new TreeItem<>("Datenbanken");
while(result.next()) {
TreeItem<String> node = new TreeItem<>(result.getString(1));
root.getChildren().add(node);
Statement statement2 = DatabaseConnection.getInstance().getConnection().createStatement();
ResultSet subResult = statement2.executeQuery("SHOW TABLES FROM " + result.getString(1));
while(subResult.next())
{
TreeItem<String> node2 = new TreeItem<>(subResult.getString(1));
node.getChildren().add(node2);
}
}
result.beforeFirst();
treeView.setRoot(root);
root.setExpanded(true);
ShowDatabase();
UseDatabase();
} catch (Exception e){
e.printStackTrace();
}
}
public void ShowDatabase() {
try {
statementDatabase = DatabaseConnection.getInstance().getConnection().createStatement();
resultDatabase = statementDatabase.executeQuery("SHOW DATABASES");
System.out.println("All Databases displayed!");
} catch (SQLException e) {
System.out.println("Databases could not be displayed!");
e.printStackTrace();
}
}
public void UseDatabase() {
try {
while (resultDatabase.next()) {
stmntUse = DatabaseConnection.getInstance().getConnection().createStatement();
resultUse = stmntUse.executeQuery("USE " + resultDatabase.getString(1));
//System.out.println(resultDatabase.getString(1));
ShowTables();
//System.out.println(resultTables.getString(1));
ShowColumns();
}
System.out.println("Database injected!");
System.out.println("All Tables displayed!");
System.out.println("All Columns displayed!");
} catch (SQLException e) {
System.out.println("Database ejected!");
e.printStackTrace();
}
}
public void ShowTables() {
try {
while (resultDatabase.next()) {
stmntTables = DatabaseConnection.getInstance().getConnection().createStatement();
// System.out.println(resultDatabase);
resultTables = stmntTables.executeQuery("SHOW TABLES FROM " + resultDatabase.getString(1));
// System.out.println(resultTables.getString(1));
}
} catch (SQLException e) {
System.out.println("Tables could not be displayed!");
e.printStackTrace();
}
}
public void ShowColumns() {
try {
while (resultTables.next()) {
stmntCols = DatabaseConnection.getInstance().getConnection().createStatement();
resultCols = stmntCols.executeQuery("SHOW COLUMNS FROM " + resultTables.getString(1));
System.out.println(resultCols);
FillTable(resultCols);
}
} catch (SQLException e) {
System.out.println("Columns could not be displayed!");
e.printStackTrace();
}
}
public void FillTable(ResultSet res) {
TableColumn<String, String>col = new TableColumn<String, String>();
try {
col.setCellValueFactory(new PropertyValueFactory<>(res.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
tableView.getColumns().add(col);
}
}
and this is the Database Connection
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static DatabaseConnection instance;
private Connection connection;
private static String ip = "localhost";
public static void setIp(String ip) {
DatabaseConnection.ip = ip;
}
private DatabaseConnection() throws SQLException
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":" + 3306, "root", "");
System.out.println("Successfully connected to " + ip + "!");
} catch (Exception exc) {
//exc.printStackTrace();
System.out.println("Connection failed to " + ip + "!");
getConnection().close();
}
}
public Connection getConnection() {
return connection;
}
public static DatabaseConnection getInstance() throws SQLException {
if (instance == null) {
instance = new DatabaseConnection();
} else if (instance.getConnection().isClosed()) {
instance = new DatabaseConnection();
}
return instance;
}
}
Here is some code that should get you going. You will probably need a listener on the TreeView to change the table data and headers as you click on different items in the TreeView. This code simulates getting the headers from the database as List<String> and get the data from the database as List<List<String>>.
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* JavaFX App
*/
public class App extends Application {
#Override
public void start(Stage primaryStage) {
ObservableList<ObservableList<String>> data = FXCollections.observableArrayList();
final List<List<String>> databaseData = getTableDataFromDBAsListOfList();//Get data from excel file
//Add database data to an observable list
for(int i = 0; i < databaseData.size(); i++)
{
data.add(FXCollections.observableArrayList(databaseData.get(i)));
}
TableView<ObservableList<String>> tableView = new TableView();
tableView.setItems(data);
//Create the table columns, set the cell value factory and add the column to the tableview.
List<String> tableHeaders = getTableHeadersFromDBAsList();
for (int i = 0; i < tableHeaders.size(); i++) {
final int curCol = i;
final TableColumn<ObservableList<String>, String> column = new TableColumn<>(tableHeaders.get(i));
column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().get(curCol)));
tableView.getColumns().add(column);
}
StackPane root = new StackPane(tableView);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch();
}
public List<String> getTableHeadersFromDBAsList()
{
List<String> returnList = new ArrayList();
returnList.add("Header1");
returnList.add("Header2");
returnList.add("Header3");
returnList.add("Header4");
return returnList;
}
public List<List<String>> getTableDataFromDBAsListOfList()
{
List<List<String>> returnList = new ArrayList();
List<String> dataRow1 = new ArrayList();
dataRow1.add("Data 1 1");
dataRow1.add("Data 1 2");
dataRow1.add("Data 1 3");
dataRow1.add("Data 1 4");
List<String> dataRow2 = new ArrayList();
dataRow2.add("Data 2 1");
dataRow2.add("Data 2 2");
dataRow2.add("Data 2 3");
dataRow2.add("Data 2 4");
returnList.add(dataRow1);
returnList.add(dataRow2);
return returnList;
}
}

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.

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().

Any way to connect JTable (TableModel) with H2 database [duplicate]

This question already has answers here:
How to fill data in a JTable with database?
(7 answers)
Closed 7 years ago.
My current project is some kind of a database system that has a gui for maintenance. Before my major code rewrite, I used to serialize and de-serialize the TableModel to save and load data to the gui. Because this was not a good solution for obvious reasons I did some research and ended up using an H2 (local) database to save and load my data from.
The code used to save the data into my database can be found in my other question.
The save process itself is not the biggest problem but I can't find any good way to load the data back into my JTable (TableModel).
Is there any way to directly wire JTable (TableModel) together with any kind of SQL database? Currently using JTable with a database seems to be a really big hassle with Java.
Okay, so this is a simple example, which creates a in-memory database, with a single table and some values.
It uses a simple custom TableModel which can be "refreshed" if the underlying data is changed.
Have a closer look at JDBC Database Access for some more details
import java.awt.BorderLayout;
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 java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class TestTable {
private Connection con;
public static void main(String[] args) {
new TestTable();
}
public TestTable() {
try {
Class.forName("org.h2.Driver");
String url = "jdbc:h2:mem:InMemoryTest";
con = DriverManager.getConnection(url);
createShoppingListTable();
fillShoppingListTable();
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
} catch (ClassNotFoundException | SQLException exp) {
exp.printStackTrace();
}
}
protected void createShoppingListTable() throws SQLException {
String query = "create table shoppingList (id bigint identity, item varchar(255), quantity int)";
try (Statement stmt = con.createStatement()) {
stmt.execute(query);
}
}
protected void fillShoppingListTable() throws SQLException {
String[] items = {"Bananas", "Apples", "Grapes", "Pears", "Oranges"};
Random rnd = new Random();
try (PreparedStatement ps = con.prepareStatement("insert into shoppingList (item, quantity) values (?, ?)")) {
for (String item : items) {
ps.setString(1, item);
ps.setInt(2, rnd.nextInt(100));
ps.addBatch();
}
ps.executeBatch();
}
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
TestTableModel model = new TestTableModel();
JTable table = new JTable(model);
add(new JScrollPane(table));
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
model.refresh();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
}
}
public class TestTableModel extends AbstractTableModel {
private List<ShoppingList> shoppingList = new ArrayList<>(25);
private List<String> columnNames = new ArrayList<>(25);
#Override
public int getRowCount() {
return shoppingList.size();
}
#Override
public int getColumnCount() {
return columnNames.size();
}
#Override
public String getColumnName(int column) {
return columnNames.get(column);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
ShoppingList rowValue = shoppingList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = rowValue.getId();
break;
case 1:
value = rowValue.getItem();
break;
case 2:
value = rowValue.getQuanity();
break;
}
return value;
}
public void refresh() throws SQLException {
List<String> values = new ArrayList<>(25);
try (PreparedStatement ps = con.prepareStatement("select * from shoppingList")) {
try (ResultSet rs = ps.executeQuery()) {
ResultSetMetaData md = rs.getMetaData();
for (int col = 0; col < md.getColumnCount(); col++) {
values.add(md.getColumnName(col + 1));
}
while (rs.next()) {
ShoppingList list = new ShoppingList(rs.getLong(1), rs.getString(2), rs.getInt(3));
shoppingList.add(list);
}
}
} finally {
if (columnNames.size() != values.size()) {
columnNames = values;
fireTableStructureChanged();
} else {
fireTableDataChanged();
}
}
}
public class ShoppingList {
private long id;
private String item;
private int quanity;
public ShoppingList(long id, String item, int quanity) {
this.id = id;
this.item = item;
this.quanity = quanity;
}
public long getId() {
return id;
}
public String getItem() {
return item;
}
public int getQuanity() {
return quanity;
}
}
}
}

How do i get the id of the cell click using JTable?

I am using a JTable to display data from my database. What I want to happen is that when a row is clicked it opens another window.
My Code
Connection to the database
public class JFrametest extends javax.swing.JFrame {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to Java Derby database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("EmailsDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "student", "student");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
out.println(cnfe);
} catch (SQLException sqle) {
out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
Displaying Data from the database
try {
String query = "select * from messages";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e) {
e.printStackTrace();
}
As anyone got any ideas on what i can do? is this possible?
You could use a mouseClicked Action Listener to do this.
You can use MouseListener for that, here is simple example:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestFrame extends JFrame {
public static void main(String... s) {
new TestFrame();
}
private JTable t;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
DefaultTableModel model = new DefaultTableModel(0,2);
for(int i=0;i<10;i++){
model.addRow(new Object[]{i,"other info "+i});
}
model.setColumnIdentifiers(new Object[]{"id","info"});
t = new JTable(model);
t.addMouseListener(getListener());
add(new JScrollPane(t));
}
protected void showDialog(int rowAtPoint) {
Object valueAt = t.getValueAt(rowAtPoint, 0);
// other operations
JDialog d = new JDialog();
d.setTitle("id="+valueAt);
d.setModal(true);
d.setAlwaysOnTop(true);
d.setLocationRelativeTo(null);
d.pack();
d.setVisible(true);
}
private MouseListener getListener() {
return new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getClickCount() >= 1){
int rowAtPoint = t.rowAtPoint(e.getPoint());
if(rowAtPoint != -1)
showDialog(rowAtPoint);
}
}
};
}
}

Categories