For some reason my JTable is not displaying it's column names?! I'm certain I've done everything correctly. I've literally copied this from a demonstration so I don't understand why it won't work.
Here is my code:
public class MemTableModel extends AbstractTableModel{
private ArrayList<member> members = new ArrayList<member>();
private String[] columnNames = {"ID", "Name", "Email", "Country", "Genre",
"Gender", "Description", "Type", "Limit", "Card No", "Expiry Date"};
public MemTableModel(){
LoadTableFromDB();
}
public int getRowCount(){
return members.size();
}
public int getColumnCount(){
return columnNames.length;
}
public Object getValueAt(int row, int col){
//Get the row from the about get method
member f = members.get(row);
switch(col){
case 0: return f.getmembId();
case 1: return f.getname();
case 2: return f.getemail();
case 3: return f.getcountry();
case 4: return f.getfavGenre();
case 5: return f.getgender();
case 6: return f.getdescription();
case 7: return f.getmemberType();
case 8: return f.getsongLimit();
case 9: return f.getcard_no();
case 10: return f.getexpiry_date();
}
return null;
}
public String getColumnName(int col){
return columnNames[col];
}
public member getRow(int row){
member c = members.get(row);
return c;
}
public Connection getConnection(){
Connection conDB = null;
/****** DEFAULT MYSQL DRIVERS **************************/
String url = connection.geturl();
String username = connection.getUsername();
String password = connection.getPassword();
try{
//load the MYSQL driver
Class.forName(connection.getDriver());
conDB = DriverManager.getConnection(url, username, password);
}
catch(Exception e){
}
return conDB;
}
//Load all DB values into ARRAY
public void LoadTableFromDB(){
Connection conDB = null;
Statement stmt = null;
ResultSet r = null;
try{
//Connection + Statement
conDB = getConnection();
stmt = conDB.createStatement();
//Queries
String sqlSelectAll = "SELECT * FROM members";
r = stmt.executeQuery(sqlSelectAll);
members.clear();
//Loop through the resultset
while(r.next()){
members.add(new member(r.getInt("membId"), r.getString("name"),
r.getString("email"), r.getString("country"), r.getString("favGenre"),
r.getString("gender"), r.getString("description"), r.getString("memberType"),
r.getString("songLimit"), r.getString("card_no"), r.getString("expiry_date")));
}
conDB.close(); // Close the DB connection
}//End of TRY
catch(Exception er){
System.out.println("Error was: " + er);
}
}
}
Here is how I've implemented the JTable:
public class ViewAll extends JFrame implements ActionListener{
//Jtextfields, buttons, labels
private JButton btnBack = new JButton("Back");
private static JLabel lblMembTitle = new JLabel("<html><h1>All Members</h1></html>");
private static JLabel lblPlayTitle = new JLabel("<html><h1>All Playlists</h1><br /></html>");
//Containers, Panels, Scrollpanes
private Container mainCon = this.getContentPane();
private static JPanel pnlTable = new JPanel(new BorderLayout());
//Jpanels - sections
private JPanel mainPanel = new JPanel();
private JPanel subPanel1 = new JPanel();
private JPanel subPanel2 = new JPanel();
private JPanel subPanel3 = new JPanel();
//Tables
private static JTable tblShowAllMemb = new JTable();
private static JTable tblShowAllPlay = new JTable();
JScrollPane scrollPane = new JScrollPane(mainPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public ViewAll(){
super("Search/Edit/Delete Members");
this.setBounds(400, 800, 854,400);
this.setVisible(true);
mainCon.add(scrollPane);
//Table Models:
MemTableModel tblMembers = new MemTableModel();
PlayTableModel tblPlaylist = new PlayTableModel();
//LAYOUT
/*By removing this the scrollpane works
^^mainPanel is already added to the scrollPane object above ^^
*/
// mainCon.add(mainPanel);
//Main Panel
mainPanel.setLayout(new BorderLayout());
mainPanel.add(BorderLayout.NORTH, subPanel1);
mainPanel.add(BorderLayout.CENTER, subPanel2);
//Panel1 - Member table + Back Button
subPanel1.setLayout(new BorderLayout());
subPanel1.add(BorderLayout.NORTH, btnBack);
subPanel1.add(BorderLayout.CENTER, lblMembTitle);
subPanel1.add(BorderLayout.SOUTH, tblShowAllMemb);
tblShowAllMemb.setModel(tblMembers);
btnBack.addActionListener(this);
//Panel2 - Playlist table
subPanel2.add(BorderLayout.NORTH, lblPlayTitle);
subPanel2.add(BorderLayout.CENTER, tblShowAllPlay);
tblShowAllPlay.setModel(tblPlaylist);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnBack){
this.dispose();
}
}
}
The likely issue is you've not wrapped the JTable, which represents your TableModel in a JScrollPane as demonstrated in How to Use Tables
By simply using something like...
add(new JScrollPane(new JTable(new MemTableModel())));
I can get:
See also How to Use Scroll Panes for more details
Updated based on updated code...
Not one of your tables is actually wrapped within it's own JScrollPane
// By the way, static here is very, very bad idea
private static JTable tblShowAllMemb = new JTable();
private static JTable tblShowAllPlay = new JTable();
JScrollPane scrollPane = new JScrollPane(mainPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public ViewAll(){
//....
//Table Models:
MemTableModel tblMembers = new MemTableModel();
PlayTableModel tblPlaylist = new PlayTableModel();
//...
subPanel1.add(BorderLayout.SOUTH, tblShowAllMemb);
//...
subPanel2.add(BorderLayout.CENTER, tblShowAllPlay);
You've just added the table by itself to some other container. Instead, consider using something like
//...
subPanel1.add(BorderLayout.SOUTH, new JScrollPane(tblShowAllMemb));
//...
subPanel2.add(BorderLayout.CENTER, new JScrollPane(tblShowAllPlay));
Related
public void GetUsersName(){
try
{
java.sql.Connection con = DriverManager.getConnection(url + dbName, userName, password);
java.sql.Statement s = con.createStatement();
ResultSet result = s.executeQuery("SELECT Username FROM tblcustomers ORDER BY UserID");
if(result != null){
while (result.next())
{
ListUserNames.usersJList.setListData(Username);
}
}
s.close();
con.close();
} catch (SQLException e)
{
System.out.println("Error: " + e);
}
Here my Code from the class where I make my JList Panel , which I then insert to another Class. I cans see my JScrollPane perfectly, the only problem is i can't insert the usernames into it, but I can see other values from a test array for example.
public class ListUserNames extends JPanel{
public static JList<String> usersJList;
public ListUserNames()
{
setLayout(new FlowLayout()) ;
usersJList =new JList<String>();
usersJList.setVisibleRowCount(10) ;
usersJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
// add a )Scroll Pane containing )List to frame
JScrollPane sp = new JScrollPane(usersJList);
sp.setSize(300, 400);
add(sp);
}
}
JList has no mehtod to add or remove an elment once it's initialized. Instead you can use a ListModel with the JList.
Example:
public class ListUserNames extends JPanel {
public static DefaultListModel<String> listModel = new DefaultListModel<>();
public ListUserNames() {
setLayout(new FlowLayout());
JList<String> usersJList = new JList<String>(listModel);
usersJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// add a )Scroll Pane containing )List to frame
JScrollPane sp = new JScrollPane(usersJList);
sp.setSize(300, 400);
add(sp);
}
}
and your fetch method:
public void getUsersName() throws SQLException {
java.sql.Connection con = DriverManager.getConnection(url + dbName, userName, password);
JList<String> list = new JList<>();
PreparedStatement ps = con.prepareStatement("SELECT Username FROM tblcustomers ORDER BY UserID");
ResultSet result = ps.executeQuery();
DefaultListModel<String> listModel = new DefaultListModel<>();
if (result != null) {
while (result.next())
{
ListUserNames.listModel.addElement(result.getString("Username"));
}
}
ps.close();
con.close();
}
You are using the static aceess to the list. ListUserNames.usersJList.setListData(Username);
That means "usersJList" might have not been initialized yet.
In your can , it was not.
2 solutions.
Solution 1
Initialize "usersJList" in ListUserNames.
such as public static
JList usersJList = new JList();
This is not a recommended way
Solution 2
The second solution make a method to initialize userJList
Code:
GetUsersName.java
public void GetUsersName(){
/*-----your other codes----*/
JList<String> usersJList = ListUserNames.getUsersJList();
if(result != null){
while (result.next())
{
usersJList.setListData(Username);
}
}
/*-----your other codes----*/
}
ListUserNames.java
public class ListUserNames extends JPanel{
private static JList<String> usersJList;
public static JList<String> getUsersJList(){
if (usersJList == null){
usersJList =new JList<String>();
}
return usersJList;
}
public ListUserNames(){
getUsersJList();
setLayout(new FlowLayout()) ;
usersJList.setVisibleRowCount(10) ;
usersJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
// add a )Scroll Pane containing )List to frame
JScrollPane sp = new JScrollPane(usersJList);
sp.setSize(300, 400);
add(sp);
}
}
Here what I am doing:
On clicking Search flight, the data comes from Database and display on another JFrame like this:
I want this data to be shown right below the searching panel instead of opening new frame. Something like this:
My codes are as follows:
listingFlight.java
public class listingFlight extends javax.swing.JPanel implements TableCellRenderer {
public listingFlight() {
initComponents();
}
#SuppressWarnings("unchecked")
//Netbeans autogenerated componnent code
#Override
public Component getTableCellRendererComponent(JTable jTable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.jLabel3.setText(jTable.getModel().getValueAt(row, column).toString()+" ("+jTable.getModel().getValueAt(row, column+1).toString()+")");
this.jLabel4.setText(jTable.getModel().getValueAt(row, column+2).toString()+" ("+jTable.getModel().getValueAt(row, column+3).toString()+")");
this.jLabel6.setText(jTable.getModel().getValueAt(row, column+9).toString());
this.jLabel8.setText(jTable.getModel().getValueAt(row, column+6).toString());
this.jLabel11.setText(jTable.getModel().getValueAt(row, column+8).toString());
this.jLabel12.setText(jTable.getModel().getValueAt(row, column+7).toString());
this.jLabel15.setText(jTable.getModel().getValueAt(row, column+4).toString());
this.jLabel16.setText(jTable.getModel().getValueAt(row, column+5).toString());
return this;
}
}
(on clicking button "Search Flight", i m performing this.)
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select s.airportName,s.cityName,d.airportName,d.cityName,f.srcTime,f.destTime,f.flightNumber,f.availability,f.price,a.airlineName,f.flightID from flights f inner join airlines a on(a.airlineID=f.flightName) inner join cityinfo s on(s.cityID=f.src) inner join cityinfo d on(d.cityID=f.dest) where f.src=" + jComboBox1.getSelectedIndex() + " and f.dest=" + jComboBox2.getSelectedIndex());
while (rs.next()) {
i++;
}
rs.beforeFirst();
data = new Object[i][11];
i = 0;
while (rs.next()) {
data[i][0] = rs.getString(1);
data[i][1] = rs.getString(2);
data[i][2] = rs.getString(3);
data[i][3] = rs.getString(4);
data[i][4] = rs.getString(5);
data[i][5] = rs.getString(6);
data[i][6] = rs.getString(7);
data[i][7] = rs.getString(8);
data[i][8] = rs.getString(9);
data[i][9] = rs.getString(10);
data[i][10] = rs.getString(11);
i++;
}
table = new JTable(data, columnNames) {
#SuppressWarnings("override")
public TableCellRenderer getCellRenderer(int row, int column) {
return new listingFlight();
}
};
showFrame(table);
table.setRowHeight(82);
conn.close();
}
For now showFrame() is :
private void showFrame(JTable table) {
JFrame f = new JFrame("Search Result");
f.setSize(800, 700);
f.add(new JScrollPane(table));
f.setVisible(true);
}
But i m trying to add jScrollPane to existing JPanel instead of creating new JFrame and displaying Data to it
private void showFrame(JTable table) {
this.jPanel1.add(new JScrollPane(table));
}
This showFrame is not adding JScrollPane to my existing jPanel1.
I am working on adapter classes.
I made JTable in an adapter class TabCl and called that JTable class TabCl in my parent class method guiInt() and adding it to container con.add() and its not letting it to do.
I am new to Java and don't have sound knowledge in Java. Please check the following code and give some help or something that can make it work.
My java version is 1.6.
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class PersonProject {
JFrame myFrame;
Container cont;
BorderLayout bl;
GroupLayout gl;
FlowLayout fl;
JTable tl;
JScrollPane jsp;
JPanel flPanel, glPanel, jTPane;
JLabel lId;
JTextField tId;
// Db variable Declaration
Connection dbCon;
String url;
String con;
String sql;
ResultSet rs;
ResultSetMetaData rsmd;
PreparedStatement pstmt;
Vector columnName, data, row;
int columnCount;
public PersonProject() {
guiInt();
}
public void guiInt() {
myFrame = new JFrame();
glPanel = new JPanel();
cont = new Container();
bl = new BorderLayout();
fl = new FlowLayout();
flPanel = new JPanel();
flPanel.setLayout(fl);
cont = myFrame.getContentPane();
cont.setLayout(bl);
gl = new GroupLayout(glPanel);
glPanel.setLayout(gl);
gl.setAutoCreateGaps(true);
gl.setAutoCreateContainerGaps(true);
lId = new JLabel("Id");
tId = new JTextField();
// /////////
GroupLayout.SequentialGroup hGroup = gl.createSequentialGroup();
hGroup.addGroup(gl.createParallelGroup().addComponent(lId));
hGroup.addGroup(gl.createParallelGroup().addComponent(tId));
gl.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = gl.createSequentialGroup();
vGroup.addGroup(gl.createParallelGroup(Alignment.BASELINE)
.addComponent(lId).addComponent(tId));
gl.setVerticalGroup(vGroup);
// ///////
TabCl tlb = new TabCl();// / class for making jatable
cont.add(flPanel, bl.NORTH);
cont.add(glPanel, bl.CENTER);
cont.add(tlb, bl.SOUTH);//// error at this point
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myFrame.setSize(600, 300);
}// end of method guiinit
private class TabCl {// start of adapter class for making jtable
public TabCl() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
url = "jdbc:odbc:personDSN";
dbCon = DriverManager.getConnection(url);
sql = "select * from emp";
pstmt = dbCon.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
rsmd = rs.getMetaData();
columnCount = rsmd.getColumnCount();
columnName = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnName.add(rsmd.getColumnName(i));
}// end of for loop
System.out.println(columnName.get(1));
data = new Vector();
row = new Vector();
while (rs.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(rs.getString(i));
}
data.add(row);
}// end of while loop
dbCon.close();
} catch (Exception ex) {
System.out.println(ex + ":Sql Exception at table level");
}
tl = new JTable(data, columnName);
jsp = new JScrollPane(tl);
jTPane = new JPanel();
tl.setPreferredScrollableViewportSize(new Dimension(500, 90));
tl.setVisible(true);
tl.setFillsViewportHeight(true);
jTPane.add(jsp);
}// end of method tabmethod
}// end of class TabCl
public static void main(String[] args) {
// TODO Auto-generated method stub
PersonProject perProj = new PersonProject();
}
}
TabCl implicitly extends Object, while add() expects a Component. Instead of this:
private class TabCl {…}
create a factory method that returns a JPanel like this:
private JPanel createTablePanel() {
…
jTPane.add(jsp);
return jTPane;
}// end of method createTablePanel
and use it like this:
JPanel tlb = createTablePanel();
cont.add(flPanel, bl.NORTH);
cont.add(glPanel, bl.CENTER);
cont.add(tlb, bl.SOUTH);//// error at this point
See also JDBCAdapter, cited here.
I've removed most of my GUI to keep the code short.
I have a buttongroup of 3 JRadioButtons to select the table schema i want to display in my JTable, which is contained in a JScrollPane
I have tried to use fireTableStructureChanged() andfireTableDataChanged() as well as JTable.repaint() to no avail. Can anyone help me?
Here is a simple example that runs a window with my configuration but does not update the table.
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel();
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
mainPanel.setSize(1260, 630);
mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
coursesBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.setOpaque(true);
tableRadioPanel.setBounds(0, 0, 150, 70);
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(160, 0, 1016, 558);
//table code end
mainPanel.add(tableRadioPanel);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1260, 630);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.getContentPane().add(vicu.getMainPanel());
frame.getContentPane().setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}
In your example, you are not registering an ActionListener to profsBtn or officeSpBtn, you keep registering to coursesBtn
JRadioButton coursesBtn = new JRadioButton("Courses");
//...
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
//...
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
//...
coursesBtn.addActionListener(this);
Once I register the ActionListener to the correct buttons, it works fine
The problem seems to be that the code adds the listener 3 times to a single button, rather than once each to each of the 3 buttons!
..my application is for a very limited scope and can do without a layout manager for my purposes, unless you think this is affecting the table's behaviour?
No, not the table. It was however causing the emptyLabel to be assigned no space in the layout. Here is a robust, resizable version of the GUI.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.util.*;
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel(new BorderLayout(5,5));
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
mainPanel.setBorder(new EmptyBorder(5,5,5,5));
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
//mainPanel.setSize(1260, 630);
//mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
profsBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
officeSpBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollPane.setBounds(160, 0, 1016, 558);
//table code end
JPanel gridConstrain = new JPanel();
gridConstrain.add(tableRadioPanel);
mainPanel.add(gridConstrain, BorderLayout.LINE_START);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("Empty Label");
emptyLabel.setFont(emptyLabel.getFont().deriveFont(80f));
//emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.PAGE_START);
frame.getContentPane().add(vicu.getMainPanel());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Event: " + e);
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}
I'm passing values for a java file which creates a JTable.
ResultSet res = np.InvestmentByInvestType(IType);
String tablename = "Investment By Invest Type";
int customAmt = np.showCustomizeInvestAmount1(IType);
CommonTable ct = new CommonTable();
ct.CommonSearchTable(res, customAmt,tablename);
I created a button in CommonSearchTable to export the JTable data using the ResultSet. But it showing error "Operation not allowed after ResultSet closed". A method in CommonSearchTable.java is as below:
public void CommonSearchTable( final ResultSet res, int totally, final String tablename) throws SQLException
{
JButton exportTable= new JButton ("Export");
ResultSetMetaData metaData = res.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++)
{
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<String>> data = new Vector<Vector<String>>();
while (res.next())
{
Vector<String> vector = new Vector<String>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++)
{
vector.add(res.getString(columnIndex));
}
data.add(vector);
}
model1 = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model1);
int rows = table.getRowCount();
Sorter = new TableRowSorter<DefaultTableModel> (model1);
table.setRowSorter(Sorter);
showSearchPages(30, 1);
table.setModel(model1);
String showTotal = "Total Amount : Rs."+totally+"/-";
JPanel footer = new JPanel();
JLabel show = new JLabel(showTotal);
box1.setBounds(10,30,800,30);
show.setBounds(10, 60, 100, 30);
show.setFont(new Font("Tahoma",Font.BOLD,16));
footer.add(box1);
footer.add(show);
footer.setPreferredSize(new Dimension(800,100));
JPanel holdingPanel = new JPanel(null);
JScrollPane sp = new JScrollPane(table);
JButton print = new JButton ("Print");
print.setBounds(10,10,100,30);
exportTable.setBounds(120,10,100,30);
sp.setBounds(10,50,780,580);
holdingPanel.add(print);
holdingPanel.add(exportTable);
holdingPanel.add(sp);
JFrame f = new JFrame("Search Results");
f.getContentPane().add(holdingPanel,BorderLayout.CENTER);
f.getContentPane().add(sp.getVerticalScrollBar(),BorderLayout.EAST);
f.getContentPane().add(footer,BorderLayout.SOUTH);
f.setPreferredSize(new Dimension(850,680));
f.pack();
f.setLocationRelativeTo(null);
f.dispose();
f.setResizable(false);
f.setIconImage(img.getImage());
f.setVisible(true);
exportTable.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent aev)
{
try
{
ExportFile ef = new ExportFile();
ef.WriteFile(res, tablename);
}
catch (SQLException | IOException ex)
{
Logger.getLogger(CommonTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
print.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
PrinterJob printJob = PrinterJob.getPrinterJob();
if (printJob.printDialog())
try
{
printJob.print();
}
catch(PrinterException pe)
{
}
}
});
}
Please show me the way.
As you can read in the docs for Resultset:
A ResultSet object is automatically closed when the Statement object
that generated it is closed, re-executed, or used to retrieve the next
result from a sequence of multiple results.
This means you have to copy the result data into another data structure (like a list, map, whatever suits your needs) before closing the database connection.
Look at this example this will help you. In this example we fetch all data from database on jcombobox actionlistener. Change this according to your need.
class Credit extends JFrame implements ActionListener{
private String value4="0";
private String val="0";
private String val1="0";
private String jama="0",baki="0";
private String nettdate="0",nettb="0",nettbal="0";
private int row=0,count=0,aa=0,bb=0,t1=0;
private String tj1="0",tb1="0",gt1="0";
String h[]={"TID","Date","Jama","Baki","Nett"};
private TableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 0; column < columnCount; column++) {
//columnNames.add(metaData.getColumnName(column));
columnNames.add(h[column]);
}
// data of the table
//Vector<Object> vector = new Vector<Object>();
//Vector<Object> vector1 = new Vector<Object>();
Vector<String> vector1 = new Vector<String>();
Vector<String> vector2 = new Vector<String>();
Vector<Vector<String>> data = new Vector<Vector<String>>();
//Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
//for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
Vector<String> vector = new Vector<String>();
//vector.add(rs.getString(columnIndex));
vector.add(rs.getString(1));
vector.add(rs.getString(2));
vector.add(rs.getString(3));
vector.add(rs.getString(4));
vector.add(rs.getString(5));
// System.out.println(vector);
//}
count++;
data.add(vector);
//System.out.println(data.get(0).get(0));
}
for(int i=0;i<count;i++){
//aa=aa+Integer.parseInt(data.get(i).get(2));
aa=aa+Integer.parseInt(table.getValueAt(i, 2).toString());
System.out.println(table.getValueAt(i, 2).toString());
System.out.println("A:"+aa);
//bb=bb+Integer.parseInt(data.get(i).get(3));
bb=bb+Integer.parseInt(table.getValueAt(i, 3).toString());
System.out.println(table.getValueAt(i, 3).toString());
System.out.println("B:"+bb);
}
tj1=Integer.toString(aa);
System.out.println("TJ:"+tj1);
//header1 = new Vector<String>();
vector1.add("");
vector1.add("Total");
vector1.add(tj1);
tb1=Integer.toString(bb);
//header1 = new Vector<String>();
//header3.add("Total");
vector1.add(tb1);
vector1.add("");
//data1.setSize(table1.getRowCount()+1);
//data1.set(table1.getRowCount()-1, header3);
//data.setSize(count++);
//data.setSize(table.getRowCount()+1);
//data.set(count, header2);
System.out.println("h2:"+vector1);
data.add(vector1);
System.out.println("data:"+data);
//data.set(table.getRowCount()-1, header2);
t1=Integer.parseInt(tb1)-Integer.parseInt(tj1);
gt1=Integer.toString(t1);
System.out.println("GT:"+gt1);
vector2.add("");
vector2.add("Nett Balance");
//header4.add("");
vector2.add("");
vector2.add(gt1);
vector2.add("");
//data.setSize(table.getRowCount()+1);
//data.setSize(count++);
data.add(vector2);
System.out.println("data1:"+data);
//data.set(count, header3);
//data.set(table.getRowCount()-1, header3);
//header2.add("");
count=0;
aa=0;
bb=0;
t1=0;
tj1="0";
tb1="0";
gt1="0";
return new DefaultTableModel(data, columnNames);
}
private static final int GAP = 5;
private static final Font BTN_FONT = new Font(Font.DIALOG, Font.PLAIN, 15);
private JPanel mainPanel = new JPanel();
JButton add,cancel,show,search,print,update,delete,net;
JTextField jTextField,jTextField1,jTextField2,jTextField3,jTextField4,jTextField5;
JComboBox jComboBox;
String Select[]={"Select"};
Object name,s1;
String an="0",nam="0",mono="0",cit="0";
int token=0,tid=1,a,stid=0;
JFrame f;
AbstractAction action;
private String id;
Connection con=null;
Statement st=null;
ResultSet rs=null;
//private String stid;
JPanel tablePanel;
DefaultTableModel model;
DefaultTableModel model1;
JTable table,table3;
private Vector<Vector<String>> data; //used for data from database
private Vector<Vector<String>> data1; //used for data from database
private Vector<String> header; //used to store data header
private Vector<String> header2; //used to store data header
private Vector<String> header3;
private Vector<String> header4;
private JLabel jlab4,jlab5,jlab6,jlab7;
Credit(JFrame frm){
Toolkit tk=Toolkit.getDefaultToolkit();
Image img=tk.getImage("1.jpg");
setIconImage(img);
JPanel creditPanel = createPanel1("Customer Credit & Debit Amount");
tablePanel = createPanel2("Customer Credit & Debit Table");
creditPanel.setBackground(Color.WHITE);
tablePanel.setBackground(Color.WHITE);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.add(creditPanel, BorderLayout.PAGE_START);
mainPanel.add(tablePanel, BorderLayout.CENTER);
creditPanel.setVisible(true);
mainPanel.setBackground(Color.BLACK);
frm.add(mainPanel);
}
private JPanel createPanel2(String title){
tablePanel=new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel,BoxLayout.Y_AXIS));
header = new Vector<String>();
header.add("TID");
header.add("Date");
header.add("Jama");
header.add("Baki");
header.add("Nett");
header4 = new Vector<String>();
header4.add("A/C No.");
header4.add("Name");
//header4.add("Date");
header4.add("Mobile");
header4.add("City");
model=new DefaultTableModel(data,header);
model1=new DefaultTableModel(data1,header4);
table = new JTable(model);
table3 = new JTable(model1);
table.setRowSorter(new TableRowSorter(model));
table.setRowHeight(30);
table3.setRowHeight(30);
table.setFont(new Font("Times New Roman",Font.BOLD,15));
table3.setFont(new Font("Times New Roman",Font.BOLD,15));
table.getTableHeader().setFont( new Font( "Times New Roman" , Font.BOLD, 15 ));
table3.getTableHeader().setFont( new Font( "Times New Roman" , Font.BOLD, 15 ));
table.setDefaultRenderer(Object.class, new TableCellRenderer(){
table3.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table3.getColumnModel().getColumn(0).setPreferredWidth(123);
table3.getColumnModel().getColumn(1).setPreferredWidth(250);
table3.getColumnModel().getColumn(2).setPreferredWidth(123);
table3.getColumnModel().getColumn(3).setPreferredWidth(125);
JScrollPane scroll=new JScrollPane(table);
JScrollPane scroll1=new JScrollPane(table3);
scroll1.setPreferredSize(new Dimension(50,63));
JPanel p=new JPanel();
JButton btn=new JButton("Print");
JButton btn1=new JButton("Export");
p.add(btn);
p.add(btn1);
tablePanel.add(p);
tablePanel.add(scroll1);
tablePanel.add(scroll);
tablePanel.setBorder(BorderFactory.createTitledBorder(title));
return tablePanel;
}
private JPanel createPanel1(String title) {
JPanel addUnitPanel = new JPanel();
addUnitPanel.setLayout(new GridLayout(4,1, GAP, GAP));
JLabel jlab=new JLabel("Name:");
jComboBox=new JComboBox(Select);//Select
jlab.setPreferredSize(new Dimension(100,10));
jComboBox.setPreferredSize(new Dimension(150,30));
jComboBox.addActionListener(new ActionListener(){
private int b=0,a=0;
private String tj="0";
private String tb="0";
private int t=0;
private String gt="0";
public void actionPerformed(ActionEvent ae){
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
// ResultSet rs1=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/Program Files/Shop/shop.accdb";
//userID = "Admin";
password = "3064101991";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
Object name=jComboBox.getSelectedItem();
con=DriverManager.getConnection(url);//,"system","manager"
st=con.createStatement();
model.setRowCount(0);
model1.setRowCount(0);
b=0;
a=0;
tj="0";
tb="0";
t=0;
gt="0";
an="0";nam="0";mono="0";cit="0";
DBEngine dbengine = new DBEngine();
data = dbengine.getJamaCustomer(name);
data1 = dbengine.getIdName(name);
System.out.println("data:"+data1);
Object[] d3={data1.get(0).get(0),data1.get(0).
get(1),data1.get(0).get(3),data1.get(0).get(4)};
model1.addRow(d3);
JTable table1=new JTable(data,header);
for(int i=0;i<table1.getRowCount();i++){
Object[] d={data.get(i).get(0),data.get(i).get(1),
data.get(i).get(2),data.get(i).get(3),data.get(i).get(4)};
model.addRow(d);
}
for(int i=0;i<table1.getRowCount();i++){
a=a+Integer.parseInt(data.get(i).get(2));
b=b+Integer.parseInt(data.get(i).get(3));
}
tj=Integer.toString(a);
tb=Integer.toString(b);
Object[] d1={"","Total",tj,tb,""};
model.addRow(d1);
t=Integer.parseInt(tb)-Integer.parseInt(tj);
gt=Integer.toString(t);
Object[] d2={"","Nett Balance","",gt,""};
model.addRow(d2);
table = new JTable(model);
table3 = new JTable(model1);
table.setRowHeight(30);
table3.setRowHeight(30);
JScrollPane scroll=new JScrollPane(table);
JScrollPane scroll1=new JScrollPane(table3);
//scroll.setBackground(Color.red);
tablePanel.add(scroll1);
tablePanel.add(scroll);
rs.close();
// rs1.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
});
JPanel p1=new JPanel();
p1.add(jlab);
p1.add(jComboBox);
addUnitPanel.add(p1);
loadcombo2();
addUnitPanel.setBorder(BorderFactory.createTitledBorder(title));
return addUnitPanel;
}
void loadcombo2()
{
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
// ResultSet rs1=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/Program Files/Shop/shop.accdb";
//userID = "Admin";
password = "3064101991";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
st=con.createStatement();
rs= st.executeQuery("select distinct(Name) from ManageCustomer");
//rs1=st.executeQuery("select Unit from AddUnit");
while(rs.next())
{
jComboBox.addItem(rs.getString(1));
//jComboBox1.addItem(rs1.getString(1));
}
rs.close();
// rs1.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
#Override
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==print){
//Your print code
}
if(ae.getSource()==Export){
//Add jComboBox.addActionListener code here
}
}
public static void main(String args[]){
JFrame frm=new JFrame("Title");
Credit b=new Credit(frm);
//frm.setSize(650, 236);
frm.setSize(650, 700);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setResizable(false);
frm.setLocationRelativeTo(null);
frm.show();
}
}