Issue
So i'm trying to make a frame where it shows a list of every item in my database after you click on the button, but actually when i click on it nothing shows.
public ArrayList show(JTextArea tData) {
ArrayList<Book> books=new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
polaczenie =DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=master",
"sa", "student");
try(Statement stmt = connection.createStatement();) {
ResultSet rs = stmt.executeQuery("{call dbo.showBook}");
while (rs.next()) {
books.add(new Book(
rs.getString("bookNumber"),
rs.getString("title"),
rs.getString("author"),
rs.getString("publicationYear"),
rs.getString("publisher"))
);
}
}
}
catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Error "+ex.getMessage(), "Error", 0);
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error "+ex.getMessage(), "Error", 0);
}
return books;
}
private void bShowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DataBook db=new DataBook();
db.show(tData);
}
Solution
Your show
method will return a ArrayList<Book>
So:
- Have you processed this to display data from the list?
- Does your database have data yet ?
"Sorry I can't add comment because my reputation < 50 " Hope it helps you.
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class App extends JFrame {
JPanel contentPane;
JButton action;
JList<Book> listBooks;
public App() {
this.prepareGUI();
}
public void prepareGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200, 200);
contentPane = new JPanel();
this.setContentPane(contentPane);
action = new JButton("Action");
contentPane.add(action);
listBooks = new JList<Book>();
contentPane.add(listBooks);
action.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Data
Book[] books = new Book[5];
for (int i = 0; i < books.length; i++) {
books[i] = new Book("book " + i, "@@");
}
listBooks.setListData(books);
}
});
}
public static void main(String[] args) {
App app = new App();
app.setVisible(true);
}
}
Hope this help you!!!
Answered By - Puskin