JTable Headers not Showing using any methods - java

I have tried almost every method to get table headers but nothing is working.
Here is the code:
package co.za.gecko.inked.crm;
import java.awt.EventQueue;
import java.awt.ScrollPane;
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 javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
public class Welcome extends JFrame {
private JPanel contentPane;
private JTable table;
static Object[][] databaseInfo;
static Object[] columns = {"first name", "last name", "cellphone", "time", "station"};
static ResultSet rows;
static ResultSetMetaData metaData;
static DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns) {
// public Class getColumnClass(int column){
// Class returnValue;
// if((column >= 0) && (column < getColumnCount())){
// returnValue = getValueAt(0, column).getClass();
// } else {
// returnValue = Object.class;
// }
// return returnValue;
// }
};
private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Welcome frame = new Welcome();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Welcome() {
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 1024, 768);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
deleteAllRows(dTableModel);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
Statement sqlState = conn.createStatement();
String selectStuff = "SELECT `first_name`, `last_name`, `cellphone`, `time` FROM volunteers";
rows = sqlState.executeQuery(selectStuff);
Object[] tempRow;
while(rows.next()){
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getString(3), rows.getString(4)};
dTableModel.addRow(tempRow);
}
// get column name ?
// metaData = rows.getMetaData();
// int numOfCol = metaData.getColumnCount();
//
// columns = new String[numOfCol];
//
// for(int i=1; i<= numOfCol; i++){
// columns[i] = metaData.getColumnName(i);
// }
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
} catch (SQLException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
}
table_1 = new JTable();
table_1.setModel(dTableModel);
table_1.setBounds(10, 11, 988, 707);
contentPane.add(table_1);
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(0, 0, 1008, 729);
contentPane.add(scrollPane);
}
public static void deleteAllRows(final DefaultTableModel model) {
for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
model.removeRow(i);
}
}
}
I have tried using table_1.getTableHeader();, .add(new scrollpane(table_1.getTableHeader()); and more. any help would be greatly appreciated.
I got the code (the pulling from the database to the dTableModel from youtube tutorials.

you would need to:
put JTable to JScrollPane e.g. JScrollPane scrollPane = new JScrollPane(table); (standard way)
add separate JTable to JFrame.CENTER area and separeate JTableHeader e.g. JTable.getTableHeader() to JFrame.NORTH area

Related

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.

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);
}
}

get table names from DB and parse it to JCombobox and then when a tablename is select it should display the table info in the JTable

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.

getSelectedRow() returns -1 after loading new data to existing JTable

