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);
}
});
}
}
}
Related
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.
I'm working on my very first GUI app.
I have an ArrayList of the Parent Class Plant of which I have four child classes.
I have some JTextFields with some information and some JCheckBoxs with other information...
The JTextFields should be converted into Strings and the JCheckBoxs into boolean.
I need to add all of these components to an ArrayList and then display the list of the Plants.
How can I do that?
Example:
public class Flower extends Plant{
private boolean thorns;
private boolean smell;
public Flower(String name, String id, String color, boolean blnThorns, boolean blnSmell){
super(name, id, color);
thorns = blnThorns;
smell = blnSmell;
}
public boolean isThorns(){
return thorns;
}
public void setThorns(boolean blnThorns){
thorns = blnThorns;
}
public boolean isSmell(){
return smell;
}
public void setSmell(boolean blnSmell){
smell = blnSmell;
}
}
This is my ArrayList
ArrayList<Plant> plantList = new ArrayList<Plant>();
Here I try to add the parameters for the Flower:
private void addFlower(ArrayList<Plant> plantList){
//Adding window
JFrame addingFrame = new JFrame();
addingFrame.setTitle("Plant Database Interface");
addingFrame.setSize(600, 200);
addingFrame.setLocationRelativeTo(null);
addingFrame.setVisible(true);
//ADDING FRAME LAYOUT
addingFrame.setLayout(new BorderLayout());
//TRAITS
JPanel fields = new JPanel();
addingFrame.add(fields, BorderLayout.NORTH);
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField(15);
String name = nameField.getText();
JLabel idLabel = new JLabel("ID:");
JTextField idField = new JTextField(10);
String id = idField.getText();
JLabel colorLabel = new JLabel("Color:");
JTextField colorField = new JTextField(10);
String color = colorField.getText();
fields.add(nameLabel);
fields.add(nameField);
fields.add(idLabel);
fields.add(idField);
fields.add(colorLabel);
fields.add(colorField);
JPanel traits = new JPanel();
addingFrame.add(traits , BorderLayout.CENTER );
JCheckBox thornsBox = new JCheckBox("Thorns Present");
thornsBox.setSelected(false);
traits.add(thornsBox);
JCheckBox smellBox = new JCheckBox("Smell Present");
smellBox.setSelected(false);
traits.add(smellBox);
JPanel southPanel = new JPanel();
addingFrame.add(southPanel, BorderLayout.SOUTH);
JButton addPlantBtn = new JButton("Add Plant");
southPanel.add(addPlantBtn, BorderLayout.EAST);
JButton cancelBtn = new JButton("Cancel");
southPanel.add(cancelBtn, BorderLayout.WEST);
boolean blnThorns;
boolean blnSmell;
//I REALLY DON'T KNOW HOW TO DO THIS PART
thornsBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED){
blnThorns =true;
}
else{
blnThorns = false;
}
}
});
smellBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED){
blnSmell =true;
}
else{
blnSmell = false;
}
}
});
addPlantBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//plantList.add(new Flower(name, id, color, blnThorns, blnSmell)); //HOW TO DO????................
}
});
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addingFrame.dispatchEvent(new WindowEvent(addingFrame, WindowEvent.WINDOW_CLOSING));
}
});
}
Use your addPlantBtn ActionListener to gather the information you need when it's called
addPlantBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Flower flower = new Flower(nameField.getText(), idField.getText(), colorField.getText(), thornsBox.isSelected(), smellBox.isSelected());
plantList.add(flower);
You would, also, find it easier, if you created a dedicated JPanel, designed to gather the user details and generate a Flower when you requested it to (from the values of the fields). You could then use this panel on some kind of dialog when ever you needed it.
Have a look at How to Make Dialogs for more details
For example...
public class FlowerPane extends JPanel {
JTextField nameField = new JTextField(15);
JTextField idField = new JTextField(10);
JTextField colorField = new JTextField(10);
JCheckBox smellBox = new JCheckBox("Smell Present");
JCheckBox thornsBox = new JCheckBox("Thorns Present");
public FlowerPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(2, 2, 2, 2);
JLabel nameLabel = new JLabel("Name:");
JLabel idLabel = new JLabel("ID:");
JLabel colorLabel = new JLabel("Color:");
add(nameLabel, gbc);
gbc.gridy++;
add(idLabel, gbc);
gbc.gridy++;
add(idLabel, gbc);
gbc.gridx++;
gbc.gridy = 0;
add(nameField, gbc);
gbc.gridy++;
add(idField, gbc);
gbc.gridy++;
add(colorField, gbc);
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(thornsBox, gbc);
gbc.gridy++;
add(smellBox, gbc);
}
public Flower create() {
return new Flower(nameField.getText(), idField.getText(), colorField.getText(), thornsBox.isSelected(), smellBox.isSelected());
}
}
Which you could then use by doing something like...
FlowerPane flowerPane = new FlowerPane();
switch (JOptionPane.showConfirmDialog(null, flowerPane, "Flower", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) {
case JOptionPane.OK_OPTION:
Flower flower = flowerPane.create();
plantList.add(flower);
break;
}
Or add it to some other container
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
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.
My school project is to create a purchasing system for that I create a JPanel array to list out all the products information and also allow user to input something for every item. And I dont know how to get all the values from jtextfields by clicking one button. The actionPerformed() method always requires a final variable which is quite troublesome for me.
private JButton payBtn;
public void shoppingCartTab(Customer userIn){
contentPanel.removeAll();
bottomPanel.removeAll();
final Customer USER = userIn;
ArrayList<Product> pArray = new ArrayList<Product>();
pArray = loadCartFile.loadCartFile(userIn);
JLabel tabLabel = new JLabel("Shopping Cart");
JPanel cartItems = new JPanel();
cartItems.setLayout(new BoxLayout(cartItems, BoxLayout.Y_AXIS));
final JPanel CONSTANT_CART = cartItems;
JScrollPane scroller = new JScrollPane(cartItems);
if(pArray != null){
JPanel item[] = new JPanel[pArray.size()];
for(int i = 0; i< pArray.size(); i++){
item[i] = new JPanel();
final JPanel JPANEL_TO_DEL = item[i];
item[i].setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.weightx = 0.3;
item[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel icon_small = new JLabel(new ImageIcon("Icons\\" + pArray.get(i).getID() + "_small.jpg"));
JLabel itemID = new JLabel(pArray.get(i).getID());
final String CONSTANT_ID = pArray.get(i).getID();
JLabel itemName = new JLabel(pArray.get(i).getName());
JLabel itemPrice = new JLabel("$" + pArray.get(i).getPrice());
JPanel setQuantity = new JPanel();
JButton plusBtn = new JButton("+");plusBtn.setPreferredSize(new Dimension(45,30));
final JTextField QUANTITY = new JTextField("0");QUANTITY.setColumns(3);
QUANTITY.setPreferredSize(new Dimension(45,30));QUANTITY.setHorizontalAlignment(JTextField.CENTER);
JButton minusBtn = new JButton("-");minusBtn.setPreferredSize(new Dimension(45,30));
plusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())<100)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())+1));
}
});
minusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())>0)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())-1));
}
});
setQuantity.add(plusBtn);
setQuantity.add(QUANTITY);
setQuantity.add(minusBtn);
JButton delBtn = new JButton("Delete");
delBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure to remove this item from your cart?", "Confirm", JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
CONSTANT_CART.remove(JPANEL_TO_DEL);
revalidate();
repaint();
ShoppingCart.removeItem(USER, CONSTANT_ID);
}
}
});
gBC.gridx = 0;
gBC.gridy = 0;
item[i].add(icon_small,gBC);
gBC.gridx = 1;
gBC.gridy = 0;
item[i].add(itemID,gBC);
gBC.gridx = 2;
gBC.gridy = 0;
item[i].add(itemName,gBC);
gBC.gridx = 3;
gBC.gridy = 0;
item[i].add(itemPrice,gBC);
gBC.gridx = 4;
gBC.gridy = 0;
item[i].add(setQuantity,gBC);
gBC.gridx = 5;
gBC.gridy = 0;
item[i].add(delBtn,gBC);
cartItems.add(item[i]);
}
contentPanel.add(tabLabel);
contentPanel.add(scroller);
payBtn = new JButton("Pay");
bottomPanel.add(payBtn); payBtn.addActionListener(this);
}else{
JLabel emptyMsg = new JLabel("Your cart is empty!");
contentPanel.add(emptyMsg);
}
revalidate();
repaint();
}
One solution would be to create a type which extends JPanel, and exposes a public property, which when called returns the value stored in the JTextField. Something like:
public class TextFieldPanel extends JPanel {
private JTextField myTextField;
public TextFieldPanel()
{
//layout init code here
}
public String getText()
{
return myTextField.getText();
}
}
Then just use this class instead of a regular JPanel. Then when your button is clicked, iterate over each of the objects in your collection, and call getText() on them to get your values.