How to auto load into Jtable, when frame/Jtable opens - java

Trying to pass an SQL query to a Jtable as the Frame/Jtable_1 loads.
looking into the forums and on the net I seem to end at WindowOpened event or some abstract example, which i have commented out.
I am new to Java and thought it may be Jtable setFocus event or on onload event etc but now struggling as i pick up knowledge, although a button Actionperformed event works a treat.
Any help would be appreciated.
Eclipse IDE Luna 4.4.1/ SQLite / Windows8.1
enter code here
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
import java.awt.event.ActionListener;
public class update extends JFrame {
private JPanel contentPane;
//private String x = Hardware.rowid;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
update frame = new update();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowOpened(WindowEvent e){
System.out.println("hello");
//Connection connection=null;
//connection=sqliteConnection.dbConnector(); //set new connection to sql
//String query="select id, Firstname, Surname, username, admin from users where id = "+ Hardware.rowid ; //set sql query statement to variable query
//PreparedStatement pst;
//try {
//pst=connection.prepareStatement(query);
// ResultSet rs=pst.executeQuery(); //pass to rs resultset and execute
//table_1.setModel(DbUtils.resultSetToTableModel(rs)); //pass data to table
//} catch (SQLException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
//}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection=null;
// WindowListener wl = new WindowListener(){
// public void windowOpened(WindowEvent e)
// {
// try
// {
// System.out.println (Hardware.rowid);
// }
// catch (FileNotFoundException ex) {
// System.out.println ("didnt work");
// }
// }
// public void windowClosing(WindowEvent e) {}
// public void windowClosed(WindowEvent e) {}
// public void windowIconified(WindowEvent e) {}
// public void windowDeiconified(WindowEvent e) {}
// public void windowActivated(WindowEvent e) {}
// public void windowDeactivated(WindowEvent e) {}
//};
//super.getFrame().addWindowListener(wl);
//}
private JTable table;
//private static JTable table_1;
private JTable table_1;
/**
* Create the frame.
*/
public update() {
connection=sqliteConnection.dbConnector(); //set new connection to sql
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btn_update = new JButton("Update Database");
btn_update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query="select id, Firstname, Surname, username, admin from users where id = "+ Hardware.rowid ; //set sql query statement to variable query
PreparedStatement pst=connection.prepareStatement(query); //passs data to pst
ResultSet rs=pst.executeQuery(); //pass to rs resultset and execute
table_1.setModel(DbUtils.resultSetToTableModel(rs)); //pass data to table
System.out.println (Hardware.rowid);
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn_update.setBounds(270, 219, 154, 31);
contentPane.add(btn_update);
JLabel lbl_update = new JLabel("Selection HISTORY");
lbl_update.setBounds(142, 11, 160, 14);
contentPane.add(lbl_update);
table_1 = new JTable();
table_1.setBounds(20, 36, 404, 175);
contentPane.add(table_1);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(246, 102, 2, 2);
contentPane.add(scrollPane);
}
}
Thanks in advance.

Related

Why the preparedStatement is not working in jdbc?

I have created a table called user in mysql. Then I create a simple j frame with having a text field and a button. The button will add the name in the DB after pressing the button. But is showing an error at insertData.InsertData$2.actionPerformed(InsertData.java:86) means there are some issue with prepared statement. I have tried without prepared statement but problem is not solved.
Most important my table having 4 columns called (name, id, Email,Phone)
package insertData;
import java.awt.EventQueue;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.mysql.cj.xdevapi.Statement;
import com.sun.jdi.connect.spi.Connection;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class InsertData {
private JFrame frame;
private JTextField textField;
Connection connection;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InsertData window = new InsertData();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public InsertData() {
initialize();
createConnection();
}
/**
* Initialize the contents of the frame.
*/
public void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");//load driver
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/shykat_db","root","root"); //Establish connection
System.out.println("sucess");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 25, 174, 44);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Submit\r\n");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String name=textField.getText();
String drop="insert into user values(?) ";
java.sql.PreparedStatement ps= ((java.sql.Connection) connection).prepareStatement(drop);
System.out.println(ps);
ps.setString(1, name);
ps.executeUpdate();
//ResultSet rs = ps.executeQuery();
//System.out.println(rs);
//java.sql.Statement stm=((java.sql.Connection) connection).createStatement();
//String drop="insert into user values(' "+name+" ')";
//stm.execute(drop);
//stm.close();
//int count=ps.executeUpdate();
//System.out.println(count+"-----Data updated");
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(313, 26, 89, 44);
frame.getContentPane().add(btnNewButton);
}
}
If you want to insert into only some columns of a multi column table, you must declare which columns you want to insert into after the table name
INSERT INTO t(column,list,goes,here)
VALUES(samenumber,ofvalues,asthere,arecolumns)
Your user table has at least 4 columns, you cannot say insert into user values(?) because your database will not be prepared to guess which column the value should go in. Try insert into user(name) values(?)