I'm writing a simple MySQL editor. My problem is that after I select from the combobox a new table from the database and load it and then select a row and try to delete it, getSelectedRow() returns -1 and generates an exception, but that doesn't happen when I delete a row from the table that is loaded at the start of my program.
Here's the crucial code parts from 2 files (in the same code quote):
package omnisql;
import java.sql.*;
import java.util.*;
public class getData
{
static Connect c = new Connect();
static GUI g = new GUI();
static ResultSet result;
public static Vector<Vector<String>> data = new Vector<Vector<String>>();
public static String table="pracownicy";
public static Vector <String> d;
public static List <String> id;
void getData() throws SQLException
{
result=c.stmt.executeQuery("select * from "+table);
id = new ArrayList<String>();
while(result.next())
{
d=new Vector<String>();
id.add(result.getString("id"));
d.add(result.getString("id"));
d.add(result.getString("Nazwisko"));
d.add(result.getString("Imię"));
d.add(result.getString("Płeć"));
d.add(result.getString("Ulica"));
d.add(result.getString("Miejscowość"));
d.add(result.getString("Kod_pocztowy"));
d.add(result.getString("Województwo"));
d.add(result.getString("Telefon"));
data.add(d);
}
}
}
package omnisql;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.event.*;
public class GUI extends JFrame implements ActionListener, TableModelListener
{
static Connect c = new Connect();
static getData gd = new getData();
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER,10,5));
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JLabel typbazy = new JLabel("Typ bazy: ");
JLabel wybtab = new JLabel("Wybierz tabelę: ");
JRadioButton postgre = new JRadioButton("PostgreSQL");
JRadioButton mysql = new JRadioButton("MySQL");
JRadioButton sqlite = new JRadioButton("SQLite");
ButtonGroup grupa = new ButtonGroup();
public static JComboBox tabela = new JComboBox();
JButton addrec = new JButton("Dodaj rekord");
JButton delrec = new JButton("Usuń rekord");
JButton reftab = new JButton("Odśwież tabelę");
JTable table;
public static DefaultTableModel model;
TableColumn column;
Vector<String> headers = new Vector<String>();
JScrollPane scroll;
static int rownumber,addrow,delrow,updaterow;
PreparedStatement pst;
String value="";
public static int height,i,firstrow=0, klick=1;
public GUI()
{
panel.add(typbazy);
grupa.add(postgre);
panel.add(postgre);
postgre.addActionListener(this);
grupa.add(mysql);
panel.add(mysql);
mysql.setSelected(rootPaneCheckingEnabled);
mysql.addActionListener(this);
grupa.add(sqlite);
panel.add(sqlite);
sqlite.addActionListener(this);
panel1.add(wybtab);
panel1.add(tabela);
tabela.setPreferredSize(new Dimension(120,20));
tabela.setBackground(Color.white);
tabela.removeAllItems();
tabela.addItem(" ");
tabela.addItem("Pracownicy");
tabela.addItem("Pracownicy 2");
tabela.setSelectedIndex(0);
tabela.addActionListener(this);
headers.add("ID");
headers.add("Nazwisko");
headers.add("Imię");
headers.add("Płeć");
headers.add("Ulica");
headers.add("Miejscowość");
headers.add("Kod_pocztowy");
headers.add("Województwo");
headers.add("Telefon");
model = new DefaultTableModel(gd.data, headers);
table = new JTable(model);
table.setRowSelectionAllowed(true);
table.getModel().addTableModelListener(this);
table.setPreferredScrollableViewportSize(new Dimension(740,159));
column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(20);
column = table.getColumnModel().getColumn(1);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(2);
column.setPreferredWidth(70);
column = table.getColumnModel().getColumn(3);
column.setPreferredWidth(70);
column = table.getColumnModel().getColumn(4);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(5);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(6);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(7);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(8);
column.setPreferredWidth(80);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel3.add(addrec);
addrec.addActionListener(this);
panel3.add(delrec);
delrec.addActionListener(this);
panel3.add(reftab);
reftab.addActionListener(this);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(panel);
getContentPane().add(panel1);
getContentPane().add(panel2);
getContentPane().add(panel3);
}
void initGUI()
{
setSize(800,340);
setTitle("OmniSQL 1.0");
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void tableChanged(TableModelEvent e)
{
rownumber = table.getSelectedRow();
if (rownumber==-1) rownumber=0;
updaterow = Integer.parseInt(gd.id.get(rownumber));
switch (e.getType())
{
case TableModelEvent.UPDATE:
table.getRowCount();
value=table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString();
try
{
pst = c.con.prepareStatement("UPDATE "+gd.table+" SET "+table.getColumnName(table.getSelectedColumn())+" = '"+value+"' where id = "+updaterow+";");
pst.executeUpdate();
}
catch (SQLException err)
{
}
break;
}
}
public void actionPerformed(ActionEvent e)
{
/*if (e.getActionCommand().equals("MySQL"))
{
try
{
c.con.close();
c.connect("jdbc:mysql://localhost:3306/omnisql","root","sqlek","com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException er)
{
}
catch(SQLException err)
{
}
}*/
if (tabela.getSelectedItem()=="Pracownicy")
{
gd.table="pracownicy";
try
{
model.setRowCount(0);
table.removeAll();
gd.getData();
}
catch (SQLException er)
{
}
}
if (tabela.getSelectedItem()=="Pracownicy 2")
{
gd.table="pracownicy2";
try
{
model.setRowCount(0);
gd.getData();
table.revalidate();
}
catch (SQLException er)
{
}
}
/*if(postgre.isSelected())
{
tabela.removeAllItems();
tabela.addItem("Adresy");
tabela.addItem("Adresy 2");
tabela.setSelectedIndex(0);
}
*/
/*if(mysql.isSelected())
{
tabela.removeAllItems();
tabela.addItem(" ");
tabela.addItem("Pracownicy");
tabela.addItem("Pracownicy 2");
}*/
/*
if(sqlite.isSelected())
{
tabela.removeAllItems();
tabela.addItem("Zakłady");
tabela.addItem("Zakłady 2");
tabela.setSelectedIndex(0);
}*/
if (e.getActionCommand().equals("Dodaj rekord"))
{
model.setRowCount(gd.id.size());
rownumber = model.getRowCount()-1;
if(rownumber==-1 && gd.id.size()==0)
{
rownumber=0;
gd.id.add(0, "1");
addrow=Integer.parseInt(gd.id.get(rownumber));
}
else
{
addrow=Integer.parseInt(gd.id.get(rownumber));
addrow++;
}
try
{
pst = c.con.prepareStatement("INSERT INTO "+gd.table+" (id) VALUES("+addrow+")");
pst.executeUpdate();
model.setRowCount(0);
gd.getData();
height = (int)table.getPreferredSize().getHeight();
table.scrollRectToVisible(new Rectangle(0,height,10,10));
}
catch (SQLException exc)
{
}
}
rownumber=table.getSelectedRow();
if (e.getActionCommand().equals("Usuń rekord"))
{
try
{
model.setRowCount(gd.id.size());
System.out.println(rownumber);
delrow = Integer.parseInt(gd.id.get(rownumber));
pst = c.con.prepareStatement("DELETE from "+gd.table+" where id="+delrow);
pst.executeUpdate();
model.setRowCount(0);
gd.getData();
}
catch (SQLException exc)
{
}
}
if (e.getActionCommand().equals("Odśwież tabelę"))
{
try
{
model.setRowCount(0);
gd.getData();
}
catch (SQLException exc)
{
}
}
}
}
I will be really grateful for any help with this problem.
If getSelectedRow() returns -1 that means that nothing is selected.

