Hopefully a simple fix with connecting to mysql database in java - java

first and foremost I want to point out I'm a novice programmer without much experience, so excuse me if this question seems obvious to some. Also, since I am not sure what the problem is, I will try to give as much information as possible so sorry I seem to ramble. Anyway what I am trying to do is create a java application with a Jframe, and have it interact with a database. I don't really have any experience with databases or mysql, but I was able to follow along a youtube video, and created a java project which successfully connects to a database, creates a table, and inserts information into that table. I figured I would be able to use the same connection function in my project with my frame.
However when I tried this,the program does not connect or display anything in the console, just simply launches my jframe. Its as if the connection part isn't even there? Connection function I used is :
public static Connection getConnection() throws Exception{
try {String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("connected");
return conn;
}catch(Exception e){System.out.println(e);}
return null;
}
here is my full code, sorry if it is hard to read, I did most of my initial coding in eclipse's window builder. The functions to get a connection and to post to the DB are at the bottom after the main (had them before the main but moved them hoping it would make a difference) any and all help is appreciated !
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import com.toedter.calendar.JDateChooser;
public class TemplatePractice extends JFrame {
private JTextField HTHoursWorked;
private JTextField HTHourlyRate;
private JTextField HTCCTips;
private JTextField PCHours;
private JTextField PCTotal;
private JTextField DisplayTP;
private JTextField DispGPPP;
private JTextField DispBnqtPay;
private JTextField DispEstPay;
JTextField DispActualPC;
private final Action action = new SwingAction();
private TemplatePractice() {
final JTextField PCTotal;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(3, 1, 0, 0));
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblNewLabel_1 = new JLabel("Date Worked");
panel.add(lblNewLabel_1);
JDateChooser PCDateWorked = new JDateChooser();
panel.add(PCDateWorked);
JLabel lblHoursWorked = new JLabel("Hours Worked:");
panel.add(lblHoursWorked);
HTHoursWorked = new JTextField();
panel.add(HTHoursWorked);
HTHoursWorked.setColumns(10);
JRadioButton rdbtnRestaruant = new JRadioButton("Restaruant:");
panel.add(rdbtnRestaruant);
JRadioButton rdbtnBanquet = new JRadioButton("Banquet");
panel.add(rdbtnBanquet);
JLabel lblHoursWorked_1 = new JLabel("Hourly Rate: $");
panel.add(lblHoursWorked_1);
HTHourlyRate = new JTextField();
panel.add(HTHourlyRate);
HTHourlyRate.setColumns(10);
JLabel lblCreditCardTips = new JLabel("Credit Card Tips:");
panel.add(lblCreditCardTips);
HTCCTips = new JTextField();
panel.add(HTCCTips);
HTCCTips.setColumns(10);
JButton HTAddBtn = new JButton("Add");
panel.add(HTAddBtn);
JLabel label = new JLabel("");
panel.add(label);
JLabel label_1 = new JLabel("");
panel.add(label_1);
JPanel PCPanel = new JPanel();
getContentPane().add(PCPanel);
JLabel lblPayPeriodStart = new JLabel("Pay Period Start:");
PCPanel.add(lblPayPeriodStart);
JDateChooser PCStartDate = new JDateChooser();
PCPanel.add(PCStartDate);
JLabel lblPayPeriodEnd = new JLabel("Pay Period End");
PCPanel.add(lblPayPeriodEnd);
JDateChooser dateChooser_2 = new JDateChooser();
PCPanel.add(dateChooser_2);
JLabel lblTotalHours = new JLabel("Total Hours:");
PCPanel.add(lblTotalHours);
PCHours = new JTextField();
PCPanel.add(PCHours);
PCHours.setColumns(10);
JLabel lblP = new JLabel("Paycheck Amount: $");
PCPanel.add(lblP);
PCTotal = new JTextField();
PCPanel.add(PCTotal);
PCTotal.setColumns(10);
JButton PCAddBtn = new JButton("Add");
PCAddBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double paydoub = Double.parseDouble(PCTotal.getText());
int i;
for (i=0;i<1000;i++){
double paycheckdouble=0;
paycheckdouble+=paydoub;
double paycheckTotal=paycheckdouble;
String paytotal= String.valueOf(paycheckTotal);
DisplayTP.setText(paytotal);
}
}
});
PCAddBtn.setAction(action);
PCPanel.add(PCAddBtn);
JPanel panel_1 = new JPanel();
getContentPane().add(panel_1);
JButton btnCalculate = new JButton("Calculate");
panel_1.add(btnCalculate);
JLabel lblTotalPay = new JLabel("total pay:");
panel_1.add(lblTotalPay);
DisplayTP = new JTextField();
panel_1.add(DisplayTP);
DisplayTP.setColumns(10);
JLabel lblGratPerParty = new JLabel("Grat Per Party");
panel_1.add(lblGratPerParty);
DispGPPP = new JTextField();
panel_1.add(DispGPPP);
DispGPPP.setColumns(10);
JLabel lblBanquetPay = new JLabel("Banquet Pay");
panel_1.add(lblBanquetPay);
DispBnqtPay = new JTextField();
panel_1.add(DispBnqtPay);
DispBnqtPay.setColumns(10);
DispEstPay = new JTextField("");
panel_1.add(DispEstPay);
DispEstPay.setColumns(10);
DispActualPC = new JTextField();
panel_1.add(DispActualPC);
DispActualPC.setColumns(10);
}
public static void main(String args[]) throws Exception{
getConnection();
post();
TemplatePractice frame = new TemplatePractice();
frame.setVisible(true);
frame.setSize(600,400);
}
public static Connection getConnection() throws Exception{
try {String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("connected");
return conn;
}catch(Exception e){System.out.println(e);}
return null;
}
public static void post() throws Exception{
final String var1 = "john";
final String var2 = "smith";
try{
Connection Con = getConnection();
PreparedStatement posted = Con.prepareStatement("INSERT INTO tablename(first,last) VALUES ('"+var1+"','"+var2+"')");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally {System.out.println("Insert Completed");}
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "SwingAction");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}

