Good Day, I have created a Java GUI with Eclipse(Java JDK 1.8.0_31 & Eclipse 4.4.1). So then I have installed Jasper report v6 in my same project and created jasper report inside my project.
It is generating report and opening Jasper Viewer window.
See the code below;
DB.java
package jasper1;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class DB {
Connection conn = null;
public static class database {
public static String host;
public static String db;
public static String user;
public static String pwd;
}
public static Connection Connector(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://"+database.host+":3306/" +database.db ,database.user,database.pwd);
return conn;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Login Failed.\n" + e);
return null;
}
}
}
form1.java
package jasper1;
import jasper1.DB.database;
import java.awt.EventQueue;
import java.sql.Connection;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class form1 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
form1 window = new form1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn = null;
private JTextField text_Host;
private JTextField text_DB;
private JTextField text_User;
private JTextField text_Pwd;
/**
* Create the application.
*/
public form1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Connect");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
btnNewButton.setText("Please wait...");
}
#Override
public void mouseReleased(MouseEvent e) {
btnNewButton.setText("Connect");
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
database.host = text_Host.getText();
database.db = text_DB.getText();
database.user = text_User.getText();
database.pwd = text_Pwd.getText();
conn = DB.Connector();
if(conn != null){
//JOptionPane.showMessageDialog(null, "Successfully Connected");
String reportPath = "reports/report.jrxml";
try {
JasperReport jr = JasperCompileManager.compileReport(reportPath);
//JOptionPane.showMessageDialog(null, conn);
JasperPrint jp = JasperFillManager.fillReport(jr, null, conn);
JasperViewer.viewReport(jp);
conn.close();
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
return;
}
}
});
btnNewButton.setBounds(73, 167, 130, 23);
frame.getContentPane().add(btnNewButton);
text_Host = new JTextField();
text_Host.setText("localhost");
text_Host.setBounds(93, 32, 110, 20);
frame.getContentPane().add(text_Host);
text_Host.setColumns(10);
text_DB = new JTextField();
text_DB.setText("qatarclean");
text_DB.setBounds(93, 63, 110, 20);
frame.getContentPane().add(text_DB);
text_DB.setColumns(10);
text_User = new JTextField();
text_User.setText("root");
text_User.setBounds(93, 94, 110, 20);
frame.getContentPane().add(text_User);
text_User.setColumns(10);
text_Pwd = new JTextField();
text_Pwd.setText("supun123");
text_Pwd.setBounds(93, 125, 110, 20);
frame.getContentPane().add(text_Pwd);
text_Pwd.setColumns(10);
JLabel lblHost = new JLabel("Host");
lblHost.setBounds(38, 31, 46, 23);
frame.getContentPane().add(lblHost);
JLabel lblDatabase = new JLabel("Database");
lblDatabase.setBounds(38, 63, 56, 20);
frame.getContentPane().add(lblDatabase);
JLabel lblUserName = new JLabel("User Name");
lblUserName.setBounds(38, 94, 67, 23);
frame.getContentPane().add(lblUserName);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(38, 125, 56, 20);
frame.getContentPane().add(lblPassword);
}
}
The questions are:
Is there any way to view this report inside my form object?.
How can I compile this to one file to work in cross platform? I tried to export it to .Jar(Executable Jar) file. But it doesn't include report.jrxml. It is not secure to keep jrxml file outside because it's user readable. How can I compile the project more secure?
What are the exact Jasper Library jar files to add in the project? I have added all jars in jasperreports-6.0.0\dist and jasperreports-6.0.0\lib. When I export it to Executable Jar, file size will be more than 50MB.
If anyone has alternate solution like BIRT Reports, Kindly answer these questions instead of Jasper Reports.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
While working on a GUI project i am stuck with an error called null pointer error.
I am unable to resolve this problem.
The line which shows the error is closed by double asterisk on both sides(**).(line 80)
I have connected this with a SQL database and error erupts while assigning Jtable its value and structure.
package connectsqlite;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
public class afterLogin extends JFrame {
public JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
afterLogin frame = new afterLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connect = null;
public afterLogin() {
connect = sqliteConnection.conn();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 695, 422);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnBack = new JButton("Log out");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connecting window = new Connecting();
window.frame.setVisible(true);
}
});
btnBack.setBounds(10, 62, 114, 23);
contentPane.add(btnBack);
JButton btnNewButton = new JButton("Load Details");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String query = "SELECT * FROM Appointments";
PreparedStatement pst = connect.prepareStatement(query);
ResultSet rs = pst.executeQuery();
**table.setModel(DbUtils.resultSetToTableModel(rs));**
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(10, 28, 114, 23);
contentPane.add(btnNewButton);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(162, 57, 435, 305);
contentPane.add(scrollPane);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane.setViewportView(scrollPane_1);
}
}
You haven't instantiated your table, it's only declared. Therefore, when you call setModel on it it's going to cause a NullPointerException.
any help would be greatly appreciated.
I've created 2 JFrames, one is a login window which verifies user credentials and I've linked it with my website's mySQL(This works and was hard since I'm very new to Java), and the other one is my main window which contains the main user interface where the user will work from.
I am trying to find a way that when user credentials are verified, the login window closes and opens the Main window. The more I dig into this, the more I think I've built this whole thing wrong, because both JFrames are built in main methods (I though this was how you did it, every tutorial begins with a main method).
to the actionPerform I've created on the JButton or textField_Password, but that does not work at all.Any idea how to open another class from actionPerform?
I would like to open the main window once user credentials are verified. Any ideas on how to proceed. This is all new to me and any help would be greaty appreciated.
Thanks in advance to anyone who helps me with this one, because I'm kind of stuck!
I was trying to add the following:
Main window = new Main();
window.frame.setVisible();
to my Jbutton actionPerform
here is the main code, any help would be greatly appreciated as I am a little loss
import javax.swing.JFrame;
import java.awt.SystemColor;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.PreparedStatement;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JSeparator;
import javax.swing.JPasswordField;
import javax.swing.JCheckBox;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.sql.SQLException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Login {
private JFrame frame;
private JTextField txtUsername;
private JPasswordField txtPassword;
final String signUp = ("https://www.google.com");
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setBounds(100, 100, 547, 382);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setLocationRelativeTo(null);
// frame.setUndecorated(true);
txtUsername = new JTextField();
txtUsername.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
txtUsername.setText(null);
}
});
JLabel labelResponse = new JLabel("");
labelResponse.setHorizontalAlignment(SwingConstants.CENTER);
labelResponse.setFont(new Font("Dialog", Font.BOLD, 12));
labelResponse.setForeground(Color.ORANGE);
labelResponse.setBounds(122, 280, 277, 30);
frame.getContentPane().add(labelResponse);
txtUsername.setBorder(null);
txtUsername.setHorizontalAlignment(SwingConstants.CENTER);
txtUsername.setFont(new Font("Meiryo", Font.BOLD, 18));
txtUsername.setForeground(new Color(0, 128, 0));
txtUsername.setOpaque(false);
txtUsername.setText("Username");
txtUsername.setBackground(SystemColor.inactiveCaption);
txtUsername.setBounds(82, 62, 353, 53);
frame.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
/*
* JLabel labelClose = new JLabel("X");
*
labelClose.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
* labelClose.addMouseListener(new MouseAdapter() {
*
* #Override public void mouseClicked(MouseEvent e) {
System.exit(0); } });
* labelClose.setFont(new Font("Tahoma", Font.BOLD, 20));
* labelClose.setForeground(new Color(102, 205, 170));
labelClose.setBounds(493,
* 11, 22, 22); frame.getContentPane().add(labelClose);
*
* JLabel labelMin = new JLabel("-");
*
labelMin.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
* labelMin.addMouseListener(new MouseAdapter() {
*
* #Override public void mouseClicked(MouseEvent arg0) {
* frame.setState(Frame.ICONIFIED); } });
labelMin.setForeground(new Color(102,
* 205, 170)); labelMin.setFont(new Font("Tahoma", Font.BOLD,
20));
* labelMin.setBounds(470, 11, 22, 22);
frame.getContentPane().add(labelMin);
*/
JLabel lblGt = new JLabel("Log In");
lblGt.setForeground(new Color(0, 128, 0));
lblGt.setFont(new Font("Meiryo", Font.BOLD, 20));
lblGt.setBounds(10, 5, 88, 38);
frame.getContentPane().add(lblGt);
JSeparator separator = new JSeparator();
separator.setBounds(82, 113, 353, 2);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(82, 190, 353, 2);
frame.getContentPane().add(separator_1);
JCheckBox chckbxShowPass = new JCheckBox("Show Pass");
chckbxShowPass.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
chckbxShowPass.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (chckbxShowPass.isSelected()) {
txtPassword.setEchoChar((char) 0);
} else {
txtPassword.setEchoChar('*');
}
}
});
chckbxShowPass.setBorder(null);
chckbxShowPass.setOpaque(false);
chckbxShowPass.setForeground(new Color(0, 128, 0));
chckbxShowPass.setFont(new Font("Meiryo", Font.BOLD, 14));
chckbxShowPass.setBackground(new Color(0, 128, 0));
chckbxShowPass.setBounds(409, 281, 106, 23);
frame.getContentPane().add(chckbxShowPass);
JLabel labelRegister = new JLabel("Register");
labelRegister.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
labelRegister.setForeground(new Color(0, 128, 0));
labelRegister.setFont(new Font("Meiryo", Font.BOLD, 14));
labelRegister.setBounds(10, 285, 76, 16);
frame.getContentPane().add(labelRegister);
JButton buttonLogin = new JButton("Login");
buttonLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "password"); // not the actual
String query = "select EmailAddress,
Password from users where EmailAddress LIKE '%"
+
txtUsername.getText() + "%'";
PreparedStatement statement =
con.prepareStatement(query);
ResultSet result =
statement.executeQuery();
if (result.next()) {
String dbasePassword =
result.getString("Password").toString().trim();
String enteredPassword = new
String(txtPassword.getText().trim());
if
(dbasePassword.equals(enteredPassword))
labelResponse.setText("User recognized");
else
labelResponse.setText("Verify credentials");
} else {
labelResponse.setText("You
must be registered to use this software.");
}
statement.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception evt) {
evt.printStackTrace();
labelResponse.setText("Exception
occurred while searching in the users table");
}
}
});
txtPassword = new JPasswordField();
txtPassword.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER)
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root",
"password");
String query = "select
EmailAddress, Password from users where EmailAddress LIKE '%"
+
txtUsername.getText() + "%'";
PreparedStatement statement =
con.prepareStatement(query);
ResultSet result =
statement.executeQuery();
if (result.next()) {
String dbasePassword =
result.getString("Password").toString().trim();
String enteredPassword
= new String(txtPassword.getText().trim());
if
(dbasePassword.equals(enteredPassword))
labelResponse.setText("User recognized");
else
labelResponse.setText("Verify credentials");
} else {
labelResponse.setText("You must be registered to use this software.");
}
statement.close();
con.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception evte) {
evte.printStackTrace();
labelResponse.setText("Exception occurred while searching in the users
table");
}
}
});
txtPassword.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
txtPassword.setText(null);
}
});
txtPassword.setText("Password");
txtPassword.setBorder(null);
txtPassword.setHorizontalAlignment(SwingConstants.CENTER);
txtPassword.setForeground(new Color(0, 128, 0));
txtPassword.setFont(new Font("Meiryo", Font.BOLD, 18));
txtPassword.setOpaque(false);
txtPassword.setBackground(SystemColor.inactiveCaption);
txtPassword.setBounds(82, 139, 353, 53);
frame.getContentPane().add(txtPassword);
buttonLogin.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttonLogin.setBorderPainted(false);
buttonLogin.setBackground(new Color(0, 128, 0));
buttonLogin.setFont(new Font("Tahoma", Font.PLAIN, 18));
buttonLogin.setBounds(82, 216, 353, 53);
frame.getContentPane().add(buttonLogin);
labelRegister.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
try {
Desktop.getDesktop().browse(new
URI("insertURL"));
} catch (Exception ex) {
// System.out.println(ex);
}
}
});
}
}
I found a solution and I will post it here. Hopefully it helps other new coders out there.
My main problem was that I was trying to link two application windows. Instead of selecting New/Other/Jframe, I used New/Other/Application Window which makes it tough to call the second window.
I am developing a simple client-server application.
I have previously written a working console application, but when I added GUI and try to start the server, the application hangs.
I have implemented a "console" using JTextPane, and want to print all output messages to this console. Please improve or correct my code, and tell me where I have gone wrong.
package com.module.server;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.net.UnknownHostException;
import java.util.Date;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
public class Entry {
private JFrame frame;
private JTextField textIP;
private JTextField textPort;
private JButton btnNewButton;
/**
* Launch the application.
* #throws
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Entry window = new Entry();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws UnknownHostException
*/
public Entry() throws UnknownHostException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws UnknownHostException
*/
private void initialize() throws UnknownHostException {
frame = new JFrame();
frame.setBounds(100, 100, 704, 493);
frame.setTitle("Server Control Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textIP = new JTextField();
textIP.setBounds(80, 39, 496, 27);
frame.getContentPane().add(textIP);
textIP.setColumns(10);
JLabel lblIpAddress = new JLabel("IP Address");
lblIpAddress.setBounds(10, 45, 77, 14);
frame.getContentPane().add(lblIpAddress);
textPort = new JTextField();
textPort.setBounds(80, 77, 86, 27);
frame.getContentPane().add(textPort);
textPort.setColumns(10);
JLabel lblPort = new JLabel("Port");
lblPort.setBounds(10, 83, 46, 14);
frame.getContentPane().add(lblPort);
JTextPane ConsolePane = new JTextPane();
ConsolePane.setBounds(10, 152, 668, 291);
frame.getContentPane().add(ConsolePane);
JLabel lblConsole = new JLabel("Console:-");
lblConsole.setBounds(10, 127, 92, 26);
frame.getContentPane().add(lblConsole);
JButton btnStart = new JButton("Start Service");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ServerSocket server = null;
try {
server = new ServerSocket(2000);
while(true)
{
ConsolePane.setText("Waiting for Clients.......!");
Socket Client = server.accept();
ConsolePane.setText("Client connected from
"+Client.getRemoteSocketAddress());
OutputStream os = Client.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Welcome to Time Server ......");
dos.writeUTF(new Date().toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnStart.setBounds(422, 77, 116, 27);
frame.getContentPane().add(btnStart);
btnNewButton = new JButton("GET IP & Port");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
InetAddress localhost;
try {
localhost = InetAddress.getLocalHost();
textIP.setText(localhost.getHostAddress());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnNewButton.setBounds(260, 79, 152, 23);
frame.getContentPane().add(btnNewButton);
}
}
I've got a problem with this, I've got text from comboBox saved into text variable but now I can't make it to be saved to the file like 'num1' and 'num2' after I click a buttom. I know I am missing something simple - or everything is wrong anyways please help! Thank!
package windowbuilded.views;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class WiewWindow {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WiewWindow window = new WiewWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public WiewWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1, num2, ans2, combo;
num1=Integer.parseInt(textField.getText());
num2=Integer.parseInt(textField_1.getText());
ans2 = num1 + num2;
textField_2.setText(Integer.toString(ans2));
try{
File dir = new File("C:\\test");
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
FileWriter writer = new FileWriter(child, true);
PrintWriter out = new PrintWriter(writer);
out.println(num1);
out.println(num2);
out.close();
}
}
} catch (IOException e) {
// do something
}
}
});
btnNewButton.setBounds(124, 206, 89, 23);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(10, 34, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(124, 34, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(124, 101, 86, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No", "Blah!"}));
String text = (String)comboBox.getSelectedItem();
System.out.println(text);
comboBox.setBounds(265, 101, 121, 20);
frame.getContentPane().add(comboBox);
}
}
Evening all,
So I've been working on creating a local database using SQLite. (As a plugin that is part of Firefox). It uses three classes:
databaseConnection
Login
Display
and two tables (which come under the database MyFilms) called:
Users
MyFilms
databaseConnection is used to simply just connect to my SQLite database MyFilms, which it does fine.
The second class, Login, access my Users table from my database so it can access the logins and proceed to my GUI called Display.
Display will load the following GUI, which consists of a button, which when clicked is supposed to load the data from my database table MyFilms into a JTable:
However, when I click the button, nothing loads... it even looks like the JTable is not there, but when I check my code it defiantly is!
The code where I think the problem might lie is:
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
Any idea why the database is not showing here? Please find the code to each class below:
databaseConnection:
import java.sql.*;
import javax.swing.*;
public class databaseConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Joe\\workspace\\MyFilms.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!");
return conn;
}
catch(Exception anException)
{
JOptionPane.showMessageDialog(null, anException);
return null;
}
}
}
Login:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frmTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frmTest.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField textFieldUN;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
connection = databaseConnection.dbConnector();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frmTest = new JFrame();
frmTest.setTitle("Database Login");
frmTest.setBounds(100, 100, 345, 184);
frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTest.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(34, 37, 64, 14);
frmTest.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password:");
lblNewLabel_1.setBounds(34, 66, 64, 14);
frmTest.getContentPane().add(lblNewLabel_1);
textFieldUN = new JTextField();
textFieldUN.setBounds(126, 34, 151, 20);
frmTest.getContentPane().add(textFieldUN);
textFieldUN.setColumns(10);
JButton btnLogin = new JButton("Login");
frmTest.getRootPane().setDefaultButton(btnLogin);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "Select * from Users where username=? and password=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldUN.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()){
count = count +1;
}
if (count == 1){
frmTest.dispose();
Display GUI = new Display();
GUI.setVisible(true);
}
else if (count > 1){
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}
else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct - Please try again..");
}
rs.close();
pst.close();
}
catch (Exception anException){
JOptionPane.showMessageDialog(null, anException);
}
}
});
btnLogin.setBounds(126, 111, 89, 23);
frmTest.getContentPane().add(btnLogin);
passwordField = new JPasswordField();
passwordField.setBounds(126, 64, 151, 17);
frmTest.getContentPane().add(passwordField);
}
}
Display:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class Display extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
btnLoadData.setBounds(596, 11, 89, 23);
contentPane.add(btnLoadData);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(684, 45, -675, 349);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
Any help would be greatly appreciated! Cheers..
However, when I run it in Eclipse I receive no errors at all. It runs fine, just does not display the database in the JTable.
Could you please replace your Display.java with the following:
Display.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
public class Display extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception anException) {
anException.printStackTrace();
}
}
});
// btnLoadData.setBounds(596, 11, 89, 23);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(btnLoadData, BorderLayout.EAST);
contentPane.add(buttonPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(684, 45, -675, 349);
table = new JTable();
scrollPane.setViewportView(table);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
}
and see the results?
Few changes have been made to your code. They are:
1) You first added scrollPane to the contentPane then you added table to scrollPane. I changed the order.
2) You used absolute layout. I changed that with BorderLayout.
The result displayed on my system is:
Hope this helps!