JTable getSelectedRow does not return the selected row index

I try to get data in the row that is selected but getSelectedRow() doesn't work. Actually, I used that method in the other class, but it works in there. When I try to print the row index; the prompt shows -1; as not selected.
I tried most of solutions that are on the internet but they didn't solve my solutions.
public Canteen() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
this.setTitle( "CANTEEN" );
jScrollPane1.setBounds(new Rectangle(0, 0, 230, 235));
jButton1.setText("REFRESH");
jButton1.setBounds(new Rectangle(0, 235, 100, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jButton2.setText("CLOSE");
jButton2.setBounds(new Rectangle(120, 235, 110, 20));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
jTable1 = new JTable (model);
String header [] = {"CUSTOMER", "PRODUCT", "QUANTITY","ORDER NO"};
for (int i = 0; i < 4; i++){
model.addColumn(header[i]);
}
//refresh every 1 minute
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
model.setRowCount(0);
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,username, password);
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT USER_NAME, QUANTITY, PRD_NAME, ORDER_NUMBER FROM ORDERS ORDER BY ORDER_NUMBER DESC");
int count = rs.getRow();
String user [] = new String [count];
int i = 0;
while (rs.next()){
String name = rs.getString(1);
String prdName = rs.getString(3);
int number = rs.getInt(2);
int orderNumber = rs.getInt(4);
model.insertRow(i,new Object []{name,prdName,number, orderNumber});
}
conn.close();
}
catch (ClassNotFoundException s) {
System.out.println("Couldn't find the database driver");
System.out.println(s);
}
catch (SQLException s) {
System.out.println("Couldn't connect to the database\n" +s);
}
}
},0, 60000);
}
private void jButton1_actionPerformed(ActionEvent e) {
//set from row 0 for refresh
model.setRowCount(0);
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,username, password);
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT USER_NAME, QUANTITY, PRD_NAME FROM ORDERS ORDER BY ORDER_NUMBER DESC");
int count = rs.getRow();
String user [] = new String [count];
int i = 0;
while (rs.next()){
String name = rs.getString(1);
String prdName = rs.getString(3);
int number = rs.getInt(2);
model.insertRow(i,new Object []{name,prdName,number});
}
conn.close();
}
catch (ClassNotFoundException s) {
System.out.println("Couldn't find the database driver");
System.out.println(s);
}
catch (SQLException s) {
System.out.println("Couldn't connect to the database\n" +s);
}
}
private void jButton2_actionPerformed(ActionEvent e) {
System.out.println(jTable1.getSelectedRow());
}
}
Look to your code
private void jbInit() throws Exception {
...
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
jTable1 = new JTable (model);
...
You add jTable1 to the JScrollPane at first and only then you create jTable1. It's incorrect way. jTable1 variable doen't linked now with table you place at the form. I think it's cause of your problem.
Move creation of the jTable1 before adding in into JScrollPane.
...
jTable1 = new JTable (model);
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
...
As your other example shows, getSelectedRow() does work, so you're going to have to debug your code. Comparison with the sscce below may suggest way forward. Both the ActionListener and the ListSelectionListener show the selected row.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
/**
* #see http://stackoverflow.com/q/12301923/230513
*/
public class TableSelection extends JPanel {
private static final String SHOW = "Show";
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
private JButton button = new JButton(new AbstractAction(SHOW) {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(table.getSelectedRow());
}
});
public TableSelection() {
model.addColumn("Column");
for (int i = 0; i < 16; i++) {
model.addRow(new Object[]{i});
}
table.setPreferredScrollableViewportSize(new Dimension(160, 100));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
button.setText(SHOW + " " + table.getSelectedRow());
}
}
});
this.add(new JScrollPane(table));
table.setRowSelectionInterval(3, 3);
}
private void display() {
JFrame f = new JFrame("TableSelection");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this, BorderLayout.CENTER);
f.add(button, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TableSelection().display();
}
});
}
}

Categories