Related

Commands are running twice in Java actionperformed

I created an utility that will be used within the firewall zone to get Websphere MQ contents using Java with Swing, since I'm not sure where the defect lies, I've posted almost the entire code apart from the redundant part:
package testbox;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class MainFrame extends JFrame implements ActionListener
{
JLabel lblqname = new JLabel("Please enter the queue name");
JTextField txtqname = new JTextField(25);
JLabel lblqcur = new JLabel("where curdeth greater than");
JTextField txtqcurdfil = new JTextField(5);
JLabel lblchlname = new JLabel("Please enter the Channel name");
JTextField txtchlname = new JTextField(30);
JLabel lblchs = new JLabel("where status is: ");
JTextField txtchs = new JTextField(8);
public String ID;
public String pwdValue;
public String qname;
public int cdepth;
public String chlname;
public String chlstatus;
public String cmdissue;
JTextArea out = new JTextArea();
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
public MainFrame()
{
JLabel jUserName = new JLabel("ID");
JTextField userName = new JTextField();
JLabel jPassword = new JLabel("Password");
JTextField password = new JPasswordField();
Object[] ob = {jUserName, userName, jPassword, password};
int result = JOptionPane.showConfirmDialog(null, ob, "Please input password for Login", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
ID = userName.getText();
pwdValue = password.getText();
final JFrame frame = new JFrame("Environment Choice");
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("QAQmgrList", makeQAPanel());
frame.getContentPane().add(tabbedPane);
}
}
public JPanel makeQAPanel()
{
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
GridBagConstraints gbc_QMGR2 = new GridBagConstraints();
gbc_QMGR2.insets = new Insets(0, 0, 5, 5);
gbc_QMGR2.gridx = 1;
gbc_QMGR2.gridy = 2;
p.add(QMGR2, gbc_QMGR2);
QMGR2.addActionListener(this);
return p;
}
public void createSubframe()
{
final JFrame subframe = new JFrame("Object Choice");
subframe.setSize(1000, 500);
subframe.getContentPane().setLayout(new GridLayout(1, 1));
out.setText(null);
out.setLineWrap(true);
out.setCaretPosition(out.getDocument().getLength());
out.setEditable (false);
JScrollPane jp = new JScrollPane(out);
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel queue = new JPanel();
queue.add(lblqname);
txtqname.setText(null);
queue.add(txtqname);
queue.add(lblqcur);
txtqcurdfil.setText(null);
queue.add(txtqcurdfil);
txtqname.addActionListener(this);
txtqcurdfil.addActionListener(this);
JPanel chl = new JPanel();
chl.add(lblchlname);
txtchlname.setText(null);
chl.add(txtchlname);
chl.add(lblchs);
txtchs.setText(null);
chl.add(txtchs);
txtchlname.addActionListener(this);
txtchs.addActionListener(this);
tabbedPane.addTab("Queues", queue);
tabbedPane.addTab("Channels", chl);
subframe.getContentPane().add(tabbedPane);
subframe.getContentPane().add(jp);
tabbedPane.setVisible(true);
subframe.setVisible(true);
}
public static void main(String[] args)
{SwingUtilities.invokeLater(new Runnable(){ public void run() { #SuppressWarnings("unused") MainFrame m = new MainFrame();}});}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == QMGR1|| e.getSource() == QMGR2)
{createSubframe();}
if (e.getSource() == txtqname){qname = txtqname.getText();}
if (e.getSource() == txtqcurdfil)
{
cdepth = Integer.parseInt(txtqcurdfil.getText());
cmdissue = "qn has value messages";
cmdissue = cmdissue.replace("qn", ""+qname+"");
cmdissue = cmdissue.replace("value", ""+cdepth+"");
System.out.println(cmdissue);
cmdissue = null;
}
if (e.getSource() == txtchlname){chlname = txtchlname.getText(); chlname=null;}
if (e.getSource() == txtchs)
{
chlstatus = txtchs.getText();
cmdissue = "chln is chls";
cmdissue = cmdissue.replace("chln", ""+chlname+"");
cmdissue = cmdissue.replace("chls", ""+chlstatus+"");
System.out.println(cmdissue);
}
}
}
I'm getting the expected outcome for the code:
Running for first time
Say I close this object choice panel and open a new instance, irrespective of which choice I make the command runs twice:
Running for the second time
The iteration repeats. Say I make a choice for the fourth or fifth time, the command runs 4/5 times.
I understood the fact that the somehow it is initializing the objects for the number of times I run it, and it needs to be reset after I close the panel. But I'm not sure how/where to get this done.
Apologies for the lengthy code posted, since I wanted to be sure that people can point the mistake that has been committed.
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 2;
p.add(QMGR1, gbc_QMGR1);
QMGR1.addActionListener(this);
Looks like you are trying to add the same component to the panel twice in two different grid locations. You can't do this.
You need to:
create two different component, or
get rid of one of the components.
Edit:
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
You create the buttons as instance variables.
But then in the makeQAPanel() method you add the actionListener to the button.
QMGR1.addActionListener(this);
...
QMGR2.addActionListener(this);
So every time you invoke that method the actionListener gets added again.
The actionListener should be added in the constructor of you class so it is only added once.
#jesper,
someone explained to me the constructor part of it:
package testbox;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class MainFrame extends JFrame implements ActionListener
{
JLabel lblqname = new JLabel("Please enter the queue name");
JTextField txtqname = new JTextField(25);
JLabel lblqcur = new JLabel("where curdeth greater than");
JTextField txtqcurdfil = new JTextField(5);
JLabel lblchlname = new JLabel("Please enter the Channel name");
JTextField txtchlname = new JTextField(30);
JLabel lblchs = new JLabel("where status is: ");
JTextField txtchs = new JTextField(8);
public String ID;
public String pwdValue;
public String qname;
public int cdepth;
public String chlname;
public String chlstatus;
public String cmdissue;
JTextArea out = new JTextArea();
JButton QMGR1 = new JButton("QMGR1");
JButton QMGR2 = new JButton("QMGR2");
public MainFrame()
{
QMGR1.addActionListener(this);
QMGR2.addActionListener(this);
txtqname.addActionListener(this);
txtqcurdfil.addActionListener(this);
txtchlname.addActionListener(this);
txtchs.addActionListener(this);
JLabel jUserName = new JLabel("ID");
JTextField userName = new JTextField();
JLabel jPassword = new JLabel("Password");
JTextField password = new JPasswordField();
Object[] ob = {jUserName, userName, jPassword, password};
int result = JOptionPane.showConfirmDialog(null, ob, "Please input password for Login", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
ID = userName.getText();
pwdValue = password.getText();
final JFrame frame = new JFrame("Environment Choice");
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("QAQmgrList", makeQAPanel());
frame.getContentPane().add(tabbedPane);
}
}
public JPanel makeQAPanel()
{
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints gbc_QMGR1 = new GridBagConstraints();
gbc_QMGR1.insets = new Insets(0, 0, 5, 5);
gbc_QMGR1.gridx = 1;
gbc_QMGR1.gridy = 1;
p.add(QMGR1, gbc_QMGR1);
GridBagConstraints gbc_QMGR2 = new GridBagConstraints();
gbc_QMGR2.insets = new Insets(0, 0, 5, 5);
gbc_QMGR2.gridx = 1;
gbc_QMGR2.gridy = 2;
p.add(QMGR2, gbc_QMGR2);
return p;
}
public void createSubframe()
{
final JFrame subframe = new JFrame("Object Choice");
subframe.setSize(1000, 500);
subframe.getContentPane().setLayout(new GridLayout(1, 1));
out.setText(null);
out.setLineWrap(true);
out.setCaretPosition(out.getDocument().getLength());
out.setEditable (false);
JScrollPane jp = new JScrollPane(out);
jp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel queue = new JPanel();
queue.add(lblqname);
txtqname.setText(null);
queue.add(txtqname);
queue.add(lblqcur);
txtqcurdfil.setText(null);
queue.add(txtqcurdfil);
JPanel chl = new JPanel();
chl.add(lblchlname);
txtchlname.setText(null);
chl.add(txtchlname);
chl.add(lblchs);
txtchs.setText(null);
chl.add(txtchs);
tabbedPane.addTab("Queues", queue);
tabbedPane.addTab("Channels", chl);
subframe.getContentPane().add(tabbedPane);
subframe.getContentPane().add(jp);
tabbedPane.setVisible(true);
subframe.setVisible(true);
}
public static void main(String[] args)
{SwingUtilities.invokeLater(new Runnable(){ public void run() { #SuppressWarnings("unused") MainFrame m = new MainFrame();}});}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == QMGR1|| e.getSource() == QMGR2)
{createSubframe();}
if (e.getSource() == txtqname){qname = txtqname.getText();}
if (e.getSource() == txtqcurdfil)
{
cdepth = Integer.parseInt(txtqcurdfil.getText());
cmdissue = "qn has value messages";
cmdissue = cmdissue.replace("qn", ""+qname+"");
cmdissue = cmdissue.replace("value", ""+cdepth+"");
System.out.println(cmdissue);
cmdissue = null;
}
if (e.getSource() == txtchlname){chlname = txtchlname.getText(); chlname=null;}
if (e.getSource() == txtchs)
{
chlstatus = txtchs.getText();
cmdissue = "chln is chls";
cmdissue = cmdissue.replace("chln", ""+chlname+"");
cmdissue = cmdissue.replace("chls", ""+chlstatus+"");
System.out.println(cmdissue);
}
}
}
Worked like a charm.. THanks for pointing it out

Creating a Layout in Java [duplicate]

This question already has answers here:
How I can do swing complex layout Java [closed]
(1 answer)
Java GUI Layouts
(5 answers)
Closed 5 years ago.
[I am trying a create a layout like a picture below. I am new to Java programming.]When I am trying to run this. There is no error or anything and nothing displays. Console stops automatically. Kindly help me.
package completeJavaReference;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
------------------------------------------------------------------------
public class tryingProject extends JFrame {
public static final long serialVersionUID = 1L;//Eclipse added
public static JLabel carname;
public static JLabel price, make, year, trim, category, VIN, model,bodytype;
public static JLabel dealerinfo, ID, URL, Name;
public static JTextField priceTextField, makeTextField, yearTextField,
trimTextField, categoryTextField, VINTextField, modelTextField,
bodytypeTextField;
private static JTextField dealerinfoTextField, IDTextField, URLTextField,
NameTextField;
public void createComponents() {
carname = new JLabel("Honda Civic");
price = new JLabel("Price: ");
make = new JLabel("Make: ");
year = new JLabel("Year:");
trim = new JLabel("Trim:");
category = new JLabel("Category:");
VIN = new JLabel("VIN:");
model = new JLabel("Model:");
bodytype = new JLabel("Body Type");
priceTextField = new JTextField(10);
makeTextField = new JTextField(10);
yearTextField = new JTextField(10);
trimTextField = new JTextField(10);
categoryTextField = new JTextField(10);
VINTextField = new JTextField(10);
modelTextField = new JTextField(10);
bodytypeTextField = new JTextField(10);
dealerinfo = new JLabel("Dealer Info");
ID = new JLabel("Dealer ID:");
URL = new JLabel("URL:");
Name = new JLabel("Dealer Name");
dealerinfoTextField = new JTextField(10);
IDTextField = new JTextField(10);
URLTextField = new JTextField(10);
NameTextField = new JTextField(10);
}
public void createLayout(){
JFrame frame = new JFrame("Vehicle Window");
JPanel Panel1 = new JPanel(new FlowLayout());
JPanel Panel2 = new JPanel(new GridLayout(4, 3));
JPanel Panel3 = new JPanel(new FlowLayout());
Panel1.add(carname);
Panel2.add(price);
Panel2.add(priceTextField);
Panel2.add(make);
Panel2.add(makeTextField);
Panel2.add(year);
Panel2.add(yearTextField);
Panel2.add(trim);
Panel2.add(trimTextField);
Panel2.add(category);
Panel2.add(categoryTextField);
Panel2.add(VIN);
Panel2.add(VINTextField);
Panel2.add(model);
Panel2.add(modelTextField);
Panel2.add(year);
Panel2.add(yearTextField);
Panel3.add(dealerinfo);
Panel3.add(dealerinfoTextField);
Panel3.add(ID);
Panel3.add(IDTextField);
Panel3.add(URL);
Panel3.add(URLTextField);
Panel3.add(Name);
Panel3.add(NameTextField);
frame.getContentPane().add(Panel1);
frame.getContentPane().add(Panel2);
frame.getContentPane().add(Panel3);
frame.setTitle("Vechicle Details");
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new tryingProject();
}
}

Two gui windows pop up instead of one

So I wrote the following code:
package myProject;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.*;
public class GuiTest extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField user = new JTextField();
JTextField pass = new JTextField();
JLabel title = new JLabel("Login");
JLabel usernameGui = new JLabel("Username:");
JLabel passwordGui = new JLabel("Password:");
public String userName;
public String passWord;
//Non GUI variables
public String username;
public String password;
File dir = new File("C:\\Users\\User\\Desktop\\account1.txt");
public boolean pressed = false;
public GuiTest(){
JFrame window = new JFrame("Position");
//window.setSize(600, 600);
window.setBounds(500,200,600,600);
window.setResizable(false);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
window.add(panel);
//Labels
panel.add(title);
title.setBounds(290, 110, 100, 100);
panel.add(usernameGui);
usernameGui.setBounds(150,200,150,30);
panel.add(passwordGui);
passwordGui.setBounds(150,240,150,30);
//Text fields
panel.add(user);
user.setBounds(230,240,150,30);
panel.add(pass);
pass.setBounds(230,200,150,30);
//Button
JButton btn = new JButton("Login");
btn.setBounds(250, 290, 100, 30);
panel.add(btn);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
userName = user.getText();
passWord = pass.getText();
pressed = true;
System.out.println(passWord+" "+password+" "+userName+" "+username);
//System.out.println(mn.passWord+" "+mn.password+" "+mn.userName+" "+mn.username);
}
});
}
public static void main(String[] args){
GuiTest test = new GuiTest();
GuiTest mn = new GuiTest();
try{
mn.Write("MyUser", "MyPass");
Scanner scan = new Scanner(mn.dir);
String text = scan.nextLine();
scan.close();
System.out.println(text);
String[] sep = text.split(" ");
mn.username = sep[0];
mn.password = sep[1];
System.out.println("User: " + mn.username + " pass: " + mn.password);
}catch(Exception e){
System.out.println("Error! File didn't create.");
}
Scanner usernameIn = new Scanner(System.in);
Scanner passwordIn = new Scanner(System.in);
String userIn = usernameIn.nextLine();
String passIn = passwordIn.nextLine();
if(mn.userName.equals(mn.username) && mn.passWord.equals(mn.password)){
System.out.print("Access Granted");
}else{
System.out.println("Access Denied");
System.out.println(mn.passWord+" "+mn.password+" "+mn.userName+" "+mn.username);
}
}
public void Write(String user, String pass){
String userONE = user;
String passONE = pass;
try{
PrintWriter file = new PrintWriter(dir);
file.print(userONE+" "+passONE);
file.close();
}catch(Exception e){
System.out.println("Error! File didn't create.");
}
}
}
When I run it two windows pop up (instead of 1) and I cant test the input as both of them somehow use the variables i guess. Does anyone know how to fix it?
Thanks in advance.
When I run it two windows pop up (instead of 1)
Since you are creating two objects of same class.
GuiTest test = new GuiTest();
GuiTest mn = new GuiTest();
Just remove one of them GuiTest test = new GuiTest();. Since you are not using test object.

Reading text file from a GUI

I have a GUI that verifies a username and password. The other part of the assignment is to read from a file that contains a username and a password and checks to see if it matches what the user put in the text field. If it does match then it will hide the Login page and another page will appear with a "Welcome" message. I have zero experience with text files, where do I put that block of code? I assume it would go in the ActionListener method and not the main method but i'm just lost. I just need a little push in the right direction. Here is what I have so far. Any help would be greatly appreciated. Thanks!
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
import javax.swing.*;
import java.awt.*;
/**
*/
public class PassWordFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new PassWordFrame();
frame.setTitle("Password Verification");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
First of all you initialize the listener (listener = new ClickListener()) after the call to #createComponents() method so this means you will add a null listener to the login button. So your constructor should look like this:
public PassWordFrame() {
listener = new ClickListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
Then, because you want to change the GUI with a welcome message, you should use a SwingWorker, a class designed to perform GUI-interaction tasks in a background thread. In the javadoc you can find nice examples, but here is also a good tutorial: Worker Threads and SwingWorker.
Below i write you only the listener implementation (using a swing worker):
class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
new SwingWorker<Boolean, Void>() {
#Override
protected Boolean doInBackground() throws Exception {
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
BufferedReader reader = new BufferedReader(new FileReader(userFile));
String user;
String pass;
try {
user = reader.readLine();
pass = reader.readLine();
}
catch (IOException e) {
//
// in case something is wrong with the file or his contents
// consider login failed
user = null;
pass = null;
//
// log the exception
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// ignore, nothing to do any more
}
}
if (usertext.getText().equals(user) && passtext.getText().equals(pass)) {
return true;
} else {
return false;
}
}
#Override
protected void done() {
boolean match;
try {
match = get();
}
//
// this is a learning example so
// mark as not matching
// and print exception to the standard error stream
catch (InterruptedException | ExecutionException e) {
match = false;
e.printStackTrace();
}
if (match) {
// show another page with a "Welcome" message
}
}
}.execute();
}
}
Another tip: don't add components to a JFrame, so replace this:
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
with:
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2, BorderLayout.WEST);
contentPane.add(panel3, BorderLayout.CENTER);
contentPane.add(panel4, BorderLayout.SOUTH);
setContentPane(contentPane);
assume there is a textfile named password.txt in g driver and it contain usename and password separate by # symbol.
like following
password#123
example code
package homework;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
String info = ReadFile();
System.out.println(info);
String[] split = info.split("#");
String uname=split[0];
String pass =split[1];
if(usertext.getText().equals(uname) && passtext.getText().equals(pass)){
instruct.setText("access granted");
}else{
instruct.setText("access denided");
}
}
});
}
private static String ReadFile(){
String line=null;
String text="";
try{
FileReader filereader=new FileReader(new File("G:\\password.txt"));
//FileReader filereader=new FileReader(new File(path));
BufferedReader bf=new BufferedReader(filereader);
while((line=bf.readLine()) !=null){
text=text+line;
}
bf.close();
}catch(Exception e){
e.printStackTrace();
}
return text;
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}

