In my project I've assembled a basic password book, the project is designed to send user information over to a mySQL database after the "Save Information" button has been clicked. It works fine when the String values are hardcoded, but when I try to use any kind of String variable or the toString() method I start getting errors. Does anyone know the correct way to send UN-hardcoded values to mySQL?
import javax.swing.*;
//import java.io.*;
//import java.lang.Thread.State;
import java.awt.event.*;
import java.sql.*;
public class PasswordBook implements ActionListener
{
private static JLabel websiteLabel;
private static JTextField websiteText;
private static JLabel userLabel;
private static JTextField userText;
private static JLabel passLabel;
private static JTextField passText;
private static JLabel emailLabel;
private static JTextField emailText;
private static JButton button;
private static JButton clearButton;
private static JLabel success;
//private static String websiteToString; (values I tried)
//private static String userToString;
//private static String emailToString;
//private static String passToString;
public static void main (String[]args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(400,350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null); // rows columns
websiteLabel = new JLabel("Website"); //1st
websiteLabel.setBounds(10, 20, 80, 25);
panel.add(websiteLabel);
websiteText = new JTextField(); //1st
websiteText.setBounds(100, 20, 165, 25);
panel.add(websiteText);
//websiteToString = websiteText.toString();
userLabel = new JLabel("Username"); //2nd
userLabel.setBounds(10, 60, 80 ,25);
panel.add(userLabel);
userText = new JTextField(20); // 2nd
userText.setBounds(100, 60, 165, 25);
panel.add(userText);
//userToString = userText.toString();
emailLabel = new JLabel("Email"); //3rd
emailLabel.setBounds(10, 100, 80 ,25);
panel.add(emailLabel);
emailText = new JTextField(); //2nd
emailText.setBounds(100, 100, 165, 25);
panel.add(emailText);
//emailToString = emailText.toString();
passLabel = new JLabel("Password"); //4th
passLabel.setBounds(10, 140, 80, 25);
panel.add(passLabel);
passText = new JTextField(); // 4th
passText.setBounds(100, 140, 165, 25);
panel.add(passText);
//passToString = passText.toString();
button = new JButton("Save Information");
button.setBounds(10, 180, 150 ,25);
button.addActionListener(new PasswordBook()); // action listener to button
panel.add(button);
clearButton = new JButton("Clear");
clearButton.setBounds(180, 180, 150, 25);
// CLEARS THE TEXT FIELDS WHEN PRESSED
clearButton.addActionListener(new ActionListener() {
#Override // Override allows function to perfrom independently of the parent class
public void actionPerformed(ActionEvent event)
{
websiteText.setText("");
userText.setText("");
emailText.setText("");
passText.setText("");
success.setText("");
}
});
panel.add(clearButton);
success = new JLabel("");
success.setBounds(10, 220, 300, 25);
panel.add(success);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/passwordbook", "root", "password");
//Statement myStatement = myConn.createStatement();
String sq1 = "INSERT into website_and_user_info"
+ " (Website, Username, Email, Password)"
+ " values (?, ?, ?, ?)";
PreparedStatement statement = myConn.prepareStatement(sq1);
statement.setString(1, websiteText.toString()); // These values work when hardcoded
statement.setString(2, userText.toString());
statement.setString(3, emailText.toString());
statement.setString(4, passText.toString());
statement.executeUpdate();
System.out.println("insert complete");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If I read it right, passText is a Textfild (advice use Hungarian notation, makes code easier to read) to get the text you need .gettext(). Like prepared preparedStatement.setString(int, passText.getText()); that should do the trick. But you need to get text before clearing the fields. You Code seems to first clear and you use .setTxt in the statement. If iam wrong I'm sry, atm.i just have my phone to browse.
Related
When I enter data to a database using the sample code below, the line System.out.println("Insertion complete") is shown on the console. When I go to the database, I find that the stored data is a blank.
I think the problem could be my sqlquery, but I don't see any problem with it.
Here is an example of my code:
public class SignUpFrame extends JFrame {
public SignUpFrame() {
super("SIGN UP");
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
setResizable(false);
setLocation(500, 250);
getContentPane().setBackground(Color.WHITE);
ImageIcon FrameIcon = new ImageIcon("images/signup.png");
JLabel frameicon = new JLabel(FrameIcon);
frameicon.setBounds(150, 0, 100, 100);
add(frameicon);
JLabel firstNamelbl,LastNameLbl,EmailAddressLbl,PasswordLbl,ConfirmPasswordLbl;
JTextField firstNametxt,LastNametxt,EmailAddresstxt;
JPasswordField passwordtxt,ConfirmPasswordtxt;
JButton OKbtn;
JButton CANCELbtn;
firstNamelbl = new JLabel("FIRST NAME:");
firstNametxt = new JTextField();
firstNametxt.setBounds(150, 110, 200, 20);
firstNamelbl.setBounds(50, 110, 100, 20);
LastNameLbl = new JLabel("USERNAME:");
LastNametxt = new JTextField();
LastNametxt.setBounds(150, 140, 200, 20);
LastNameLbl.setBounds(50,140, 100, 20);
EmailAddressLbl = new JLabel("EMAIL ADDRESS:");
EmailAddresstxt = new JTextField();
EmailAddresstxt.setBounds(150, 170, 200, 20);
EmailAddressLbl.setBounds(50, 170, 150, 20);
PasswordLbl = new JLabel("PASSWORD:");
passwordtxt = new JPasswordField();
passwordtxt.setBounds(150, 200, 200, 20);
PasswordLbl.setBounds(50, 200, 150, 20);
ConfirmPasswordLbl = new JLabel("CONFIRM PASSWORD:");
ConfirmPasswordtxt = new JPasswordField();
ConfirmPasswordtxt.setBounds(200, 230, 150, 20);
ConfirmPasswordLbl.setBounds(50, 230, 150, 20);
add(firstNamelbl);
add(firstNametxt);
add(LastNameLbl);
add(LastNametxt);
add(EmailAddressLbl);
add(EmailAddresstxt);
add(PasswordLbl);
add(passwordtxt);
add(ConfirmPasswordLbl);
add(ConfirmPasswordtxt);
OKbtn = new JButton("OK");
OKbtn.setBounds(100, 270, 50, 20);
add(OKbtn);
char [] pass = passwordtxt.getPassword();
String passWord = new String(pass);
String FIRSTNAME,USERNAME,EMAIL,PASSWORD;
FIRSTNAME = firstNametxt.getText().toString();
USERNAME =LastNametxt.getText().toString();
EMAIL = EmailAddresstxt.getText().toString();
PASSWORD = passWord;
OKbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String url = "jdbc:mysql://localhost:3306/System";
String user = "root";
String password = "";
Connection con;
try {
con = DriverManager.getConnection(url, user, password);
Statement statement = con.createStatement();
String sqlquery = "insert into signUp_tb "+
"(FirstName,UserName,Email,Password) values ('"+FIRSTNAME+"','"+USERNAME+"','"+EMAIL+"','"+PASSWORD+"')";
statement.executeUpdate(sqlquery);
System.out.println("Insertion complete");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
CANCELbtn = new JButton("CANCEL");
CANCELbtn.setBounds(170, 270, 100, 20);
add(CANCELbtn);
CANCELbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
}
}
You need to initialize your FIRSTNAME, USERNAME etc in ActionListener for OK button. You had initialized those Strings when there was no input data, that's why everything was blank. You want to get JTextFields values when user presses button. Not before.
Tested on SQLite.
OKbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
char [] pass = passwordTxt.getPassword();
String PASSWORD = new String(pass);
String FIRSTNAME,USERNAME,EMAIL;
FIRSTNAME = firstNameTxt.getText();
USERNAME = lastNameTxt.getText();
EMAIL = emailAddressTxt.getText();
String url = "jdbc:mysql://localhost:3306/System";
String user = "root";
String password = "";
Connection con;
try {
con = DriverManager.getConnection(url, user, password);
Statement statement = con.createStatement();
String sqlquery = "insert into signUp_tb "+
"(FirstName,UserName,Email,Password) values ('"+FIRSTNAME+"','"+USERNAME+"','"+EMAIL+"','"+PASSWORD+"')";
statement.executeUpdate(sqlquery);
System.out.println("Insertion complete");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
And setVisible(true) should be the last thing you do. Should look like:
SwingUtilities.invokeLater(() -> {
this.setVisible(true);
});
So you will launch it from EDT.
Edit: about setLayout(null) - Try those A Visual Guide to Layout Managers .
Although it is possible to do without a layout manager, you should use
a layout manager if at all possible. A layout manager makes it easier
to adjust to look-and-feel-dependent component appearances, to
different font sizes, to a container's changing size, and to different
locales. Layout managers also can be reused easily by other
containers, as well as other programs.
From Doing Without a Layout Manager (Absolute positioning)
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
I ve been working on a phonebook program on eclipse java
but and idk how to save information from a textfield to mysql and then be able use it in search, such as writing the name and finding all the info of the specific contact
I also want to save it to my sql
thats my code:
public class Phone {
private JFrame frame;
private JTextField firstfield;
private JTextField phonefield;
private JTextField emailfield;
private JTextField lastfield;
private JPanel MainScreen;
private JPanel newcontact;
private JPanel searchscreen;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Phone window = new Phone();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Phone() {
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(new CardLayout(0, 0));
final JPanel MainScreen = new JPanel();
frame.getContentPane().add(MainScreen, "name_6058038854379");
MainScreen.setLayout(null);
MainScreen.setVisible(true);
final JPanel newcontact = new JPanel();
newcontact.setLayout(null);
frame.getContentPane().add(newcontact, "name_791613670731");
newcontact.setVisible(false);
final JPanel searchscreen = new JPanel();
frame.getContentPane().add(searchscreen, "name_6068807854350");
searchscreen.setVisible(false);
JButton newrecord = new JButton("New Record");
newrecord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newcontact.setVisible(true);
MainScreen.setVisible(false);
}
});
newrecord.setBounds(63, 99, 116, 52);
MainScreen.add(newrecord);
JButton Search = new JButton("Search");
Search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchscreen.setVisible(true);
newcontact.setVisible(false);
}
});
Search.setBounds(243, 99, 102, 52);
MainScreen.add(Search);
JLabel myphonebook = new JLabel(" My Phonebook");
myphonebook.setBounds(162, 44, 102, 14);
MainScreen.add(myphonebook);
JLabel first = new JLabel("First Name:");
first.setBounds(118, 83, 66, 14);
newcontact.add(first);
JLabel last = new JLabel("Last Name:");
last.setBounds(118, 108, 66, 14);
newcontact.add(last);
JLabel Phone = new JLabel("Phone:");
Phone.setBounds(118, 143, 66, 14);
newcontact.add(Phone);
JLabel Emailadress = new JLabel("Email Adress:");
Emailadress.setBounds(118, 180, 66, 14);
newcontact.add(Emailadress);
firstfield = new JTextField();
firstfield.setColumns(10);
firstfield.setBounds(220, 80, 86, 20);
newcontact.add(firstfield);
lastfield = new JTextField();
lastfield.setColumns(10);
lastfield.setBounds(220, 108, 86, 20);
newcontact.add(lastfield);
phonefield = new JTextField();
phonefield.setColumns(10);
phonefield.setBounds(220, 140, 86, 20);
newcontact.add(phonefield);
emailfield = new JTextField();
emailfield.setColumns(10);
emailfield.setBounds(220, 177, 86, 20);
newcontact.add(emailfield);
JLabel lblNewContact = new JLabel("New Contact");
lblNewContact.setBounds(166, 30, 86, 14);
newcontact.add(lblNewContact);
JButton Save = new JButton("Save");
Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String firstname=firstfield.getText();
String lastname=lastfield.getText();
String phonenumber=phonefield.getText();
String emailadress=emailfield.getText();
}
});
Save.setBounds(81, 232, 89, 23);
newcontact.add(Save);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newcontact.setVisible(false);
MainScreen.setVisible(true);
}
});
cancel.setBounds(283, 232, 89, 23);
newcontact.add(cancel);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_6081212161880");
}
}
Write this into your savecommand. You should only create a database an table and change the uppercased words.
try
{
// create a mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://LOCATION/DATABASE";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into TABLE (first_name, last_name, phone_number, email_adress)"
+ " values (?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, firstname);
preparedStmt.setString (2, lastname);
preparedStmt.setString (3, phonenumber);
preparedStmt.setString (4, emailadress);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
I'm having really hard time splitting up my class into two classes, right now I have the GUI and the logic all together in one class and I want it to be separate, I had a read on objects and classes but I still don't understand how I would split it up for my example, my only "logic" in this program is 3 inner classes which determine what the buttons do (Delete record, save record etc...)
Heres my code, can anyone point me in the right direction?
private String name;
private String surname;
private String phone;
private String address;
private String postcode;
private String email;
static String summary;
private JPanel panel;
private JPanel buttonspanel;
private JPanel labelspanel;
private JPanel tablepanel;
private JFrame frame;
private JLabel lblName;
private JLabel lblEmail;
private JLabel lblPostcode;
private JLabel lblAddress;
private JLabel lblSurname;
private JLabel lblPhone;
private JTextField txtName;
private JTextField txtSurname;
private JTextField txtPostcode;
private JTextField txtEmail;
private JTextField txtPhone;
private JTextField txtAddress;
private JButton btnSave;
private JButton btnUpload;
private JButton btnDelete;
String columns[] = {"Name","Surname","Phone","Address","Postcode","Email"};
private DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
public AddressBook() {
createForm();
createLabels();
createTextField();
createButton();
createTable();
frame.add(panel);
frame.setVisible(true);
}
public void createLabels(){
lblName = new JLabel ("Name");
lblName.setBounds(10, 30, 100, 20);
labelspanel.add (lblName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(10, 50, 100, 20);
labelspanel.add (lblSurname);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
labelspanel.add (lblAddress);
lblPhone = new JLabel ("Phone");
lblPhone.setBounds(10, 90, 100, 20);
labelspanel.add (lblPhone);
lblPostcode = new JLabel ("Postcode");
lblPostcode.setBounds(10, 110, 100, 20);
labelspanel.add (lblPostcode);
lblEmail = new JLabel ("Email");
lblEmail.setBounds(10, 130, 100, 20);
labelspanel.add (lblEmail);
}
public void createTextField(){
txtName = new JTextField (null);
txtName.setBounds(110, 30, 150, 20);
labelspanel.add (txtName);
txtSurname = new JTextField (null);
txtSurname.setBounds(110, 50, 150, 20);
labelspanel.add (txtSurname);
txtAddress = new JTextField (null);
txtAddress.setBounds(110, 70, 150, 20);
labelspanel.add (txtAddress);
txtPhone = new JTextField (null);
txtPhone.setBounds(110, 90, 150, 20);
labelspanel.add (txtPhone);
txtPostcode = new JTextField (null);
txtPostcode.setBounds(110, 110, 150, 20);
labelspanel.add (txtPostcode);
txtEmail = new JTextField (null);
txtEmail.setBounds(110, 130, 150, 20);
labelspanel.add (txtEmail);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Address Book");
frame.setSize(800,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
buttonspanel = new JPanel();
buttonspanel.setLayout(new FlowLayout());
buttonspanel.setBorder (BorderFactory.createEtchedBorder ());
labelspanel = new JPanel();
labelspanel.setBorder (BorderFactory.createEtchedBorder ());
labelspanel.setLayout(null);
labelspanel.setPreferredSize(new Dimension (400,200));
tablepanel = new JPanel();
tablepanel.setLayout(new BorderLayout());
panel.add(buttonspanel);
panel.add(labelspanel);
panel.add(tablepanel);
}
public void createButton(){
btnSave = new JButton ("Save to a file");
btnSave.addActionListener(new SaveHandler());
buttonspanel.add (btnSave);
btnDelete = new JButton ("Delete from the table");
btnDelete.addActionListener(new DeleteHandler());
buttonspanel.add (btnDelete);
btnUpload = new JButton ("Add details to table");
btnUpload.addActionListener(new AddHandler());
buttonspanel.add (btnUpload);
}
public void createTable(){
model.setColumnIdentifiers(columns);
JScrollPane scrollPane = new JScrollPane(table);
tablepanel.add(scrollPane, BorderLayout.SOUTH);
}
class SaveHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave)
{
name = ("");
surname = ("");
phone = ("");
address = ("");
postcode = ("");
email = ("");
name = txtName.getText();
surname = txtSurname.getText();
phone = txtPhone.getText();
address = txtAddress.getText();
postcode = txtPostcode.getText();
email = txtEmail.getText();
summary = ("Name:" +name)+("Surname:" +surname)+("Phone:" + phone)+("Address:" + address)+("Postcode:" + postcode)+("Email:" + email);
String saveFile = summary;
try {
BufferedWriter reader = new BufferedWriter(new FileWriter(new File("userinfo.txt"), true));
reader.write(saveFile);
reader.newLine();
reader.close();
JOptionPane.showMessageDialog(frame, "The details were sucessfuly saved");
} catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Something went wrong, please try again");
}
}
}
}
class AddHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnUpload)
{
String nameRow = txtName.getText();
String surnameRow = txtSurname.getText();
String phoneRow = txtPhone.getText();
String addressRow = txtAddress.getText();
String postcodeRow = txtPostcode.getText();
String emailRow = txtEmail.getText();
Object[] row = {nameRow,surnameRow,phoneRow,addressRow,postcodeRow,emailRow};
model.addRow(row);
}
}
}
class DeleteHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnDelete)
{
int i = table.getSelectedRow();
if(i >= 0){
model.removeRow(i);
}
}
}
}
public static void main(String[] args) {
new AddressBook();
}
class GUI{
Jbutton btnsave;
Jbutton Delete;
jbutton update
HandleAll btnHandler = new HandleAll();
btnSave.addActionListener(btnHandler);
Deletea.ddActionListener(btnHandler);
update.addActionListener(btnHandler);
class HandleAll implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave){
//on click save button
}else if(e.getSource()==Delete){
//on click delete button
}else if(e.getSource()==update){
//on click update button
}
}
}
}
you can follow above approach to seperate logic from Gui . by the way i have made the HandleAll class a inner class. HandleAll implements actionListner interface . on every button press actionperformed on this class will get call but by selecting e.getsource you can check which button was pressed exactly.try this approach
I am trying to create a register system for my MySQL database. I have a Java form that I created, in which the user inserts a username, password, and their email. I take that infromation and store it in a variable accordingly. The MySQL connection code works, and it does insert a new row, but the information is blank on the MySQL page. Am I doing someting wrong?
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JPasswordField passwordField;
private static Connection con;
private static PreparedStatement st;
private static int rs;
String username;
String password;
String email;
private JTextField textField_1;
String insertTableSQL = "INSERT INTO `users`" + "(username, password, email) VALUES" + "(?,?,?)";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setResizable(false);
setTitle("Barrage : Login / Register");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 350, 200);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Username: ");
lblNewLabel.setBounds(60, 25, 68, 20);
contentPane.add(lblNewLabel);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setBounds(60, 59, 68, 20);
contentPane.add(lblPassword);
textField = new JTextField();
username = textField.getText();
textField.setBounds(138, 22, 120, 26);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
password = passwordField.getText();
passwordField.setBounds(138, 56, 120, 26);
contentPane.add(passwordField);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/barrage", "root", "");
st = con.prepareStatement(insertTableSQL);
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
}
});
btnRegister.setBounds(119, 138, 89, 23);
contentPane.add(btnRegister);
JLabel lblEmail = new JLabel("E-mail: ");
lblEmail.setBounds(60, 96, 68, 20);
contentPane.add(lblEmail);
textField_1 = new JTextField();
email = textField_1.getText();
textField_1.setBounds(138, 93, 120, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
}
}
Don't do it this way. This is a security vulnerability called a SQL Injection. Instead use a PreparedStatement with variable binding (eg: ?). Here is a tutorial.
As for why it's blank in the database (which is what I think you're saying), you're going to have to prove that the value of those variables are not blank with traditional debugging. IMO, if your tables were set up with the correct constraints (eg: not null) it wouldn't even let you insert in that invalid state in the first place.
I've got a simple Swing GUI and I want to add a new line of text to a JTextArea after a button is pressed, simple right?
The Button and it's ActionListener function correctly (printing stuff to the console works fine), but when I use .append()or .setText() to add text to the textarea, I get a nullpointer exception.
As always, code it below. Any input would be greatly appreciated, thanks!!!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class GUI extends JFrame implements ActionListener {
private JFrame frame;
private JLabel paneHeader;
public JTextArea ipArea, portArea, outputLog, orderLog, cookLog;
private JButton newServer;
public String ipAddress, portNumber, cashierName, cookName;
public GUI() {
initGUI();
}
public void initGUI() {
frame = new JFrame("Restaurant Overview");
Container contentPane = frame.getContentPane();
JLabel paneHeader = new JLabel("Restaurant Monitoring System");
paneHeader.setBounds(200, 0, 200, 25);
paneHeader.setFont(new Font("Calibri", Font.BOLD, 14));
JLabel ipLabel = new JLabel("IP Address: ");
ipLabel.setBounds(25, 30, 75, 20);
ipLabel.setFont(new Font("Calibri", Font.PLAIN, 12));
final JTextArea ipArea = new JTextArea();
ipArea.setBorder(new LineBorder(Color.GRAY));
ipArea.setBounds(105, 30, 100, 20);
JLabel portLabel = new JLabel("Port Number: ");
portLabel.setBounds(25, 55, 75, 20);
portLabel.setFont(new Font("Calibri", Font.PLAIN, 12));
final JTextArea portArea = new JTextArea();
portArea.setBorder(new LineBorder(Color.GRAY));
portArea.setBounds(105, 55, 100, 20);
JButton newServer = new JButton("Create new Server");
newServer.setBorder(new LineBorder(Color.GRAY));
newServer.setBounds(250, 30, 150, 40);
newServer.setActionCommand("createserver");
newServer.addActionListener(this);
JTextArea outputLog = new JTextArea(" ");
outputLog.setBorder(new LineBorder(Color.GRAY));
outputLog.setBounds(25, 90, 150, 150);
//outputLog.setEditable(false);
JTextArea cashierLog = new JTextArea();
cashierLog.setBorder(new LineBorder(Color.GRAY));
cashierLog.setBounds(185, 90, 150, 150);
//cashierLog.setEditable(false);
JTextArea cookLog = new JTextArea();
cookLog.setBorder(new LineBorder(Color.GRAY));
cookLog.setBounds(345, 90, 150, 150);
//cookLog.setEditable(false);
contentPane.add(paneHeader);
contentPane.add(ipLabel);
contentPane.add(ipArea);
contentPane.add(portLabel);
contentPane.add(portArea);
contentPane.add(outputLog);
contentPane.add(cashierLog);
contentPane.add(cookLog);
contentPane.add(newServer);
frame.setLayout(null);
frame.pack();
frame.setSize(600,400);
frame.setVisible(true);
}
public void test() {
//ipAddress = ipArea.getText() + "\n";
//portNumber = portArea.getText() + "\n";
String text = "lemons";
//System.out.println(text);
outputLog.append(text);
//outputLog.append(portNumber);
}
public void actionPerformed(ActionEvent e) {
if ("createserver".equals(e.getActionCommand())) {
//test();
outputLog.append("lemons");
} else {
//Do Nothing
}
}
}
You are likely shadowing a variable -- declaring it more than once, but initializing a local variable not the class field, and so the class field remains null.
Edit:
Yep, sure enough you do. In your constructor you have
JTextArea outputLog = new JTextArea(" ");
This re-declares the outputLog variable, and so you are initializing only the variable local to the constructor. The solution is not to redeclare the variable but instead initialize the class field. So change the above to
outputLog = new JTextArea(" ");
You will need to do this for every variable that needs to be accessed in the class scope. For those that are OK to declare locally, do so, but in the sake of safety, get rid of their corresponding class declaration so as not to risk causing the same error in the future.
Your error is that the instance variable outputLog is not initialized.
your code not done on EDT, you have to wrap tht into invokeLater()
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
outputLog.setText(outputLog.getText()
+ System.getProperty("line.separator") + text);
}
});