How to resolve the nullpointer exception [duplicate] - java

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.

Related

SQLite database not displaying on button click

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!

Scrollbar not getting created/ table not shown

I'm writing a program where there is a JTable to be created (Which I'm able to). But I want to add a scroll bar to it. Below is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
static DefaultTableModel model = new DefaultTableModel();
static JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.add(new JScrollPane(table));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
table.setBounds(10, 131, 516, 178);
contentPane.add(table);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
When I run the above program, the table frame is also not displayed. But when I remove frame.add(new JScrollPane(table));, it is displaying the table in the JTable area, but there is no scrollbar in it.
Please let me know how can I get a scrollbar in the table and display the data correctly.
Thanks
At first don't use null layout, please read here.
frame.add(new JScrollPane(table)); this scroll pane is not displaying because in null layout each component needs to have bounds. Try below code. I just changed static variables to instance variables. And added scrollpane in to the constructor.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(10, 131, 516, 178);
contentPane.add(scroll);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}

Eclipse Jasper report in Java Swing Application

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.

NullPointException error when setting attributes

I'm getting a NullPointerException error at line 77 lblNewLabel.setVisible(false);
which is called from line 65 runTest(); in the following code. (This is a dummy project I wrote to simulate a problem I'm having in a larger project). What I'm trying to do is change the attribute of several fields, buttons, etc based on user action at various places in the project. I would like to group all the changes in a separate method that can be called from various other methods. I'm still a Java novice, having come from some Visual Basic and Pascal experience. Seems like what I'm trying to do should be straight forward, but for now, I'm at a loss. Thanks in advance for your suggestions.
package woodruff;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class MyTest extends JFrame {
private JPanel contentPane;
private JTextField txtHasFocus;
private JLabel lblNewLabel;
/**
* Create the frame.
*/
public MyTest() {
initialize();
}
private void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 237, 161);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblNewLabel = new JLabel("This is a label.");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setHorizontalTextPosition(SwingConstants.CENTER);
lblNewLabel.setBounds(10, 25, 202, 14);
contentPane.add(lblNewLabel);
JButton btnShow = new JButton("Show");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setVisible(true);
}
});
btnShow.setBounds(10, 50, 89, 23);
contentPane.add(btnShow);
JButton btnHide = new JButton("Hide");
btnHide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewLabel.setVisible(false);
}
});
btnHide.setBounds(123, 50, 89, 23);
contentPane.add(btnHide);
txtHasFocus = new JTextField();
txtHasFocus.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
// Following results in NullPointerException error
// at woodruff.MyTest.runTest(MyTest.java:77)
runTest();
}
});
txtHasFocus.setHorizontalAlignment(SwingConstants.CENTER);
txtHasFocus.setText("Has Focus?");
txtHasFocus.setBounds(67, 92, 86, 20);
contentPane.add(txtHasFocus);
txtHasFocus.setColumns(10);
}
private void runTest() {
lblNewLabel.setVisible(false);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyTest frame = new MyTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
In the initialize() method, you have created a local variable for JLabel, and hence are not initializing the instance field, as a reason it remains initialized to null, and hence NPE.
final JLabel lblNewLabel = new JLabel("This is a label.");
change the above line to: -
lblNewLabel = new JLabel("This is a label.");

New Button Window and UI Alignment

I created a main window where the user will click if he's a system admin, an employee or a member a finance, one of my problem is that they are not centered in the screen, how would I do that? Second, I want it to work like, when I click the Finance Button, the Mainwindow Will close and it will bring me to my log in screen, how would I do that?? Here's my MainWindow Code
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JEditorPane;
import javax.swing.SpringLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFormattedTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow frame = new MainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 333, 191);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JButton btnNewButton = new JButton("Employee");
contentPane.add(btnNewButton, BorderLayout.WEST);
JButton btnNewButton_1 = new JButton("Finance");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
}
});
contentPane.add(btnNewButton_1, BorderLayout.CENTER);
JButton btnNewButton_2 = new JButton("System Admin");
contentPane.add(btnNewButton_2, BorderLayout.EAST);
JLabel lblNewLabel = new JLabel("Welcome");
contentPane.add(lblNewLabel, BorderLayout.NORTH);
}
}
here is my code for a login form
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Login extends JFrame {
private JLabel label1, label2;
private JButton submit;
private JTextField textfield1;
private JPasswordField passfield;
private JPanel panel;
public Login() {
setSize(300, 100);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
label1 = new JLabel("User ID:");
textfield1 = new JTextField(15);
label2 = new JLabel("Password:");
passfield = new JPasswordField(15);
submit = new JButton("Submit");
panel = new JPanel(new GridLayout(3, 1));
panel.add(label1);
panel.add(textfield1);
panel.add(label2);
panel.add(passfield);
panel.add(submit);
add(panel, BorderLayout.CENTER);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}// end login constructor
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String user = textfield1.getText();
char[] passChars = passfield.getPassword();
Connection conn = Jdbc.dbConn();
PreparedStatement ps = null;
ResultSet rs = null;
String pass = new String(passChars);
if (passChars != null) {
String sql = "SELECT employee_ID, employee_password FROM user WHERE employee_ID = ? AND employee_password = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null,"Welcome! "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}// end actionPerformed
}// End ButtonHandler
}// End of class
}
Some suggestions:
Do not use setBounds() for MainWindow (JFrame). Use some Layout and at end use pack(). If you want to set size manually then you can also use setSize().
To close current window and open Login frame add setVisible(false) or dispose() and create Login object and make it visible.
For making frame to be at center try setLocationRelativeTo(null);.
Do not use variable names like label1, textFiled2, btnNewButton, etc... Use proper names for proper variable that reflects it usage.
Example for point 2:
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
Login login = new Login();
}
});
You need to carefully choose a layout manager to suit your needs. You are currently using BorderLayout which doesn't seem to do what you want.
Try adding your three buttons to a JPanel and then setting that panel as your frame's content pane. JPanel uses FlowLayout by default which should do the trick.

Categories