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.
Related
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.
The only thing remotely similar to my issue that I could find was this, however his problem seemed to be from a user error.
Reset cursor position after ResultSet updateRow
My problem is the following: After updating a row I am not able to access any other rows in my ResultSet. The update itself works fine, but if I want to continue I have to restart the application.
Here's the code:
package database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Gui extends MyDB {
JFrame f;
JLabel FName;
JLabel LName;
JLabel Age;
JTextField t;
JTextField t2;
JTextField t3;
JButton next = new JButton("next");
JButton update = new JButton("Update");
public Gui() {
frame();
start();
btnAction();
}
public void frame() {
f = new JFrame();
f.setVisible(true);
f.setSize(680, 480);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FName = new JLabel("Name");
LName = new JLabel("Anrede");
Age = new JLabel("age");
t = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
JPanel p = new JPanel();
p.add(FName);
p.add(t);
p.add(LName);
p.add(t2);
p.add(Age);
p.add(t3);
p.add(b1);
p.add(update);
public void btnAction() {
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String FName = t.getText();
String LName = t2.getText();
String Age = t3.getText();
try {
System.out.println(rs.getRow());
rs.updateString("FName", FName);
rs.updateString("LName", LName);
rs.updateString("Age", Age);
rs.updateRow();
//System.out.println(rs.getString("FName"));
System.out.println(rs.getRow());
JOptionPane.showMessageDialog(null, "Record updated ");
} catch (Exception ex) {
System.out.println("no");
}
}
});
}
public void start() {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
}
Also:
package database;
import java.sql.*;
public class MyDB {
Connection con;
Statement st;
ResultSet rs;
public MyDB() {
connect();
}
public void connect() {
try {
String db = "jdbc:ucanaccess://Datenbank1.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select * from Tabelle1";
rs = st.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace(System.out);
}
}
public static void main(String[] args) {
new Gui();
}
}
Output of System.out.println(rs.getRow()); is '0'.
If I want to click on the 'next' button after updating, the message "no next records" is displayed.
I have tried using rs.first(), rs.beforeFirst() and rs.isBeforeFirst(), none of which have worked.
If it helps, I am following this tutorial, which does not run into the same problem:
https://www.youtube.com/watch?v=NPV2o6YjP10
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);
}
}
};
}
}
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.
I need help with retrieving tableNames from my database and then parse it to JCombobox and the when the tableName is click the sql statement will be performed and then display the table in the JTable.
My problem is how to code the selectedItem so that it will execute the query and display IT on the JTable
Here is my gui.java file
package Assignment3.Live;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;
;
/**
* #author jmickey
*
*/
public class GUI extends JFrame {
// Variables
public Main main;
DBCon db;
MakeTable make;
private JFrame frame = new JFrame();
private JPanel pNorth, pChooser, pdp, pRC, pSCR, pTab, pSouth, pBtn;
public ResultSet rseTo = null;// result set
public PreparedStatement pst = null;
private ResultSetMetaData meta = null;
String tableNamesnow = "";
private JMenuBar jMenuBar;
private JMenu file, help;
private JComboBox<String> jcmb = new JComboBox<String>();
ComboBoxModel<?> giveMeTableName = (ComboBoxModel<?>) jcmb
.getSelectedItem();
private JTable jT = new JTable();
private JTextArea text;
private JButton search, clear, displayRow, deletRow, addRow, query, save,
restore;
private JCheckBox rowS = new JCheckBox("Select by Rows", true);
private JCheckBox colS = new JCheckBox("Selcet by Column", false);
/*
* private String[] columnNames = {}; private Object [][] rowData = {};
*/
public GUI() throws SQLException {
GUInterface();
getTableNames();
arrayOfTable();
}
public void GUInterface() {// constructor
// Menubar
setLayout(new BorderLayout(5, 10));
jcmb.setSelectedItem("");
jMenuBar = new JMenuBar();
file = new JMenu("File");
file.add(new JMenuItem("Start"));
file.add(new JMenuItem("Exit"));
help = new JMenu("Help");
help.add(new JMenuItem("Help"));
jMenuBar.add(file);
jMenuBar.add(help);
// Button
save = new JButton("Save");
clear = new JButton("Clear");
restore = new JButton("Restore");
displayRow = new JButton("Display Row");
deletRow = new JButton("Delet Row");
addRow = new JButton("Add New Row");
query = new JButton("QUERY");
// choose table panel = 1
pChooser = new JPanel();
pChooser.setLayout(new BorderLayout(5, 0));
pChooser.setBorder(new TitledBorder("Tables"));
pChooser.add(new JLabel("Select a table: "), BorderLayout.WEST);
pChooser.add(jcmb, BorderLayout.CENTER);
// Row/Column selection Panel = 2
pRC = new JPanel();
pRC.setLayout(new FlowLayout(FlowLayout.LEFT));
pRC.add(rowS);
pRC.add(colS);
// noth panel holds (pChooser & pRC)
pNorth = new JPanel();
pNorth.setLayout(new GridLayout(2, 1));
pNorth.add(pChooser);
pNorth.add(pRC);
// JTable panel
pTab = new JPanel();
pTab.setLayout(new GridLayout(1, 1));
pTab.add(jT);
pTab.add(new JScrollPane(jT));
// display holds (pNorth & pTab)
pdp = new JPanel();
pdp.setLayout(new BorderLayout(2, 1));
pdp.add(pNorth, BorderLayout.NORTH);
pdp.add(pTab, BorderLayout.SOUTH);
// Save, Clear or restore Panel
pSCR = new JPanel();
pSCR.add(save);
pSCR.add(clear);
pSCR.add(restore);
// Button selection panel
pBtn = new JPanel();
pBtn.setLayout(new GridLayout(2, 2));
pBtn.add(displayRow);
pBtn.add(addRow);
pBtn.add(query);
pBtn.add(deletRow);
// South panel (pSCR & pBtn)
pSouth = new JPanel();
pSouth.setLayout(new BorderLayout(2, 1));
pSouth.add(pBtn, BorderLayout.SOUTH);
pSouth.add(pSCR, BorderLayout.CENTER);
// Table info
jT.setAutoResizeMode(jT.AUTO_RESIZE_OFF);
jT.setGridColor(Color.BLUE);
jT.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jT.setSelectionBackground(Color.BLUE);
jT.setSelectionForeground(Color.WHITE);
jT.setRowSelectionAllowed(true);
/*
* Task 1. change action to diplay row = create the 2.delete row
* 3.insert row
*/
frame.setJMenuBar(jMenuBar);
frame.add(pdp, BorderLayout.NORTH);
frame.add(pSouth, BorderLayout.SOUTH);
frame.setTitle("Walters SPJ Directory");
frame.setResizable(true);
frame.setSize(465, 648);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// display rows
displayRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the search button is clicked
if (e.getSource() == displayRow) {
jcmb.setSelectedItem(giveMeTableName);
for (int i = 0; i < jcmb.getSelectedIndex(); i++)
displayS();
}
}
});
// Checkbos ActionListener
rowS.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jT.setRowSelectionAllowed(rowS.isSelected());
}
});
colS.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jT.setRowSelectionAllowed(colS.isSelected());
}
});
// Clear ActionListener
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
TableModel myData = DbUtils.resultSetToTableModel(rseTo);
jT.tableChanged(null);
}
});
}
// get tableNames
public void getTableNames() throws SQLException {
rseTo = null;
java.sql.DatabaseMetaData meta = DBCon.con.getMetaData();
rseTo = meta.getTables(null, null, "%", new String[] { "TABLE" });
while (rseTo.next()) {
String nameOfTables = rseTo.getString(3);
String tableCatalog = rseTo.getString(1);
String tableSchema = rseTo.getString(2);
System.out.printf("%s - %s - %s%n", tableCatalog, tableSchema,
nameOfTables);
}
db.stm.close();
}
// get table name to JCombobox
public void arrayOfTable() throws SQLException {
rseTo = db.con.getMetaData().getTables(null, null, "%",
new String[] { "TABLE" });
while (rseTo.next()) {
String giveMeTableName = (rseTo.getString(3));
jcmb.addItem(giveMeTableName);
System.out.println(giveMeTableName);
}
jcmb.setBounds(130, 30, 190, 30);
jcmb.setEditable(false);
jcmb.getSelectedIndex();
return;
}
/*
* Table selection method
*/
public void displayS() {
try {
String sql = "SELECT DISTINCT * FROM " + giveMeTableName;
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
TableModel myData = DbUtils.resultSetToTableModel(rseTo);
jT.setModel(myData);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displayP() {
try {
String sql = "SELECT DISTINCT * FROM P";
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displayJ() {
try {
String sql = "SELECT DISTINCT * FROM " + make.tableName;
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displaySPJ() {
try {
String sql = "SELECT DISTINCT * FROM SPJ";
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
}
For tasks like this, you need to be aware that you're developing a new (simple) programming language. This means the input is no longer free form but has to obey certain rules. For example:
Table name: S
...
Table name:
P
is bad. The people editing the file should stick to one way to specify the table name; otherwise your parser will quickly get complex.
As a general guideline for tasks like this:
Read the input line by line.
Ignore empty lines
Trim lines to get rid of excessive whitespace
Use patterns like Table name: together with line.startsWith() to find out what the next "block" of your language means.
Read the values of each block and process then. line.split("\\s", -1) is your friend to split the input into words.
Getting it right will become easier when you create a few simple test cases and use unit tests to make sure your parser builds the correct data structures in memory.