JDBC ODBC with MS Access issue

I want to store a record but don't know what to do.
When i start entering the details of a customer, at that time database connectivity is successfully created but I fail to store the data in the database.
The procedure is correct to create the database but I can't enter the details, what can I do?
Here is the code:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
//package p1;
public abstract class New_Customer extends JFrame implements ActionListener
{
JTextField textFieldId;
JTextField textFieldName;
JTextField textFieldContactNo;
JLabel l1;
JLabel l2;
JLabel l3;
JLabel l4;
JLabel l5;
JLabel l6;
JComboBox combo;
String course[] = {"Navakal","SandhyaKal","Pudhari","MidDay","Inqlab","BusinessLine","Mumbai Samachar","GujrajSamachar","KarnatakMalla","Vartahar","PunyaNagari"};
JButton b1;
JButton b2;
Container c = getContentPane();
New_Customer()
{
super("Shree DattaDigambar Samarth");
setBounds(140,250,777,555);
c.setLayout(null);
textFieldId = new JTextField();
textFieldName = new JTextField();
textFieldContactNo = new JTextField();
l1 = new JLabel("New Customer Entry");
l2 = new JLabel("Building No");
l3 = new JLabel("Customer Name");
l4 = new JLabel("Contact No");
l5 = new JLabel("Paper");
combo = new JComboBox(course);
l1.setBounds(10,10,340,20);
l2.setBounds(10,20,140,70);
l3.setBounds(110,20,140,70);
l4.setBounds(300,50,140,20);
l5.setBounds(400,50,140,20);
textFieldId.setBounds(10,70,70,20);
textFieldName.setBounds(110,70,180,20);
textFieldContactNo.setBounds(300,70,90,20);
combo.setBounds(400,70,130,20);
b1 = new JButton("Add paper");
b2 = new JButton("Ok");
b1.setBounds(10,100,100,20);
b2.setBounds(10,160,50,20);
c.add(combo);
c.add(b1);
c.add(b2);
c.add(l1);
c.add(l2);
c.add(l3);
c.add(l4);
c.add(l5);
c.add(textFieldId);
c.add(textFieldName);
c.add(textFieldContactNo);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
}
public static void main(String[] args)
{
New_Customer nc=new New_Customer() {};
}
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked the button");
if(e.getSource()==b1)
{
}
if(e.getSource()==b2)
{
try
{
Connection con;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:devendra");
try
{
java.sql.Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement(null);
ResultSet rs = ps.executeQuery("insert into Customer values(?,?,?,?)");
while(rs.next())
{
ps.setString(1,textFieldId.getText());
ps.setString(2,textFieldName.getText());
ps.setString(3,textFieldContactNo.getText());
ps.setString(4,combo.getName());
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
}
catch (ClassNotFoundException | SQLException ee)
{
System.out.println("Error:connection not created");
}
}
}
}
First of all to insert values in database, you should use executeUpdate() method.
And this method does not return any ResultSet.
So Change your code
PreparedStatement ps = con.prepareStatement("insert into Customer values(?,?,?,?)");
ps.setString(1,textFieldId.getText());
ps.setString(2,textFieldName.getText());
ps.setString(3,textFieldContactNo.getText());
ps.setString(4,combo.getName());
ps.executeUpdate();

Categories

Resources