Am an Aptech student and we are doing a lot of projects and this is one.
Its about bank management and usage. This is my authentication class but i want to include a session:
public class AuthenticationFrame {
public static void display() {
JFrame frame = new JFrame("JSoft");
JPanel panel1 = new JPanel(new GridBagLayout());
panel1.setOpaque(true);
panel1.setBackground(Color.BLACK);
JPanel panel2 = new JPanel(new GridBagLayout());
panel2.setOpaque(true);
panel2.setBackground(Color.GRAY);
JPanel panel3 = new JPanel(new BorderLayout());
panel3.setOpaque(true);
panel3.setBackground(Color.GRAY);
GridBagConstraints cons = new GridBagConstraints();
cons.insets = new Insets(5,3,5,3);
JLabel label1 = new JLabel("Enter Your name");
label1.setForeground(Color.BLUE);
JTextField field1 = new JTextField();
field1.setPreferredSize(new Dimension(130,20));
field1.setForeground(Color.RED);
JLabel label2 = new JLabel("Enter Your pin");
label2.setForeground(Color.BLUE);
JPasswordField field2 = new JPasswordField();
field2.setPreferredSize(new Dimension(130,20));
field2.setForeground(Color.RED);
JLabel lb = new JLabel("CB Banking");
JButton Rdbtn = new JButton("Proceed");
JButton Bkbtn = new JButton("<<");
cons.gridx = 0;
cons.gridy = 0;
panel1.add(label1, cons);
cons.gridx = 1;
cons.gridy = 0;
panel1.add(field1, cons);
cons.gridx = 0;
cons.gridy = 2;
panel1.add(label2, cons);
cons.gridx = 1;
cons.gridy = 2;
panel1.add(field2, cons);
cons.gridx = 1;
cons.gridy = 3;
panel1.add(Rdbtn, cons);
panel2.add(lb);
panel3.add(Bkbtn, BorderLayout.WEST);
Rdbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception er){
JOptionPane.showMessageDialog(null, er.getMessage());
}
try{
if(field1.getText().equals("") && field2.getText().equals("")){
JOptionPane.showMessageDialog(null, "no empty fields");
}
else{
Connection CBcon = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankSystem_Db", "root", "elemie");
String username = field1.getText();
int pin = Integer.parseInt(field2.getText());
String query = "SELECT fname, pin FROM usertb WHERE fname = ? AND pin = ?";
PreparedStatement CBprep = CBcon.prepareStatement(query);
CBprep.setString(1, username);
CBprep.setInt(2, pin);
ResultSet CBrs = CBprep.executeQuery();
int CBresult = 0;
while(CBrs.next()){
CBresult+=1;
}
if(CBresult == 1){
UserFrame.monitor_three();
frame.dispose();
}
else{
JOptionPane.showMessageDialog(null,"Incorrect username or password");
field1.setText(null);
field2.setText(null);
}
CBrs.close();
CBprep.close();
}
}
catch(Exception er){
JOptionPane.showMessageDialog(null, er.getMessage());
}
}
});
Bkbtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ee){
Bsystem2.monitor_One();
frame.dispose();
}
});
frame.setSize(800, 500);
frame.setLocationRelativeTo ( null );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(panel1);
frame.getContentPane().add(panel2, BorderLayout.NORTH);
frame.getContentPane().add(panel3, BorderLayout.SOUTH);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
display();
}
});
}
}
This part should work like an atm. Get everything about the user in the database. Its suppose to open my userFrame class
Related
I have this main function (Class: DialogBoxForIt.java):
public void main(final SimpleCallback<HashMap<SPARAM, Object>> sr) {
if(mainwindow == null){
JFrame jf = new JFrame();
jf.setTitle(_T.PasswordEncrypt_title.val());
jf.setResizable(false);
jf.setIconImages(ResourceCenter.icons);
jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(), BoxLayout.Y_AXIS));
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
thiswindow = jf;
}
else{
JDialog jd = new JDialog(mainwindow);
jd.setModal(true);
jd.setTitle(_T.PasswordEncrypt_title.val());
jd.setResizable(false);
jd.setIconImages(ResourceCenter.icons);
jd.getContentPane().setLayout(new BoxLayout(jd.getContentPane(), BoxLayout.Y_AXIS));
jd.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
thiswindow = jd;
}
JPanel line1 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel line2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel lineok = new JPanel(new GridBagLayout());
JPanel line3 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
final JPanel lineopt = new JPanel(new FlowLayout(FlowLayout.RIGHT));
final JPasswordField tf = new JPasswordField();
tf.setPreferredSize(new Dimension(200, 25));
final JPasswordField tf2 = new JPasswordField();
tf2.setPreferredSize(new Dimension(200, 25));
final JTextField jtf = new JTextField(""+CryptoCodes.STANDARD_PBKDF2_ITERATIONS);
JButton b = new JButton("OK");
ActionListener act = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
char[] s1 = tf.getPassword();
char[] s2 = tf2.getPassword();
if(s1 == null || s2 == null || s1.length == 0 || s2.length == 0)
return;
int minlen = CryptoCodes.STANDARD_PBKDF2_PWLEN;
tf.setText(DUMMYTEXT);
tf2.setText(DUMMYTEXT);
tf.setText("");
tf2.setText("");
if(Arrays.equals(s1, s2) && s1.length >= minlen){
thiswindow.dispose();
CryptoUtils.kill(s2);
char[] passw = PasswordGenerator.GenerateRandomString(18,25,3,1,1,1).toCharArray();
String passwds = String.valueOf(passw);
try {
passwds = new String(passw);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
myParams.put(SPARAM.password, passwds.toCharArray());
System.out.println("let test -- "+String.valueOf((char[])myParams.get(SPARAM.password))) ;
if(lineopt.isVisible()){
String tmp = jtf.getText();
if(FilterNumbers.validate(tmp)) myParams.put(SPARAM.itcount, tmp);
}
sr.callbackValue(this, myParams);
}
else{
CryptoUtils.kill(s1);
CryptoUtils.kill(s2);
tf.requestFocus();
if(s1.length < minlen)
JOptionPane.showMessageDialog(thiswindow, _T.PasswordEncrypt_len.msg(minlen));
else
JOptionPane.showMessageDialog(thiswindow, _T.PasswordEncrypt_nomatch);
}
}
};
b.addActionListener(act);
tf.addActionListener(act);
tf2.addActionListener(act);
jtf.addActionListener(act);
JLabel jl = new JLabel(_T.PasswordEncrypt_label + ": ");
line1.add(jl);
line1.add(tf);
thiswindow.add(line1);
jl = new JLabel(_T.PasswordEncrypt_retype + ": ");
line2.add(jl);
line2.add(tf2);
thiswindow.add(line2);
b.setPreferredSize(new Dimension(200, 35));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
lineok.add(b, gbc);
thiswindow.add(lineok);
javax.swing.ToolTipManager.sharedInstance().setDismissDelay(7000);
((PlainDocument) jtf.getDocument()).setDocumentFilter(new FilterNumbers());
jtf.setPreferredSize(new Dimension(200, 25));
jtf.setToolTipText(_T.PasswordEncrypt_itcountdescr.val());
jl = new JLabel(_T.PasswordEncrypt_itcount + ": ");
jl.setToolTipText(_T.PasswordEncrypt_itcountdescr.val());
lineopt.add(jl);
lineopt.add(jtf);
final JButton jb = new JButton(new ImageIcon(ResourceCenter.optsup));
line3.add(jb);
thiswindow.add(line3);
thiswindow.add(lineopt);
lineopt.setVisible(false);
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(lineopt.isVisible()){
lineopt.setVisible(false);
jb.setIcon(new ImageIcon(ResourceCenter.optsup));
}
else{
lineopt.setVisible(true);
jb.setIcon(new ImageIcon(ResourceCenter.optsdown));
}
thiswindow.pack();
}
});
thiswindow.pack();
thiswindow.setLocationRelativeTo(mainwindow);
thiswindow.setVisible(true);
thiswindow.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
try {
tf.setText(DUMMYTEXT);
tf2.setText(DUMMYTEXT);
tf.setText("");
tf2.setText("");
} catch (Exception ex) {}
}
});
if(Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)){
JOptionPane.showMessageDialog(thiswindow, _T.Password_caps);
}
}
I call this main function from another class like this (The other class name: AppTest.java):
new DialogBoxForIt(currentSource).main(this);
I want get the passwds String of main function from this class.
How to do that please ?
What changes i must apport in order to get it there ?
You must know that passwds String contain a random generated password, and must be transfered to the other class for another use.
I tried to add public string (public String passwpub = "") and then inside the function (passwpub = passwds;), but can't get it from the other class.
If you have any idea will be highly appreciated.
Thank you !
So, I have a login JFrame which shows up when I run the code. The problem is if the user enters the correct userName and password this login frame needs to be disposed when the other frame is shown up but it doesn't. I tried dispose(), setVisible = false, but still no chance to be hidden or disposed.
class LoggingWindow extends JFrame {
static JFrame loginFrame = new JFrame();
JPanel loginPanel = new JPanel();
JTextField loginNameFld = new JTextField(10);
JPasswordField loginPassFld = new JPasswordField(10);
JTextField statusFld = new JTextField(11);
String userName = "user";
String password = "password";
//Initialize loginFrame
public static void initLoginFrame() {
JFrame loginWindow = new LoggingWindow();
//loginFrame.setTitle("\"Moflo Registration\"");
loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginWindow.setResizable(false);
loginWindow.setUndecorated(true);
loginWindow.setVisible(true);
loginWindow.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
loginWindow.setSize(new Dimension(220, 290));
loginWindow.setLocationRelativeTo(null);
loginWindow.pack();
LoggingWindow() {
loginFrame.add(loginPanel);
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints gbb = new GridBagConstraints();
gbb.insets = new Insets(1, 1, 1, 1);
gbb.anchor = GridBagConstraints.CENTER;
JPanel loginNameAndPasswordPanel = new JPanel();
loginPanel.add(loginNameAndPasswordPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 2;
loginNameAndPasswordPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(0,0,0,0);
JLabel loginNameLab = new JLabel("Нэр : ");
gbc.gridx = 0;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameLab, gbc);
JLabel loginPassLab = new JLabel("Нууц үг : ");
gbc.gridx = 0;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassLab, gbc);
loginNameFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameFld, gbc);
loginPassFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassFld, gbc);
statusFld.setEditable(false);
loginNameAndPasswordPanel.add(statusFld, gbc);
statusFld.setHorizontalAlignment(JTextField.CENTER);
JPanel buttonsPanel = new JPanel();
loginPanel.add(buttonsPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 3;
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gba = new GridBagConstraints();
gba.anchor = GridBagConstraints.LINE_END;
gba.insets = new Insets(2, 2, 2, 2);
JButton loginBtn = new JButton("Нэвтрэх");
gba.gridx = 0;
gba.gridy = 0;
buttonsPanel.add(loginBtn, gba);
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String name = loginNameFld.getText();
String pass = loginPassFld.getText();
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
initMainFrame();
loginFrame.dispose();
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " + showDate, " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
}
});
JButton closeBtn = new JButton(" Хаах ");
gba.gridx = 1;
gba.gridy = 0;
buttonsPanel.add(closeBtn, gba);
add(loginPanel);
closeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
//Main method
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initLoginFrame();
}
});
}
}
public class MainFrame extends JFrame {
//Initialzie mainFrame
public static void initMainFrame() {
JFrame mainFrame = new MainFrame();
mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
mainFrame.setMinimumSize(new Dimension(800, 600));
mainFrame.setLocationRelativeTo(null);
}
some, i think unimportant statements are not shown for the sake of brevity
I believe you confused "loginWindow" with "loginFrame". You try to use
loginFrame.dispose();
but your content is on loginWindow, not loginFrame.
I was able to get it to dispose the username window doing the following.
static JFrame loginWindow; <--- create as class variable, not local.
//loginFrame.add(loginPanel); <--- doesn't appear that this is actually used
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
MainFrame.initMainFrame();
//loginFrame.dispose(); <--- again, not used
loginWindow.dispose(); <--- want to dispose
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " , " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
You must also change this:
JFrame loginWindow = new LoggingWindow();
to:
loginWindow = new LoggingWindow();
You can always dispatch the "close" event to the JFrame object:
loginFrame.dispatchEvent(new WindowEvent(loginFrame, WindowEvent.WINDOW_CLOSING));
I definitely confused with loginFrame was indeed useless. I created a class variable: static JFrame loginWindow; but it results NullPointerException.
For instance, I want the program to run multiple times without stopping after somebody has pressed the "Please hit to finish process". However, when I do run the GUI method again, only the first panel shows up. Unsure of why this is happening.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class Hotel {
public static JFrame frame;
public static JPanel pan;
public static JPanel endPanel;
public static JPanel buttonPanel;
public static GridBagConstraints c;
public static GridBagConstraints f;
public static JButton econ;
public static Boolean openA = true;
public Hotel(){
Frame();
GUI();
}
public static void Frame(){
frame = new JFrame ("Kiosk");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(600,400);
}
public static void GUI (){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
frame.add(pan);
JLabel l2 = new JLabel("Please fill out your name and room number");
l2.setVisible(false);
pan.add(l2);
buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints GB = new GridBagConstraints();
JButton b1 = new JButton("Check in?");
c.gridx=0;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b1, c);
JButton b2 = new JButton("Check out?");
c.gridx=1;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b2, c);
frame.add(buttonPanel);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
buttonPanel.setVisible(false);
Checkin();
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
l2.setVisible(true);
b1.setVisible(false);
b2.setVisible(false);
}
});
}
public static void Checkin(){
JLabel name = new JLabel("What is your name?");
c.gridx=0;
c.gridy=0;
pan.add(name,c);
JLabel number = new JLabel("How many people in your party?");
c.gridx=0;
c.gridy=3;
pan.add(number,c);
JTextField namefield = new JTextField(20);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=0;
pan.add(namefield,c);
JTextField numberfield = new JTextField(2);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=3;
pan.add(numberfield,c);
JButton confirm = new JButton("Confirm");
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=4;
pan.add(confirm,c);
JPanel errorPanel = new JPanel(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
errorPanel.setVisible(false);
frame.add(errorPanel);
JButton econ = new JButton("Confirm");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=4;
errorPanel.add(econ,d);
JLabel error = new JLabel("Sorry you must fill in all the fields");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=0;
errorPanel.add(error,d);
confirm.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if((namefield.getText().equals("")) ||
(numberfield.getText().equals(""))){
pan.setVisible(false);
errorPanel.setVisible(true);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
errorPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
endPanel = new JPanel(new GridBagLayout());
f = new GridBagConstraints();
pan.setVisible(false);
frame.add(endPanel);
String hey = namefield.getText();
Memory(hey);
int people =0;
try {
people = Integer.parseInt(numberfield.getText());
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}
Rooms(people);
}
}
});
}
public static void Memory(String h){
ArrayList<String> Guest = new ArrayList<String>();
for(int x=0;x<Guest.size();x++){
if(Guest.get(x).equals(h)){
JLabel duplicate = new JLabel("Duplicate Name - Please refer
to the manager " + h);
JPanel dupPanel = new JPanel();
pan.setVisible(false);
dupPanel.setVisible(true);
frame.add(dupPanel);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dupPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
JLabel nameLab = new JLabel("Have a nice day " + h);
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(nameLab);
}
Guest.add(h);
}
}
public static void Rooms(Integer n){
JLabel roomLab = new JLabel("Sorry there are no rooms with that
occupany available");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(roomLab,f);
JButton restart = new JButton("Please hit to finish process");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=4;
endPanel.add(restart,f);
int x=0;
if(openA == true && n<2){
openA = false;
x=1;
}
switch(x){
case 1 : roomLab.setText("You have been assigned room A");
}
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
endPanel.setVisible(false);
GUI();
}
});
}
public static void main(String[] args) {
new Hotel();
}
}
If you want to cleanly restart a GUI, and make sure that the new GUI is 100% independent from the previous one, the best way is to dispose of the previous one, and create a brand new instance.
The biggest problem in your case is that all your fields and methods are static. This is wrong. You should typically have something like:
public class Hotel extends JFrame {
public JPanel pan;
...
public Hotel() {
super("Kiosk");
createGUI();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(600,400);
}
public void createGUI(){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
add(pan);
...
If you want to restart the GUI, it's then very simple:
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
new Hotel();
}
});
If you just want to reset a particular panel within the frame, you can remove it from its container, and add a new instance:
somepanel.remove(somesubpanel);
somepanel.add(createSubpanel());
Im making a desktop application in java and i need some help ,
Im using sql database to store all my information on the users , e.g UserName , Password , full name .
i have 2 frames , The first one is the login frame where the admin enters his username and password and if it matches with the details on sql database then it will take him to the next frame which is the admin panel , now i want that the admins full name should show on the top left corner of the second frame(which is the admin panel) in the NorthPanel,
this is my codes for both frames , please help
How do i take the name of the admin that logged in from the sql database and show it in the admin panel?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.*;
import java.sql.*;
import java.awt.*;
import javax.swing.*
public class Login extends JFrame implements ActionListener, KeyListener, FocusListener, WindowListener
{
JPanel UserPanel,NorthPanel;
JLabel UserId,UserPassword;
JLabel LblFrgtPass;
JTextField TxtUser;
JPasswordField TxtUserPass;
JButton BtnLogin;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
boolean flag=false;
public Login()
{
add(GetUserPanel(), BorderLayout.CENTER);
add(GetNorthPanel(), BorderLayout.NORTH);
addWindowListener(this);
}
public boolean GetConnection()
{
flag=false;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:Project");
stmt=con.createStatement();
flag=true;
}catch(Exception ex)
{
ex.printStackTrace();
flag=false;
}
return flag;
}
public boolean CloseConnection()
{
flag=false;
try
{
if(con!=null)
{
con.close();
flag=true;
}
}catch(Exception ex)
{
flag=false;
}
return flag;
}
public ResultSet GetRecords(String sql)
{
rs=null;
try
{
rs=stmt.executeQuery(sql);
}catch(Exception ex)
{
rs=null;
}
return rs;
}
JPanel GetNorthPanel()
{
NorthPanel = new JPanel();
NorthPanel.setLayout(new FlowLayout());
ImageIcon titleIcon = new ImageIcon("titleicon.png");
JLabel title = new JLabel(titleIcon);
NorthPanel.add(title);
NorthPanel.setBackground(Color.white);
return NorthPanel;
}
JLabel GetLblForgetPassword()
{
LblFrgtPass = new JLabel("Forgot Password ? ");
return LblFrgtPass;
}
JPanel GetUserPanel()
{
UserPanel=new JPanel();
UserPanel.setLayout(new GridBagLayout());
UserPanel.setBackground(Color.WHITE);
GridBagConstraints GbcUserId = new GridBagConstraints();
GbcUserId.gridx=1;
GbcUserId.gridy=3;
GbcUserId.fill=GridBagConstraints.BOTH;
GbcUserId.insets = new Insets(10, 70, 0, 0);
UserPanel.add(GetUserId(),GbcUserId);
GridBagConstraints GbcTxtUser = new GridBagConstraints();
GbcTxtUser.gridx=2;
GbcTxtUser.gridy=3;
GbcTxtUser.insets = new Insets(10, 40, 0, 0);
UserPanel.add(GetTxtUser(),GbcTxtUser);
GridBagConstraints GbcUserPassword = new GridBagConstraints();
GbcUserPassword.gridx=1;
GbcUserPassword.gridy=4;
GbcUserPassword.fill=GridBagConstraints.BOTH;
GbcUserPassword.insets = new Insets(10, 70, 0, 0);
UserPanel.add(GetUserPassword(),GbcUserPassword);
GridBagConstraints GbcTxtUserPass = new GridBagConstraints();
GbcTxtUserPass.gridx=2;
GbcTxtUserPass.gridy=4;
GbcTxtUserPass.insets = new Insets(10, 40, 0, 0);
UserPanel.add(GetTxtUserPass(),GbcTxtUserPass);
GridBagConstraints GbcBtnLogin = new GridBagConstraints();
GbcBtnLogin.gridx=2;
GbcBtnLogin.gridy=5;
GbcBtnLogin.insets = new Insets(50, 50, 20, 20);
UserPanel.add(GetBtnLogin(),GbcBtnLogin);
GridBagConstraints GbcLblFrgtPass = new GridBagConstraints();
GbcLblFrgtPass.gridx=3;
GbcLblFrgtPass.gridy=5;
GbcLblFrgtPass.insets = new Insets(50, 0, 20, 20);
UserPanel.add(GetLblFrgtPass(),GbcLblFrgtPass);
return UserPanel;
}
JLabel GetUserId()
{
UserId = new JLabel("User Id : ");
UserId.setFont(new Font("Bookman Old Style", Font.PLAIN, 14));
return UserId;
}
JTextField GetTxtUser()
{
TxtUser = new JTextField(10);
TxtUser.addKeyListener(this);
TxtUser.addFocusListener(this);
return TxtUser;
}
JLabel GetUserPassword()
{
UserPassword = new JLabel("Password : ");
UserPassword.setFont(new Font("Bookman Old Style", Font.PLAIN, 14));
return UserPassword;
}
JPasswordField GetTxtUserPass()
{
TxtUserPass = new JPasswordField(10);
TxtUserPass.addKeyListener(this);
TxtUserPass.addFocusListener(this);
return TxtUserPass;
}
JLabel GetLblFrgtPass()
{
LblFrgtPass = new JLabel("Forgot Passord ?");
return LblFrgtPass;
}
JButton GetBtnLogin()
{
BtnLogin = new JButton(" LogIn ");
//Project1 p = new Project1();
BtnLogin.addActionListener(this);
BtnLogin.setFont(new Font("Bookman Old Style", Font.PLAIN, 14));
BtnLogin.registerKeyboardAction(BtnLogin.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);
BtnLogin.registerKeyboardAction(BtnLogin.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);
return BtnLogin;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==BtnLogin)
{
String User_Id = TxtUser.getText().trim();
String User_Pass = TxtUserPass.getText().trim();
String sql = "Select * from users where UserId = '"+User_Id+"' and Password= '"+User_Pass+"'";
if(GetConnection()==true)
{
try
{
rs =GetRecords(sql);
int count = 0;
String usertype="";
while(rs.next())
{
count = count + 1;
usertype=rs.getString(3);
}
if(count ==1)
{
if(usertype.equalsIgnoreCase("student"))
{
JOptionPane.showMessageDialog(null, "Student Frame");
}
else if(usertype.equalsIgnoreCase("teacher"))
{
JOptionPane.showMessageDialog(null, "Teacher Frame");
}
else if(usertype.equalsIgnoreCase("admin"))
{
Admin frame=new Admin();
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
dispose();
}
else
{
JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
catch(Exception ex)
{
//ex.printStackTrace();
System.err.println("ERROR2");
}
}
else
{
System.out.println("Not Connected");
}
}
}
public void keyTyped(KeyEvent ex)
{
//ASCII :American Standard Code for Information Interchange
}
public void keyPressed(KeyEvent ex)
{
System.out.println(ex.getKeyCode());
if(ex.getKeyCode()==10 && ex.getSource()==TxtUser)
{
TxtUserPass.requestFocus();
}
else if(ex.getKeyCode()==10 && ex.getSource()==TxtUserPass)
{
BtnLogin.requestFocus();
}
else if(ex.getKeyCode()==10 && ex.getSource()==BtnLogin)
{
JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
public void keyReleased(KeyEvent ex)
{
if(ex.getKeyCode()==10 && ex.getSource()==TxtUserPass)
{
// JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
public void focusGained(FocusEvent ex)
{
if(ex.getSource()==TxtUser)
{
TxtUser.setBackground(Color.white);
}
else if(ex.getSource()==TxtUserPass)
{
TxtUserPass.setBackground(Color.white);
}
}
public void focusLost(FocusEvent ex)
{
if(ex.getSource()==TxtUser)
{
TxtUser.setBackground(Color.white);
}
else if(ex.getSource()==TxtUserPass)
{
TxtUserPass.setBackground(Color.white);
}
}
public void windowActivated(WindowEvent ex)
{
}
public void windowDeactivated(WindowEvent ex)
{
}
public void windowIconified(WindowEvent ex)
{
}
public void windowDeiconified(WindowEvent ex)
{
}
public void windowClosing(WindowEvent ex)
{
//JOptionPane.showMessageDialog(null,"GoodBye","Exit LogIn",JOptionPane.PLAIN_MESSAGE);
}
public void windowClosed(WindowEvent ex)
{
}
public void windowOpened(WindowEvent ex)
{
}
public static void main(String[] args)
{
Login Frame = new Login();
Frame.setResizable(false);
Frame.setSize(600,400);
Frame.setLocationRelativeTo(null);
Frame.setVisible(true);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The code below is the second frame
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class Admin extends Login {
JFrame frame = new JFrame("Admin");
JPanel panel;
JPanel nPanel;
JLabel logOut;
JLabel UserName;
JButton btn1;
JButton btn2;
JButton btn3;
JButton btn4;
JButton btn5;
JButton btn6;
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
boolean flag = false;
//****************MAIN CONSTRUCTOR******************************************
public Admin(){
add(GetNPanel(), BorderLayout.NORTH);
add(GetCPanel(), BorderLayout.CENTER);
}
//****************SQL CONNECTION********************************************
public boolean GetConnection(){
flag = false;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Project");
//System.out.println("Connected");
stmt = con.createStatement();
flag=true;
}
catch(Exception ex){
ex.printStackTrace();
flag = false;
}
return flag;
}
//****************CENTER PANEL**********************************************
JPanel GetCPanel(){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//gbc.insets = new Insets(1, 1, 1, 1); //cell padding
gbc.fill = GridBagConstraints.BOTH; //fill cell area
gbc.weightx = 1; // fill horizontal cell area
gbc.weighty = 1; //fill vertical cell area
//btn1
btn1 = new JButton(new ImageIcon("teacher.png"));
btn1.setToolTipText("Add / Edit / Remove Teachers");
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(btn1, gbc);
//btn2
btn2 = new JButton(new ImageIcon("student.png"));
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(btn2, gbc);
//btn3
btn3 = new JButton(new ImageIcon("notice.png"));
gbc.gridx = 2;
gbc.gridy = 0;
panel.add(btn3, gbc);
//btn4
btn4 = new JButton(new ImageIcon("complaints.png"));
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(btn4, gbc);
//btn5
btn5 = new JButton(new ImageIcon("messages.png"));
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(btn5, gbc);
//btn6
btn6 = new JButton(new ImageIcon("password.png"));
gbc.gridx = 2;
gbc.gridy = 1;
panel.add(btn6, gbc);
return panel;
}
JPanel GetNPanel()
{
nPanel = new JPanel();
return nPanel;
}
//****************NORTH PANEL***********************************************
public static void main(String[] args)
{
new Admin();
Admin frame = new Admin();
//FRAME
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
}
You are extending your AdminPanel Frame from Login frame. What you can do is create an instance variable in your Login frame and store the value of Full Name of user to it if the login is successful.
As the AdminPanel inherits Login Frame, so it will automatically get the value of Full name of user. Then you can take any JLabel in your AdminPanel in the left corner and set text the value of instance variable there.
I would have a setName method that takes a string variable and then set the text of the label.
Public void setName(String name){
Label.setText(name)
}
Then I would call the method upon the login being successful.
I'm working on this application and I just can't get the GUI to display properly. I'm using FlowLayout, and everything just looks all jumbled (any other layout looks even worse). If there were just some way to add a horizontal rule between sections, that would work, but nothing I tried works.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class ConnectToDB implements ActionListener {
public static void main(String[] args){
//GUI STUFF
//constants
final int windowX = 640; //pixels
final int windowY = 655; //pixels
final int fieldX = 20; //characters
final FlowLayout LAYOUT_STYLE = new FlowLayout();
//window
JFrame window = new JFrame("Mike's MySQL GUI Client");
//Connection Details
JLabel enterInfo = new JLabel("Enter Connection Details: ");
JLabel driver = new JLabel("Database Driver: ");
JTextField driverText = new JTextField(fieldX);
JLabel dburl = new JLabel("Database URL: ");
JTextField dburlText = new JTextField(fieldX);
JLabel dbuser = new JLabel("Username: ");
JTextField dbuserText = new JTextField(fieldX);
JLabel dbpass = new JLabel("Password: ");
JTextField dbpassText = new JTextField(fieldX);
//Enter a SQL Command
JLabel enterSQL = new JLabel("Enter a SQL Command:");
JTextArea enterSQLText = new JTextArea(10, 30);
//Connection Status and Command Buttons
JLabel connectionStatus = new JLabel ("No Connection Now");
JButton connectButton = new JButton("Connect");
JButton executeButton = new JButton("Execute SQL Command");
JButton clearCommandButton = new JButton("Clear Command");
//SQL Execution Result
JLabel executionResult = new JLabel("SQL Execution Result:");
JButton clearResultsButton = new JButton("Clear Results");
JTextArea executionResultText = new JTextArea(20, 50);
//Configure GUI
window.setSize(windowX, windowY);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
driverText.setEditable(false);
dburlText.setEditable(false);
dbuserText.setEditable(false);
dbpassText.setEditable(false);
executionResultText.setEditable(false);
//Register Event Listeners
connectButton.addActionListener(null);
executeButton.addActionListener(null);
clearCommandButton.addActionListener(null);
clearResultsButton.addActionListener(null);
//Construct Container
Container c = window.getContentPane();
c.setLayout(LAYOUT_STYLE);
c.add(enterInfo);
c.add(driver);
c.add(driverText);
c.add(dburl);
c.add(dburlText);
c.add(dbuser);
c.add(dbuserText);
c.add(dbpass);
c.add(dbpassText);
c.add(connectionStatus);
c.add(connectButton);
c.add(enterSQL);
c.add(enterSQLText);
c.add(executeButton);
c.add(clearCommandButton);
c.add(new JSeparator(SwingConstants.VERTICAL));
c.add(executionResult);
c.add(clearResultsButton);
c.add(executionResultText);
window.setVisible(true);//END GUI STUFF
//DB Connection details
System.out.println("Attempting to connect to database...");
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "project3";
String DBdriver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "OMGnpw=-0";
driverText.setText(DBdriver);
dburlText.setText(url);
dbuserText.setText(userName);
dbpassText.setText(password);
try
{
//Connect to DB and notify user
Class.forName(DBdriver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
/*>>>>>>Do everything you need to do while connected to DB<<<<<<*/
//HOW TO EXECUTE A STATEMENT AND PRINT IT
//Create a statement
Statement statement = conn.createStatement();
//Execute a statement
ResultSet resultSet = statement.executeQuery("SELECT * FROM riders");
//Process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
System.out.printf("%20s\t", metaData.getColumnName(i));
}
System.out.println();
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
System.out.printf("%20s\t", resultSet.getObject(i));
}
System.out.println();
}
/*>>>>>>Finish DB activities<<<<<<*/
//Disconnect from DB
conn.close();
System.out.printf("Disconnected from database");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
System.out.println("Button Works!");
}
}
I may need to use a different layout, but FlowLayout is the only one I'm familiar with. Can anyone suggest an easy fix?
Try a box layout. And add some panels to it. Make the panels flow layout and put a pair of label and textfield in each panel
|-----container with box layout-----|
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]label texfield]
panel[[flow]sqltextfields]
panel[[flow]buttons]
|-----------------------------------|
and near the bottom put your sql textfields and buttons
http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
So, we a little playing around you can achieve this...
This uses a combination of card layout, border layout, grid bag layout and flow layout
Connection Pane...
Query Pane
public class TestLayout11 {
public static void main(String[] args) {
new TestLayout11();
}
public TestLayout11() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SQLPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class SQLPane extends JPanel {
private ConnectionPane connectionPane;
private QueryPane queryPane;
public SQLPane() {
setLayout(new CardLayout(8, 8));
connectionPane = new ConnectionPane();
connectionPane.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Perform login...
((CardLayout) getLayout()).show(SQLPane.this, "query");
}
});
queryPane = new QueryPane();
add(connectionPane, "connection");
add(queryPane, "query");
((CardLayout) getLayout()).show(this, "connection");
}
}
public static class ConnectionPane extends JPanel {
protected static final int FIELD_CHARACTER_WIDTH = 20; //characters
private JButton connectButton;
private JTextField driverText;
private JTextField dburlText;
private JTextField dbuserText;
private JTextField dbpassText;
public ConnectionPane() {
JLabel enterInfo = new JLabel("Enter Connection Details: ");
JLabel driver = new JLabel("Database Driver: ");
driverText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dburl = new JLabel("Database URL: ");
dburlText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dbuser = new JLabel("Username: ");
dbuserText = new JTextField(FIELD_CHARACTER_WIDTH);
JLabel dbpass = new JLabel("Password: ");
dbpassText = new JTextField(FIELD_CHARACTER_WIDTH);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = 2;
gbc.insets = new Insets(2, 2, 2, 2);
add(enterInfo, gbc);
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = 1;
gbc.gridy++;
add(driver, gbc);
gbc.gridy++;
add(dburl, gbc);
gbc.gridy++;
add(dbuser, gbc);
gbc.gridy++;
add(dbpass, gbc);
gbc.gridx++;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
add(driverText, gbc);
gbc.gridy++;
add(dburlText, gbc);
gbc.gridy++;
add(dbuserText, gbc);
gbc.gridy++;
add(dbpassText, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 2;
connectButton = new JButton("Connect");
add(connectButton, gbc);
}
public void addActionListener(ActionListener listener) {
connectButton.addActionListener(listener);
}
public void removeActionListener(ActionListener listener) {
connectButton.removeActionListener(listener);
}
}
public static class QueryPane extends JPanel {
private JTextArea enterSQLText;
public QueryPane() {
JLabel enterSQL = new JLabel("Enter a SQL Command:");
enterSQLText = new JTextArea(10, 30);
JButton clearResultsButton = new JButton("Clear Results");
JButton executeButton = new JButton("Execute SQL Command");
setLayout(new BorderLayout());
add(enterSQL, BorderLayout.NORTH);
add(new JScrollPane(enterSQLText));
JPanel buttons = new JPanel();
buttons.add(executeButton);
buttons.add(clearResultsButton);
add(buttons, BorderLayout.SOUTH);
executeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute query...
String text = enterSQLText.getText();
enterSQLText.setText("I've being executed....");
}
});
clearResultsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
enterSQLText.setText(null);
}
});
}
}
}