I am not able to load JFrame for multiple clients whereas it works fine for a single client. I am able to perform all the operations on a single client. The frame becomes visible but the contents are not.
Do I need to add something extra? Am I making the correct connections?I am running it on my local machine.
Can I run multiple instances on the same machine?
Server :
public class ServerThread extends Thread{
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(4518);
while(true){
Socket clientSocket = serverSocket.accept();
Thread window=new Frame1();
window.start();
}
} catch (Exception e) {
e.printStackTrace();
}
Client:
public class Client extends JFrame{
public static void main(String arg[]){
String hostName="localhost";
int portNumber=4518;
try{
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
}
JFrame:
public class Frame1 extends Thread{
static JFrame frame;
private static JTextField textField;
private static JPasswordField passwordField;
static Connection conn = null;
static PreparedStatement pst = null;
static ResultSet rs = null;
public Frame1() {
System.out.println("hello");
initialize();
}
private static void initialize() {
frame = new JFrame();
frame.setVisible(true);
frame.setTitle("Course Registration- Spring 2017");
frame.getContentPane().setBackground(new Color(204, 204, 255));
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Sign in");
btnNewButton.setBackground(new Color(204, 102, 153));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
conn = DBConnect.DBConnect();
String sql = "Select * from users where username =? and password=?";
try{
String userName=textField.getText();
String password=passwordField.getText();
pst = conn.prepareStatement(sql);
pst.setString(1, userName);
pst.setString(2, password);
rs = pst.executeQuery();
if(userName.equals("admin") && password.equals("admin")){
ServerSideViews s = new ServerSideViews();
s.setVisible(true);
s.setUserName(userName);
s.setFrameLogin(frame);
System.out.println(userName);
frame.setVisible(false);
}
else if(rs.next() && !(userName.equals("admin"))){
JOptionPane.showMessageDialog(null, "Welcome " + textField.getText() );
CourseRegistration c = new CourseRegistration();
c.setVisible(true);
c.setFrameLogin(frame);
frame.setVisible(false);
String sql1 = "Select major from users where username=?;";
System.out.println(sql1);
pst = conn.prepareStatement(sql1);
pst.setString(1, userName);
rs = pst.executeQuery();
String major="";
while(rs.next())
{
major=rs.getString("major");
}
c.setUserName(userName);
c.comboBox.setSelectedItem(major);
c.comboBox.disable();
}
else{
JOptionPane.showMessageDialog(null, "Invalid user name or password");
}
}catch(Exception e1){
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(157, 182, 117, 29);
frame.getContentPane().add(btnNewButton);
JLabel lblUserName = new JLabel("User Name");
lblUserName.setBounds(76, 96, 86, 16);
frame.getContentPane().add(lblUserName);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(86, 129, 61, 16);
frame.getContentPane().add(lblPassword);
textField = new JTextField();
textField.setBounds(157, 91, 130, 26);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton_1 = new JButton("Register");
btnNewButton_1.setBackground(new Color(51, 102, 204));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UserRegistration reg = new UserRegistration();
reg.setVisible(true);
reg.setFrameLogin(frame);
frame.setVisible(false);
}
});
btnNewButton_1.setBounds(157, 225, 117, 29);
frame.getContentPane().add(btnNewButton_1);
passwordField = new JPasswordField();
passwordField.setBounds(157, 124, 130, 26);
frame.getContentPane().add(passwordField);
JLabel lblNewLabel = new JLabel("Course Registration - Spring 2017");
lblNewLabel.setBounds(109, 24, 241, 16);
frame.getContentPane().add(lblNewLabel);
}
}
Don't start a task that blocks on the Event Dispatch Thread (EDT). The GUI won't be able to respond to events.
So don't start the ServerSocket from the SwingUtilities.invokeLater(..).
Instead you need to use a separate Thread for the ServerSocket.
Read the section from the Swing tutorial on Concurrency for more information and examples.
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());
}
}
What is causing the null exception here? I am simply unable to see it.. please second set of eyes would help this beginner java student..This application basically captures 5 pieces of info about a game team and insert into mySQL database.
The error is as below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at InsertTeamInfo.insertRecord(InsertTeamInfo.java:130) at InsertTeamInfo.access$100(InsertTeamInfo.java:11)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class InsertTeamInfo extends JFrame{
private String sql;
private Connection con;
private Statement stat;
private JButton btnSave;
private JTextField txtTeam;
private JTextField txtCity;
private JTextField txtYear;
private JTextField txtLoserTeam;
private JTextField txtLoserCity;
private JLabel lblTeam;
private JLabel lblCity;
private JLabel lblYear;
private JLabel lblLoserTeam;
private JLabel lblLoserCity;
public InsertTeamInfo(){
super("Favorite Team");
btnSave = new JButton("Save");
txtTeam = new JTextField("");
txtCity = new JTextField("");
txtYear = new JTextField("");
txtLoserTeam = new JTextField("");
txtLoserCity = new JTextField("");
lblTeam = new JLabel("Team");
lblCity = new JLabel("City");
lblYear = new JLabel("Year Played");
lblLoserTeam = new JLabel("Loser Team");
lblLoserCity = new JLabel("Loser City");
txtYear.setEditable(true);
txtLoserTeam.setEditable(true);
txtLoserCity.setEditable(true);
txtTeam.setEditable(true);
txtCity.setEditable(true);
}
public void launchJFrame(){
//width - height
setSize(500, 300);
getContentPane().setLayout(null);
getContentPane().setBackground(Color.white);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
getContentPane().add(btnSave);
getContentPane().add(txtTeam);
getContentPane().add(txtCity);
getContentPane().add(txtYear);
getContentPane().add(txtLoserTeam);
getContentPane().add(txtLoserCity);
getContentPane().add(lblTeam);
getContentPane().add(lblCity);
getContentPane().add(lblYear);
getContentPane().add(lblLoserTeam);
getContentPane().add(lblLoserCity);
lblTeam.setBounds(new Rectangle(65,20,100,30));
lblCity.setBounds(new Rectangle(65,55,100,30));
lblYear.setBounds(new Rectangle(65, 85, 100, 30));
lblLoserTeam.setBounds(new Rectangle(65, 115, 100, 30));
lblLoserCity.setBounds(new Rectangle(65, 145, 100, 30));
txtTeam.setBounds(new Rectangle(210, 20, 150, 30));
txtCity.setBounds(new Rectangle(210, 54, 150, 30));
txtYear.setBounds(new Rectangle(210, 86, 150, 30));
txtLoserTeam.setBounds(new Rectangle(210, 119, 150, 30));
txtLoserCity.setBounds(new Rectangle(210, 150, 150, 30));
btnSave.setBounds(new Rectangle(65, 190, 90, 30));
setVisible(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
shutDown();
}
});
btnSave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){ //Handle Save button click event
insertRecord();
}
});
}
private void insertRecord(){
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/week5", "root","Saras231");
}
catch(Exception ex){
JOptionPane.showMessageDialog( null, "Error connection to database.");
System.exit(0);
}
try {
sql = "INSERT INTO Wins_S001 (Team, City, Year_T, LoserTeam, LoserCity) VALUES (?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setString(1, txtTeam.getText());
preparedStatement.setString(2, txtCity.getText());
preparedStatement.setString(3, txtYear.getText());
preparedStatement.setString(4, txtLoserTeam.getText());
preparedStatement.setString(5, txtLoserCity.getText());
preparedStatement.executeUpdate();
JOptionPane.showMessageDialog( null, "Data Inserted Successfully");
}
catch(SQLException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog( null, "Data Insert failed.");
}
try{
stat.close();
con.close();
}
catch(SQLException ex){
JOptionPane.showMessageDialog( null, "All active connection closed to the database.");
}
}
private void shutDown(){
int returnVal = JOptionPane.showConfirmDialog(this, "Are you sure you want to quit?");
if(returnVal == JOptionPane.YES_OPTION){
System.exit(0);
}
}
public static void main(String[] args){
InsertTeamInfo gui = new InsertTeamInfo();
gui.launchJFrame();
}
}
Remove the stat instance variable. Remove the con instance variable. Remove the sql instance variable. They should all be local variables (and that's probably the cause of your exception: you're closing stat instead of closing preparedStatement. The line number in the stack trace should confirm it).
Also, make sure these are closed in a finally block, to be absolutely sure that they're closed. And beware: if closing the prepared statement throws an exception, the connection won't be closed.
I want to be able to create an instance of my Client class in my GUI and then pass GUI.this as a parameter for the Client constructor but I'm not sure exactly how to do that. I know I'm missing something obvious! I want to be able to call methods on the other from either class. Obviously I have commented code out because I don't know how or what I am supposed to do to achieve this two way communication without merging the classes! I want to be able to do stuff like send a command through the Client from the GUI class when the "Up" button is clicked on the GUI etc. Thanks for the help in advance.
Client class:
public class Client{
//static playerGUI GUI;
public static void main(String[] args) {
//GUI = new playerGUI();
//GUI.getFrame().setVisible(true);
//Client cli = new Client("localhost",4444);
}
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//GUI.processgrid(response);
//send to GUI to process output!
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
//inputbuttons!
String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}
GUI Class:
public class playerGUI {
private JFrame Frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private playerGUI GUI;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(this.playerGUI);
}
/**
* Create the application.
*/
public playerGUI() {
Frame.getContentPane().setBackground(new Color(255, 255, 255));
Frame.getContentPane().setLayout(null);
Frame.setBounds(100, 100, 500, 630);
Frame.setUndecorated(false); // REMOVES MENU BAR
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ############################################################################################################################################################################
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 600);
humanGameWindow.setVisible(false);
JLabel gameTitle = new JLabel("DUNGEON OF DOOM!!");
gameTitle.setForeground(new Color(100, 149, 237));
gameTitle.setFont(new Font("Moire", Font.BOLD, 28));
gameTitle.setBounds(92, 5, 380, 50);
JButton up = new JButton("Up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
up.setBackground(new Color(100, 149, 237));
up.setBounds(274, 514, 100, 40);
JButton down = new JButton("Down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
down.setBackground(new Color(100, 149, 237));
down.setBounds(274, 555, 100, 40);
JButton left = new JButton("Left");
left.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
left.setBackground(new Color(100, 149, 237));
left.setBounds(173, 535, 100, 40);
JButton right = new JButton("Right");
right.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
right.setBackground(new Color(100, 149, 237));
right.setBounds(375, 535, 100, 40);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
JButton Exit = new JButton("Exit");
Exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Exit.setBackground(new Color(100, 149, 237));
Exit.setBounds(427, 17, 70, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
humanGameWindow.add(gameTitle);
humanGameWindow.add(up);
humanGameWindow.add(down);
humanGameWindow.add(left);
humanGameWindow.add(right);
humanGameWindow.add(pickup);
humanGameWindow.add(Exit);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.LIGHT_GRAY);
mainMenu.setBounds(0, 0, 500, 600);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
hostTextPane = new JTextPane();
hostTextPane.setToolTipText("Enter the host name");
hostTextPane.setBackground(new Color(192, 192, 192));
hostTextPane.setBounds(50, 100, 234, 30);
hostTextPane.setFont(new Font("Moire", Font.BOLD, 19));
portTextPane = new JTextPane();
portTextPane.setToolTipText("Enter the port");
portTextPane.setBackground(new Color(192, 192, 192));
portTextPane.setBounds(50, 175, 234, 30);
portTextPane.setFont(new Font("Moire", Font.BOLD, 19));
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
//not sure if i need to be creating the Client here?
/*
* if (!(hostTextPane.getText().equals("")) &&
* !(portTextPane.getText().equals(""))) { try { Client cli =
* new Client(hostTextPane.getText(), Integer
* .parseInt(portTextPane.getText())); } catch (Exception e1) {
* System.out.println("Error."); } } else {
* JOptionPane.showMessageDialog(null,
* "Do not leave hostname or port no. blank."); }
*/
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
mainMenu.add(hostTextPane);
mainMenu.add(portTextPane);
getFrame().getContentPane().add(humanGameWindow);
getFrame().getContentPane().add(mainMenu);
getFrame().setVisible(true);
}
}
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(GUI);
}
main is a static method, which means it is run in a static context (ie, not "as" any instantiated object). This means you can't access this in main because there is no this to access. You need to access playerGUI with just playerGUI or playerGUI.playerGUI in your Client.main method. Also, you need to set the field playerGUI.playerGUI to static.
Instead of this:
Client newclient = new Client(this.playerGUI);
you need this:
Client newclient = new Client(GUI);
Notice that as main is static there is no this defined.
Also consider changing the names of your class and variables to follow Java naming conventions:
playerGUI should be PlayerGUI
GUI should be gui or whatever you feel like but starting with lowercase
Also do you notice that you are not using that field called GUI? You are only using the variable GUI. So it may be adding up to the confusion.
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.