call in a method from another class when jbutton is clicked - java

I intend to write a public method in one class and make the method work when a button is clicked in another JFrame. the class with the method is below:
package Pack.billing;
import Pack.First_Term_Arrears;
import Pack.myKIDS;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
public class Arrears {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
public Arrears(){
conn = myKIDS.connectKids();
}
public void display_all_Arrears(){
First_Term_Arrears ta = new First_Term_Arrears();
try{
String sql ="select ID,NAME,SURNAME,CLASS,OLD_ARREARS,FEES,PAID,NEW_ARREARS,DATE,CONTACT from All_Arrears";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
ta.ArrearsTable.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
and this is the method I want to use:
public void display_all_Arrears(){
First_Term_Arrears ta = new First_Term_Arrears();
try{
String sql ="select ID,NAME,SURNAME,CLASS,OLD_ARREARS,FEES,PAID,NEW_ARREARS,DATE,CONTACT from All_Arrears";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
ta.ArrearsTable.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
the button on the other jframe which I want it to perform this action is as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Arrears ar = new Arrears(); ar.first_term_arrears(); // TODO add your handling code here:
}
but nothing works. please what am I doing wrong. thank you

Are you calling the correct method? You say you want to call display_all_Arrears() on the Arrears instance you create in the button event handler, but instead it calls first_term_arrears() which is not an existing method on that class. Try
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Arrears ar = new Arrears();
ar.display_all_Arrears();
}

Related

Referring to a variable from outside static Connection method [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 1 year ago.
I am new to java and started doing a javaFX project. In this project, I receive a variable from a previous frame, and use it to execute an SQL query in order to render the table based on that particular variable.
Here is my code:
package financials;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* #author param
*/
public class theControl implements Initializable {
#FXML
private Label test;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Statement st;
Connection con = null;
}
/**
*
* #param name
*/
public void previous(String name) {
System.out.println(name);
}
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", "Password");
return con;
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
}
public static ObservableList<RenderNow> getListAccount() {
Connection con = ConnectDB();
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code=? ");
pst.setString(1, name); //This is where I am having trouble
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
}
The problem is that the variable name is not being recognized in the pst.setString line. The error I am getting is that variable 'name' is not found. I tried a different approach where I used name to set the text of Label test, and then later tried to get the variable in the public static Connection ConnectDB() method.
Something like:
public class theControl implements Initializable {
#FXML
private Label test;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Statement st;
Connection con = null;
}
/**
*
* #param name
*/
public void previous(String name) {
System.out.println(name);
test.setText(name); //Where i set the text of label 'text'
}
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", "Password");
return con;
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
}
public static ObservableList<RenderNow> getListAccount() {
String name2 = test.getText(); //Where I try and get the text from label 'text'
Connection con = ConnectDB();
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code=? ");
pst.setString(1, name2); //This is where I am having trouble
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
}
However, this attempt returns an error non-static variable test cannot be referenced from a static context. My understanding is that since the label test is not static, static Connection is unable to get the text. Is there any work around for this ?
In your first case, the variable was not set. It's only available on the method where you have your print method.
In the second case, you are not using the object. The test variable is in one object, so not accessible by static method which are not depending of object.
I suggest you to ad new parameter to your static method, and use like this:
// create new static method which require the name in parameters
public static ObservableList<RenderNow> getListAccountWithName(String name) {
Connection con = ConnectDB(); // get DB thanks to static method
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code = '?'");
pst.setString(1, name); // now you can use name value
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
And now, you can call it from the object like:
ObservableList<RenderNow> accounts = getListAccountWithName(test.getText());
// now what you have what you are looking for

Constructing and object of a class and calling it's methode in Java

Trying to program that can read a MySql database. Somehow I cannot call the methode connect(). It says:
Error: cannot find symbol"
connect.connnect();
_______^
What I'm trying to do is to have the connnect and getData method in different classes, so I can also use the connect class seperately for other projects.
Main:
import java.sql.*;
public class Main {
public static void main( String argv[]) {
Connect connect = new Connect();
Connect.connect();
GetData getdata = new GetData();
getdata.getdata();
}
}
Connect:
import java.sql.*;
public class Connect{
public Connection con;
public Statement st;
public ResultSet rs;
public connect(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/leichtathletik","root","");
st = con.createStatement();
}catch(Exception e1) {
System.out.println("Error: "+e1);
}
}
}
GetData:
import java.sql.*;
public class GetData {
public void getData() {
try {
String query = "select * läufer";
rs = st.esecuteQuery(query);
while (rs.next()) {
String vorname = rs.getString("vorname");
String nachname = rs.getString("nachname");
System.out.println(vorname+" "+nachname);
} // end of while
} catch(Exception e2) {
System.out.println("Error: "+e2);
}
}
}
The "connect"- method on the Connect class needs to have a type.
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html , can be helpful.
Further more, the youtuber (https://www.youtube.com/channel/UCiczh_Q-rC7VhMV0x6__dBw) can maybe help you get started with java.

Linking JComboBox with SQL

I am writing a code to make a list in JComboBox using the data in the database.
It's actually for a POS system, where i have to select an item from a list in the database..
Here is the code i have been trying:
(i did take try it without the while(itemsList != null) .. but it didnt work either
private class ButtonHandlerSales implements ActionListener
{
public final String userName = "root";
private final String password = "";
private final String serverName = "localhost";
private final int portNumber = 3306;
private final String dbName = "alphapos";
public void actionPerformed(ActionEvent action)
{
Connection conn = null;
try
{
conn = this.getConnection();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
//System.out.println("Connected to database");
while(itemsList != null)
{
String[] list= null;
String command = "SELECT itemName FROM item";
try
{
list = viewTable(conn, command);
}
catch (SQLException e)
{
e.printStackTrace();
}
itemList = new JComboBox(list);
}
}
private String[] viewTable(Connection con, String command) throws SQLException
{
String list[] = null;
Statement stmt = null;
try
{
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(command);
int i=0;
while (rs.next())
{
list[i] = rs.getString("itemName");
i++;
}
}
catch (SQLException e )
{
e.printStackTrace();
}
finally
{
if (stmt !=
null) { stmt.close(); }
}
return list;
}
private Connection getConnection() throws SQLException
{
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
conn = DriverManager.getConnection("jdbc:mysql://"
+ this.serverName + ":" + this.portNumber + "/" + this.dbName,
connectionProps);
return conn;
}
}//end of class
I'm not getting any errors.. the code compiles.. but im not getting any output (list is empty)..
Am i doing something wrong here?
Any help is really appreciated... ( im not looking for straight up codes )
Problem 1
In your viewTable method String list[] = null;. You never initialize it with a new String[..]. So you will new a NullPointerException. But it would be better to use an ArrayList, since you may not know exactly how many values will be returned
private List<String> viewTable(Connection con, String command) {
List<String> list = new ArrayList<>();
...
while (rs.next()) {
list.add(rs.getString("itemName"));
}
return list;
}
Problem 2
You are creating the JComboBox in the ActionListener. So you can't add the combo before the action is performed. With combo boxes, it's preferred to work with it's model, rather then the component, when working with the data. JComboBox has a ComboBoxModel. We can use the concrete DefaultComboBoxModel. You can pass an array to its constructor. List, has the method toArray we can call to create an array from the List. Then just pass the array to the DefaultComboBoxModel constructor and call the combo box setModel
List<String> list = null;
String command = "SELECT itemName FROM item";
try {
list = viewTable(conn, command);
} catch (SQLException e) {
e.printStackTrace();
}
ComboBoxModel model = new DefaultComboBoxModel(list.toArray());
itemList.setModel(model);
This way, you can initialize the combo box before the action is performed.
Update
If you want the combo box loaded on application start up, I don't see what the problem is. Just create a method in you class, using the code in the actionPerformed. Then just call that method, like in your main constructor or something. Maybe you could do something like below, where you have the method return a ComboBoxModel and you can use to set the model for the combo box
import java.awt.GridLayout;
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.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test {
private final JComboBox itemList;
public Test() throws SQLException {
itemList = new JComboBox(viewTable(getConnection(), command));
JButton button = new JButton("Populate");
button.addActionListener(new ButtonHandler());
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(itemList);
panel.add(button);
JOptionPane.showMessageDialog(null, panel);
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try {
ComboBoxModel model = viewTable(getConnection(), command);
itemList.setModel(model);
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) throws SQLException {
Test test = new Test();
}
private ComboBoxModel viewTable(Connection con, String command) throws SQLException {
List<String> list = new ArrayList<>();
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(command);
while (rs.next()) {
list.add(rs.getString("itemName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return new DefaultComboBoxModel(list.toArray());
}
public final String userName = "root";
private final String password = "";
private final String serverName = "localhost";
private final int portNumber = 3306;
private final String dbName = "alphapos";
private final String command = "select itemName from item";
private Connection getConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
conn = DriverManager.getConnection("jdbc:mysql://"
+ this.serverName + ":" + this.portNumber + "/" + this.dbName,
connectionProps);
return conn;
}
}

Java: Simple If Statement not executing

Alright, so this has been pissing me off for hours .I do not understand why isn't this if statement not executing. Here's my complete code. There are 2 classes, 'Client' is the main class and the other is the connector class.
package com.app.client;
import java.net.ServerSocket;
import java.sql.SQLException;
public class Client{
private int IntervalForDatabase=60000;
private int IntervalForIPCheck=180000;
private boolean AppRunning=true;
public boolean ConnectionSuccess=false;
private Connector ConnectionTools = new Connector();
public static void main(String args[]){
Thread thread = new Thread(new Runnable(){
public void run(){
Client client = new Client();
}
});
thread.start();
}
Client(){
/* Check For Current Instance Of Program */
try{
ServerSocket ApplicationSocket = new ServerSocket(6251);
}catch(Exception e){
System.exit(0);
}
Thread Network = new Thread(new Runnable(){
public void run(){
while(!ConnectionSuccess){
try{
ConnectionTools.ConnectToDatabaseServer();
ConnectionSuccess=true;
System.out.println("bein a bit");
}catch(Exception e){
}
}
}
});
Network.start();
Thread LiveConnectionCheck = new Thread(new Runnable(){
public void run(){
while(AppRunning){
if(ConnectionSuccess){
/* THIS IF STATEMENT IS NOT EXECUTING */
try {
System.out.println("tester");
Thread.sleep(IntervalForIPCheck);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
LiveConnectionCheck.start();
}
}
The connector class:
package com.app.client;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Connector {
public boolean DatabaseConnection=false;
Socket ClientSocket;
private String DatabaseHost="localhost";
private String DatabaseUsername="root";
private String DatabasePassword = "";
private String DatabaseName = "spyware";
private String TableName="activespywares";
public String CurrentServerIP = "";
private Connection MYSQLConnection = null;
public ResultSet result;
public void ConnectToDatabaseServer(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
MYSQLConnection = DriverManager.getConnection("jdbc:mysql://"+DatabaseHost+"/"+DatabaseName,DatabaseUsername,DatabasePassword);
DatabaseConnection=true;
System.out.println("connected");
}catch(Exception e){
System.out.println(e);
DatabaseConnection=false;
return;
}
}
public String ObtainServerIP() throws SQLException{
String text = "";
try{
System.out.println("we've made it till here");
PreparedStatement state = MYSQLConnection.prepareStatement("SELECT * FROM `activespywares`");
result = state.executeQuery();
System.out.println("we've made it till here");
if(result.next()){
result.next();
text = result.getString("InternetProtocol");
}
return text;
}catch(Exception e){
System.out.println(e);
text=e+"";
}
return text;
}
}
I've checked everything. I don't know what is the problem over here. The if statement is in the 'Client' Class. The connector class is just so you know that it's isn't causing problems.
Make connectionSuccess either volatile or change to an AtomicBoolean (and mark as final). The problem is that you are setting the variable in one Thread but reading it from another.
if(result.next()){
result.next();
Make no sense. You are throwing the first result away when you call result.next() twice here.
For your exceptions, I would recommend the usage of
e.printStackTace()
in the case of something breaking your program.
Now if you execute
//...your code
if(result.next()){
result.next();
//...your code
It throws away your first result and presents you with your second result. I would recommend that you use
//...your code
while(result.next()){
//...your code
to scroll through your records as you please

Navigate through & display each database record in the 'textfield' using an AWT button

How to navigate through and display each database record in the 'textfield' using an AWT button?
I'm trying the make a Java form to navigate through the database records, such that when the 'next' button is pressed, each subsequent hit fetches the next database record into the respective textfields. The problem with this code is no matter how many times I press the next button, only the first record is displayed in the textfields.
I've read on several threads that if(rs.next()) condition will not work in such case. What could be the right fix for this and why?
PS: I've marked the problematic area within Problem code begins and Problem code ends.
import java.awt.Button;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class ManageEmployees implements ActionListener
{
Connection con;
Statement st;
ResultSet rs;
Frame f;
Choice employeeID;
Button savenewemployeeButton, updateemployeeButton, returndashboardButton, nextButton/*, previousButton, lastButton, firstButton*/;
Label nameLabel, usernameLabel, addressLabel, contactnumberLabel, passwordLabel, confirmpasswordLabel, selectemployeeLabel;
TextField nameTextField, usernameTextField, addressTextField, passwordTextField, confirmpasswordTextField;
ManageEmployees()
{
dbconnect();
initframe();
}
public void dbconnect()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:8889/InventoryManagement","root","root");
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from SalesMen";
rs=st.executeQuery(sql);
}
catch(Exception ce)
{
ce.printStackTrace();
}
}
public void initframe()
{
f=new Frame("Manage Employees");
selectemployeeLabel=new Label("Select Employee Type:");
nameLabel=new Label("Employee Name:");
addressLabel=new Label("Address:");
usernameLabel=new Label("User Name:");
passwordLabel=new Label("Password:");
confirmpasswordLabel=new Label("Confirm Password:");
employeeID=new Choice();
employeeID.add("Sales Person");
employeeID.add("Sales Manager");
employeeID.add("Inventory Manager");
employeeID.add("Administrator");
savenewemployeeButton=new Button("Save New Employee details");
savenewemployeeButton.addActionListener(this);
returndashboardButton=new Button("Return to Dashboard");
returndashboardButton.addActionListener(this);
nextButton=new Button("Next");
nextButton.addActionListener(this);
nameTextField=new TextField(30);
addressTextField=new TextField(50);
usernameTextField=new TextField(20);
passwordTextField=new TextField(15);
confirmpasswordTextField=new TextField(15);
f.setLayout(new GridLayout(10,2,0,2));
f.add(selectemployeeLabel);
f.add(employeeID);
f.add(nameLabel);
f.add(nameTextField);
f.add(addressLabel);
f.add(addressTextField);
f.add(usernameLabel);
f.add(usernameTextField);
f.add(passwordLabel);
f.add(passwordTextField);
f.add(confirmpasswordLabel);
f.add(confirmpasswordTextField);
f.add(returndashboardButton);
f.add(savenewemployeeButton);
f.add(nextButton);
passwordTextField.setEchoChar('*');
confirmpasswordTextField.setEchoChar('*');
f.setSize(500,400);
f.setVisible(true);
f.setResizable(false);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{
// Return to dashboard on button click
if(e.getSource()==returndashboardButton)
{
f.dispose();
new Dashboard();
}
// ---------------------------------------- (Begin) Save new employee information ------------------------------------------------------------//
// Save new Sales Person information
String salesmen=employeeID.getSelectedItem();
if(salesmen=="Sales Person" && e.getSource()==savenewemployeeButton)
{
try
{
String fullname1=nameTextField.getText();
String address1=usernameTextField.getText();
String username1=addressTextField.getText();
String password1=passwordTextField.getText();
String sql="insert into SalesMen values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"New Sales Man's details saved!");
}
catch(Exception ce)
{
ce.printStackTrace();
}
}
// Save new Sales Manager information
String salesmanager=employeeID.getSelectedItem();
if(salesmanager=="Sales Manager" && e.getSource()==savenewemployeeButton)
{
try
{
String fullname1=nameTextField.getText();
String address1=usernameTextField.getText();
String username1=addressTextField.getText();
String password1=passwordTextField.getText();
String sql="insert into SalesManagers values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"New Sales Manager's details saved!");
}
catch(Exception ce)
{
ce.printStackTrace();
}
}
// Save new Inventory Manger information
String inventorymanger=employeeID.getSelectedItem();
if(inventorymanger=="Inventory Manager" && e.getSource()==savenewemployeeButton)
{
try
{
String fullname1=nameTextField.getText();
String address1=usernameTextField.getText();
String username1=addressTextField.getText();
String password1=passwordTextField.getText();
String sql="insert into InventoryManagers values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"New Inventory Manager's details saved!");
}
catch(Exception ce)
{
ce.printStackTrace();
}
}
// Save new Administrator information
String administrator=employeeID.getSelectedItem();
if(administrator=="Administrator" && e.getSource()==savenewemployeeButton)
{
try
{
String fullname1=nameTextField.getText();
String address1=usernameTextField.getText();
String username1=addressTextField.getText();
String password1=passwordTextField.getText();
String sql="insert into Administrators values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"New Admin's details saved!");
}
catch(Exception ce)
{
ce.printStackTrace();
}
// ---------------------------------------- (End) Save new employee information ------------------------------------------------------------//
}
if(salesmen=="Sales Person" && e.getSource()==nextButton)
{
try
{
String sql="select * from SalesMen";
rs=st.executeQuery(sql);
// Problem code begins
if(rs.next())
{
nameTextField.setText(rs.getString("FullName"));
usernameTextField.setText(rs.getString("UserName"));
addressTextField.setText(rs.getString("Address"));
}
else
{
rs.previous();
System.out.println("boo!");
JOptionPane.showMessageDialog(null,"No more records");
}
}
// Problem code ends
catch(Exception ce)
{
ce.printStackTrace();
}
}
}
public static void main(String[] args)
{
new ManageEmployees();
}
}
use Swing JComponents rather than AWT Components
use JTable instead of sets of AWT TextFields
search for ResultSetTableModel or TableFromDatabase for easy, stable and correct workaround
ResultSetTableModel, TableFromDatabase or your idea has an issue with Event Dispatch Thread
Okay, despite the useful answers people have given; after trial and error, i've found a more appropriate answer to the question. The "if(rs.next())" condition DOES WORK to navigate the database records forward, if used correctly. It works perfectly fine with either AWT or SWING. The problem occurs by inappropriately placing the following lines of code:
/* Remember to carefully use and place the following code in your program*/
String sql="select * from Tablename";
rs=st.executeQuery(sql);
So with reference to the program in this question, notice that the two lines of code above are already called once during program's lifetime when dbconnect() function is called by the constructor. Now pay attention because here's where the problem begins. *The two strings highlighted above are redundantly trigged each time when the 'next button' is hit, thus each time resetting the resultset, and logically disallowing 'rs.next()' to move to the next record. So, only placing those two lines of code once in the dbconnect() function does the job correctly.*

Categories