I have two classes, the first is the GUI which has jTable, and the other one for querying database.
Adding rows to the table within the same class works fine. I used this way:
((DefaultTableModel) table.getModel()).addRow(values);
While values is a Object[] holding the row content.
This is working fine. But populating has to be done from another class. So I have in the query class:
((DefaultTableModel) rg.table.getModel()).addRow(values);
While rg is an object of the GUI class. And table is public.
This doesn't do anything not even throwing an exception.
What should I change in my query class? Here's my method in the query class:
public void selectPassengers(int rows) {
PreparedStatement pst = null;
ResultSet rs = null;
String query = "SELECT * FROM brs.passenger";
try {
pst = con.prepareStatement(query);
rs = pst.executeQuery();
Object[] attributes = new Object[9];
Register rg = new Register();
while (rs.next()) {
attributes[0] = String.valueOf(rs.getString(1));
attributes[1] = rs.getString(2);
attributes[2] = rs.getString(3);
attributes[3] = rs.getString(4);
attributes[4] = rs.getString(5);
attributes[5] = rs.getString(6);
attributes[6] = rs.getString(7);
attributes[7] = rs.getString(8);
attributes[8] = rs.getString(9);
((DefaultTableModel) rg.table.getModel()).addRow(attributes);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Fetching data from the DB is fine. I could print them to the console.
jTable is I assume is built correctly. I can tell this because I
can insert rows correctly but only within the GUI class itself (the
class where jTable is there).
Moving the inserting logic to a different class (querying class) is
where I am stuck.
I solved this by calling the frame object before the model object.
So instead of rg.model.addRow();, I used rg.frame.model.addRow();, after making frame public in the GUI class.
Related
I'm totally new to programming and not really good with it. This is my first question in stack overflow. I'm doing a project where I use java swing to develop a hotel management desktop application. I need help on displaying data from 2 sql tables to a single jtable.I have created a method for that.A positive response is appreciated :). The code is stopped in the while loop and gives fail as output.
The code will be as follows:
public void displayTable(){
try{
String sql = "SELECT customer.Cid,customer.Cname,customer.CEmail,customer.CContact,Reservation.checkIn,Reservation.checkOut from customer,Reservation where customer.Cid = Reservation.CusID";
System.out.println("done");
PreparedStatement pst;
pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
System.out.println(jTable1);
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
List<itp.reservation.model.ReservationDetails> arrList = new ArrayList<itp.reservation.model.ReservationDetails>();
List<itp.reservation.model.CustomerDetails> arList = new ArrayList<itp.reservation.model.CustomerDetails>();
System.out.println("new done");
while(rs.next())
{
System.out.println("lev");
itp.reservation.model.CustomerDetails x = new itp.reservation.model.CustomerDetails();
//itp.reservation.model.ReservationDetails y = new itp.reservation.model.ReservationDetails();
System.out.println("qwe");
x.setCid(rs.getString(1));
x.setCname(rs.getString(2));
x.setCemail(rs.getString(3));
x.setCcontact(rs.getInt(4));
System.out.println("new");
//y.setCheckin(rs.getDate(5));
//y.setCheckout(rs.getDate(6));
System.out.println("restable");
//arrList.add(y);
arList.add(x);
}
jTable1.setModel(model);
}catch(Exception e){
System.out.println("Fail");
}
}
Good afternoon
I'm working on a project in witch I have to calculate the performance of a pump for certain parameters like rotation, number of stages, diameter and viscosity. At first I created a database using PostgreSQL with several commercial pumps. The database contains schemas as the companies that manufacture the pumps, in each schema there are tables representing the different series of pumps and the tables have several pumps organized as lines. The lines contains coefficients that represent the pumps and that are necessary to calculate the performance.
I tried to code the application in C++, but was too hard to connect with Postgre, so I ended working with Java and Netbeans (I think it's easier to newcomers). The application is running quite good so far, but I have found two problems that I cannot solve.
To select the pump to make the calculations I had to use two Jcomboboxes and a Jlist. The first Jcombobox is for selecting the manufacturer, the second to select the serie. Finally, the Jlist displays all the pumps in that serie so the user can select one.
I was able to populate the first Jcombobox with the schemas of the database (thanks to you guys, actually), the second with the tables of the schema selected in the first and the Jlist with the names of the pumps.
The first problem is that I cannot clear the second Jcombobox (the series one) after changing the selected manufacturer in the first Jcombobox, it will add more itens every time that I change the first Jcombobox, even if I re-select an item that was already selected. I tried using the command "removeAllItems()", but then it displays just one table and stop filling the Jcombobox.
The second problem is that, when I select a serie in the second Jcombobox, it doesn't immediately display the pumps in the Jlist, the Jlist starts displaing after I select another serie. So, I have to select one and then change to another so the pumps start appearing in the Jlist.
I'm sorry for the long text and the english errors, I hope its enough for you guys to understand. I know the code is not pretty, that's because I'm not so good at this yet and I'm in a bit of a hurry to deliver it.
Here is the code, without all the generated code that Netbeans does.
public final class LabPump extends javax.swing.JFrame {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public LabPump() {
initComponents();
con = ConnectPump.connect();
FillSelectFabricante();
}
public void FillSelectFabricante(){
try {
rs = con.getMetaData().getSchemas();
while(rs.next()){
String schemas = rs.getString("TABLE_SCHEM");
if(schemas.equals("information_schema") || schemas.equals("pg_catalog")){
}
else{
selectFabricante.addItem(schemas);
}
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillSelectSerie(String fabricante){
//selectSerie.removeAllItems();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
while(rs.next()){
String tables = rs.getString(3);
selectSerie.addItem(tables);
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillListBomba(String fabricante, String serie){
DefaultListModel dlm = new DefaultListModel();
dlm.removeAllElements();
try{
String sql = "select * from " + fabricante + "." + serie;
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String bomba = rs.getString("bomba");
dlm.addElement(bomba);
}
listBomba.setModel(dlm);
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
private void selectSerieActionPerformed(java.awt.event.ActionEvent evt) {
selectSerie.addActionListener((ActionEvent e) -> {
String fabricante = selectFabricante.getSelectedItem().toString();
String serie = selectSerie.getSelectedItem().toString();
FillListBomba(fabricante, serie);
});
}
private void selectFabricanteActionPerformed(java.awt.event.ActionEvent evt) {
String fabricante = selectFabricante.getSelectedItem().toString();
FillSelectSerie(fabricante);
}
Thank you all.
I managed to solve the problem just now. When the selectSerie.removeAllItems() line was uncommented the program returned a NullPointerException error.
To solve the problem I used the DefaultComboBoxModel class and then used the RemoveAllElements() method. I'm not quite sure why the other method didn't work though.
Thanks for your time and help Peter.
public void FillSelectSerie(String fabricante) {
DefaultComboBoxModel box;
box = new DefaultComboBoxModel();
box.removeAllElements();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
box.addElement("-");
while (rs.next()) {
String tables = rs.getString(3);
box.addElement(tables);
}
selectSerie.setModel(box);
} catch (SQLException error) {
//JOptionPane.showMessageDialog (null,error);
}
}
Well, I needed to take values from the database, and insert them into the combobox for selection.
Sounds easy enough to do just using 2 classes, UI class and Entity class, which contains all the SQL queries inside (anything to do with database, it's in there):
//This is the UI class
public void fillComboBox(){
Entity et = new Entity();
try{
//call out dbConnector method from Entity class
conn = et.dbConnector();
String query="select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows topic data in combobox
comboBoxName.addItem(rs.getString("Name"));
}
}
catch(Exception e){
e.printStackTrace();
}
}
//runs method
fillComboBox();
Now, the above output works fine with no hitches. In my form, the combo box displays unique values taken from my database in my specified column.
The problem comes when implementing another tier within it.
In short, I have three classes now.
Class 1: UI -> this class purely handles UI
Class 2: Controller -> this class purely runs methods
Class 3: Entity -> this class purely runs anything that have to do with sql database queries
What I did, was to modify the above code, into this:
This is the UI class:
//Declare Variables
JComboBox comboBoxName = new JComboBox();
Controller ct = new Controller();
comboBoxName.addItem(ct.fillComboBox());
And a certain method within the Controller class:
//Declare Variables
Entity et = new Entity();
public String fillComboBox(){
return et.takeNames();
}
Lastly, my Entity class, which contains all sql queries within.
//Declare all variables first
Connection conn = null;
String task = null, names = null;
String query;
//This method connects to database
//There's nothing wrong with this method, I just placed it here to give a general overview of what this method exactly is for you to understand, as I will be calling it out later. Yes, I removed off the **URL** portion intentionally.
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:URL");
JOptionPane.showMessageDialog(null, "Connected!");
return conn;
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
return null;
}
}
public String takeNames(){
try{
conn = dbConnector();
query = "select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows Name data in combobox
names = rs.getString("Name");
}
pst.close();
}
catch(Exception ex){
ex.printStackTrace();
}
return names;
}
Well, basically, how this "new" implementation runs is that, the UI class calls out the Controller class, which calls out the Entity class, which runs the method inside and parse back values all the way to UI.
This method is useful in the sense that it separates different portions of a program, making it look neater. Too bad it is a headache to implement. >.>
Now, the error in this would be that, it will retrieve only 1 value, instead of multiple values. What it does retrieve is the very first 'distinct' value in that particular column I specified. The remaining 'distinct' values are ignored.
I have a hunch it had everything to do with the rs setting, #:
ResultSet rs = pst.executeQuery();
What I had in mind was that it only takes 1 value and sets it, then ignores the rest. Does anyone have any solutions for this? I tried arraylist but failed on how to store numerous rs values in the arraylist (this really stumped me >.>)
I do apologize for the lengthy post, but I tried my best to do up till what I can, before I got stuck at this part for hours.....
modify takeNames() as follows
public ArrayList<String> takeNames(){
//This will collect all names from db
ArrayList<String> names = new ArrayList<>();
try{
conn = dbConnector();
query = "select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows Name data in combobox
//Add data to the array list
names.add(rs.getString("Name"));
}
pst.close();
}
catch(Exception ex){
ex.printStackTrace();
}
//Return the array list you created
return names;
}
Modify fillComboBox() as follows
public ArrayList<String> fillComboBox(){
return et.takeNames();
}
And modify the rest as follows
JComboBox comboBoxName = new JComboBox();
Controller ct = new Controller();
ArrayList<String> nameList = ct.fillComboBox();
for(String name : nameList){
comboBoxName.addItem(name);
}
Can you populate more than one jTable with the same resultSet?
public void tableDisplay() {
String tableQuery = "SELECT foodQuantity,foodName FROM food ORDER BY RAND() LIMIT 3";
ResultSet rs;
PreparedStatement statement;
try {
statement = con.prepareStatement(tableQuery);
rs = statement.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
The code compiles but the second table doesn't get any records from DB.
The point is that I need to select random items from mySql table and I want to display them in few jTables.
Without knowing too much about your code, I'd say that you need to call DbUtils.resultSetToTableModel(rs) once, and store the resulting table model in a local variable. Then, pass that local variable to the two setModel(...) methods
How I populate a JTable with resultSet
try{
playerTableModel = (DefaultTableModel)playerTable.getModel();
rs = controller.getPlayer();
while (playerTableModel.getRowCount() > 0);
int columns = playerTableModel.getColumnCount();
Object[] rows = new Object[columns];
while(rs.next()){
rows[0] = rs.getString(1);
rows[1] = rs.getString(2);
rows[2] = rs.getString(3);
rows[3] = rs.getString(4);
playerTableModel.addRow(rows);
}catch(Exception e){
e.printStackTrace();
}
Can't you just call same method for the second table too?
I am trying to populate a JTable with data from a database. I've tried so many different ways and it just doesn't want to work. Currently I have a class which returns a resultset with the entire database to my UIClass which then uses the resultset to populate the JTable. Bellow is my method that retrieves the resultset and then populates the JTable.
private void SetJTable()
{
int count = 0;
String boatclass, senior, under23, junior;
try
{
ResultSet results = object.AllWorldBestTimes();
DefaultTableModel model = (DefaultTableModel) Times.getModel();
model.addColumn("Boat Class");
model.addColumn("Senior");
model.addColumn("Under 23");
model.addColumn("Junior");
while(count<24)
{
boatclass = results.getString(1);
senior = results.getString(2);
under23 = results.getString(3);
junior = results.getString(4);
System.out.println(boatclass + senior + under23 + junior);
model.insertRow(Times.getRowCount(), new Object[]{boatclass, senior, under23, junior});
count++;
}
Times = new JTable(model);
}
catch (SQLException e)
{
System.out.println("Ef");
}
}
Here is the method of retrieving data from the database:
public ResultSet AllWorldBestTimes() throws SQLException
{
DatabaseConnection connection = new DatabaseConnection();
ResultSet result = connection.SelectStatements("SELECT * FROM WorldBestTimes");
return result;
}
there is no crash so i cannot give the stack trace, nor does it go into the catch statement.
any help would be appreciated!
model.insertRow(Times.getRowCount(), ...
Times.getRowCount() is always going to return zero, since it's empty.
Times = new JTable(model);
Reassigns the reference Times, but it doesn't take the old table out of the form or add the new one into the form.
Try this...
model = new DefaultTableModel();
...and this...
model.insertRow(model.getRowCount(), ...
...and this...
Times.setModel(model);
Hard to say if that will do it or not. The code sample isn't exactly SCCE.