Clicking on button doesn't retrieve data from database

So i'm trying to make a frame where it shows a list of every item in my database after you click on the button, but actually when i click on it nothing shows.
public ArrayList show(JTextArea tData) {
ArrayList<Book> books=new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
polaczenie =DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=master",
"sa", "student");
try(Statement stmt = connection.createStatement();) {
ResultSet rs = stmt.executeQuery("{call dbo.showBook}");
while (rs.next()) {
books.add(new Book(
rs.getString("bookNumber"),
rs.getString("title"),
rs.getString("author"),
rs.getString("publicationYear"),
rs.getString("publisher"))
);
}
}
}
catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Error "+ex.getMessage(), "Error", 0);
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error "+ex.getMessage(), "Error", 0);
}
return books;
}
private void bShowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DataBook db=new DataBook();
db.show(tData);
}
Your show method will return a ArrayList<Book>
So:
Have you processed this to display data from the list?
Does your database have data yet ?
"Sorry I can't add comment because my reputation < 50 "
Hope it helps you.
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class App extends JFrame {
JPanel contentPane;
JButton action;
JList<Book> listBooks;
public App() {
this.prepareGUI();
}
public void prepareGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200, 200);
contentPane = new JPanel();
this.setContentPane(contentPane);
action = new JButton("Action");
contentPane.add(action);
listBooks = new JList<Book>();
contentPane.add(listBooks);
action.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Data
Book[] books = new Book[5];
for (int i = 0; i < books.length; i++) {
books[i] = new Book("book " + i, "##");
}
listBooks.setListData(books);
}
});
}
public static void main(String[] args) {
App app = new App();
app.setVisible(true);
}
}
Hope this help you!!!

JTable in GroupLayout not populating from database [duplicate]

I have a text box that allows users to put in select type queries with the idea that when they click a button the result of the select statement will be shown in a JTable. I don't get any errors but also nothing is shown in the textPane when my button is pressed. The I have is below:
public class Console {
String myquery="";
private JFrame frame;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Console window = new Console();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Console() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 950, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textAreaQuery = new JTextArea();
JTable table_ResQues = new JTable();
JButton btnNewButton = new JButton("Execute");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/Physiology.mdb;";
System.out.println("Connection To Database Made");
Connection conn = null;
try {
conn = DriverManager.getConnection(connectDB);
} catch (SQLException e1) {
e1.printStackTrace();
}
Statement st = null;
try {
st = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
myquery=textAreaQuery.getText();
String stg2 = "Select "+myquery;
ResultSet rs = null;
try {
rs = st.executeQuery(stg2);
table_ResQues.setModel(getDataFromDatabase);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
and the code to build the model:
public TableModel getDataFromDatabase()
{
DefaultTableModel model = new DefaultTableModel(5, 5);
model.setValueAt("Hard", 0, 0);
model.setValueAt("Coded", 1, 1);
model.setValueAt("Data", 2, 2);
return model;
}
}
Ive removed the local variable
No, you removed the instance variable. Did you actually try this with your real code or just edit the question?
I have no idea how to provide a testable database for this question
I already suggested you create a method to simplify the logic. Somethng like:
public TableModel getDataFromDatabase()
{
DefaultTableModel model = new DefaultTableModel(5, 5);
model.setValueAt("Hard", 0, 0);
model.setValueAt("Coded", 1, 1);
model.setValueAt("Data", 2, 2);
return model;
}
Then in your ActionListener you simple do something like:
table_ResQues.setModel( getDataFromDataBase() );
Once you get this basic logic working you move the SQL logic into the getDataFromDatabase() method.
So now you create your SSCCE showing how you actually create the frame and add the components to the frame. The code should be compilable and executable.
Edit:
You have been told to display a table is a scrollpane. It is no extra effort to do this. Instead of using:
panel.add(table);
you use:
panel.add( new JScrollPane( table ) );
I would also suggest that to test your layout you can use code like the following to display a dummy table:
//JTable table_ResQues = new JTable();
JTable table_ResQues = new JTable(5,5);
Then when you use the setModel() method, only the data is affected, not the layout of the table.
I cant help but feel this is a fireTableDataChanged problem though.
I doubt it. That method is invoked by the TableModel when you change the data in the model. It is not used in this case because you are using the setModel(...) method. This will cause the table to repaint() itself automatically.
Here is my solution to your problem. I have retained your variable names though not all of them followed Java conventions. I think all you wanted was that the user would type SQL query in JTextArea and see the result of the query in a JTable.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
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 javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
public class Console {
private JFrame frame;
private JTextArea textAreaQuery;
private JTable table_ResQues;
private JButton btnNewButton;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Console window = new Console();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Console() {
initialize();
}
private void initialize() {
frame = new JFrame("SQL Query");
frame.setBounds(100, 100, 950, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textAreaQuery = new JTextArea();
btnNewButton = new JButton("Execute");
table_ResQues = new JTable();
JPanel queryPanel=new JPanel(new BorderLayout()); // holds JTextArea and JButton
queryPanel.add(new JScrollPane(textAreaQuery), BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
btnPanel.add(btnNewButton);
queryPanel.add(btnPanel, BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, queryPanel,
new JScrollPane(table_ResQues));
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(150);
frame.setContentPane(splitPane);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/*try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
}*/
String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/Physiology.mdb;";
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection(connectDB);
//conn = DriverManager.getConnection("jdbc:mysql://localhost/cwcx", "root", "admin");// MySQL connection
st = conn.createStatement();
System.out.println("Connection To Database Made");
} catch (SQLException e1) {
e1.printStackTrace();
}
String myquery = textAreaQuery.getText();
if(myquery.endsWith(";")){
myquery=myquery.substring(0, myquery.length()-1);
}
ResultSet rs = null;
try {
rs = st.executeQuery(myquery);
// extract column information
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List<String> columnData = new ArrayList<String>(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnData.add(rsmd.getColumnName(i));
}
// sql result data
List<List<Object>> rowData = new ArrayList<List<Object>>();
while (rs.next()) {
List<Object> row = new ArrayList<Object>(columnCount);
for (int i = 0; i < columnCount; i++) {
row.add(rs.getObject(i + 1));
}
rowData.add(row);
}
table_ResQues.setModel(new ListTableModel(rowData, columnData));
} catch (SQLException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
});
}
// this table model is created from two dimensional List rowData and single dimensional List columnData
private static class ListTableModel extends AbstractTableModel{
private static final long serialVersionUID = 1L;
private List<List<Object>> rowData;
private List<String> columnData;
public ListTableModel(List<List<Object>> rowData, List<String> columnData) {
this.rowData = rowData;
this.columnData = columnData;
}
#Override
public int getRowCount() {
return rowData.size();
}
#Override
public int getColumnCount() {
return columnData.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rowData.get(rowIndex).get(columnIndex);
}
#Override
public String getColumnName(int column) {
return columnData.get(column);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Object obj=rowData.get(0).get(columnIndex);
return obj.getClass();
}
}
}
On my system, I have tested it with MySQL database. But I have commented out that part. You may try this on your system without any modification. Please do tell me whether you wanted to achieve this solution or not.

Load data to a table

private void update_table(){
try{
DefaultTableModel df=(DefaultTableModel)jTable1.getModel();
Conn c=new Conn();
Statement s=c.createConn().createStatement();
// df.getDataVector().removeAllElements();
String sql="Select * from leave_taken";
ResultSet rs=s.executeQuery(sql);
while(rs.next()){
Vector v=new Vector();
df.addRow(v);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (Exception e) {
e.printStackTrace();
}
This is what i wrote. i want to lad data to the table by this method. but it loads only the table headings. how can i load table data to the table? Is there some thing need to add to this code?
Your v variable happens to be empty vector when you do df.addRow(v). Seems like you don't need df in your code.
Full example working with data
package javaapplication2;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class JavaApplication2
{
public static void main(String[] args)
{
Runnable r = new Runnable()
{
#Override
public void run()
{
JFrame f = new JFrame();
JPanel p = new JPanel();
f.setContentPane(p);
f.setPreferredSize(new Dimension(600, 600));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable t = new JTable();
p.add(new JScrollPane(t), BorderLayout.CENTER);
JButton b = new JButton("Run");
p.add(b, BorderLayout.WEST);
b.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection c = DriverManager.getConnection("jdbc:sqlserver://localhost;integratedSecurity=true;databaseName=stackoverflow");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM leave_taken");
t.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (SQLException es)
{
es.printStackTrace();
}
catch (ClassNotFoundException ecn)
{
ecn.printStackTrace();
}
}
});
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
Result on application start.
Result after button "Run" pressed.

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