Using pure java, I would like to have a player press a JButton, have a text box pop up which they can type in, and then have a certain action happen when the player presses "Enter".
How could I do this?
I have not yet attempted this because I do not know where to start, however my current code is
package Joehot200;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main extends JFrame {
static boolean start = false;
private JPanel contentPane;
/**
* Launch the application.
*/
static Main frame = null;
String version = "0.4";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Main();
frame.setVisible(true);
frame.setTitle("Privateers");
} catch (Exception e) {
e.printStackTrace();
}
}
});
TerrainDemo.startGame();
}
boolean cantConnect = false;
/**
* Create the frame.
*/
public Main() {
setExtendedState(JFrame.MAXIMIZED_BOTH);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
final JButton btnEnterBattlefield = new JButton("Enter battlefield!");
btnEnterBattlefield.setForeground(Color.red);
//btnEnterBattlefield.setBackground(Color.green);
//btnEnterBattlefield.setOpaque(true);
menuBar.add(btnEnterBattlefield);
btnEnterBattlefield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println(new File(System.getProperty("user.dir") + "res/images/heightmap.bmp").getAbsolutePath());
//System.out.println("You clicked the button");
if (cantConnect){
btnEnterBattlefield.setText("Unable to connect to the server!");
}else{
btnEnterBattlefield.setText("Connecting to server...");
}
start = true;
}
});
//JMenu mnLogIn = new JMenu("Log in");
JMenu mnLogIn = new JMenu("Currently useless button");
mnLogIn.setForeground(Color.magenta);
menuBar.add(mnLogIn);
JButton btnLogIntoGame = new JButton("Log into game.");
mnLogIn.add(btnLogIntoGame);
JButton btnRegisterNewAccount = new JButton("Register new account");
mnLogIn.add(btnRegisterNewAccount);
final JButton btnGoToWebsite = new JButton("We currently do not but soon will have a website.");
btnGoToWebsite.setForeground(Color.BLUE);
//btnGoToWebsite = new JButton("Go to website.");
btnGoToWebsite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("Going to website!");
try {
java.awt.Desktop.getDesktop().browse(new URI("www.endcraft.net/none"));
} catch (Exception e1) {
btnGoToWebsite.setText("Error going to website!");
}
}
});
menuBar.add(btnGoToWebsite);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
FlowLayout flowLayout = (FlowLayout) contentPane.getLayout();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
ImageIcon icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
Image img = icon.getImage() ;
Image newimg = img.getScaledInstance(this.getWidth()*3, this.getHeight()*3, java.awt.Image.SCALE_SMOOTH ) ;
icon = new ImageIcon( newimg );
JLabel background=new JLabel(icon);
getContentPane().add(background);
background.setLayout(new FlowLayout());
//JProgressBar progressBar = new JProgressBar();
//contentPane.add(progressBar);
//JMenu mnWelcomeToA = new JMenu("Welcome to a pirate game!");
//contentPane.add(mnWelcomeToA);
//JButton btnStartGame = new JButton("Start game");
//mnWelcomeToA.add(btnStartGame);
//JSplitPane splitPane = new JSplitPane();
//mnWelcomeToA.add(splitPane);
//JButton btnRegister = new JButton("Register");
//splitPane.setLeftComponent(btnRegister);
//JButton btnLogin = new JButton("Login");
//splitPane.setRightComponent(btnLogin);
}
}
It is the "Register account" and "Log into game" button that I would like to have the above described action happen on.
Would be great if someone could tell me how to do this.
If you decide to implement a new frame (not best practice), with a new panel, and the JTextField or JTextArea within, you must bind a listener to the button that calls setVisible() on the newly created frame..
For example:
public void actionPerformed(ActionEvent e) {
yourFrame.setVisible(true);
}
Further, you could create the frame everytime the button is clicked, within the actionPerformed method aswell, however this is also not best practice..
A better alternative may be to implement a JOptionPane, see here or here..
Related
I have a JFrame with a button labelled as "order". When that button is clicked, a dialog box comes up. This dialog box is supposed to show a summary of items that are ordered as a text view. I thought of having a string as a way to view the order, but that did not work out...
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import javax.swing.JRadioButton;
public class PizzaOrder3 {
PizzaOrder3() {
JFrame frame = new JFrame();
JButton order = new JButton("Order");
JPanel panel1 = new JPanel();
panel1.add(order);
frame.getContentPane().add(panel1);
panel1.setBounds(350,632,110,40);
panel1.setOpaque(false);
//Action listener for showing summary of the order
order.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JDialog d = new JDialog(frame, "Hello", true);
//Where the coding for text view is meant to go
d.setSize(400, 300);
d.setVisible(true);
}
});
frame.setLayout(null);
frame.setSize(600, 700);
frame.getContentPane().setBackground(new Color(40, 80, 120));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
PizzaOrder3 PizzaOrder3 = new PizzaOrder3();
}
}
Hi im currently working on a program but I need to be able to change the class (so that the frame changes) with just the click of a menu tab.
I would like someone to modify this to get my to class2.java
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
class 1.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class circle_ac {
private JFrame frame;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
circle_ac window = new circle_ac();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public circle_ac() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame = new JFrame();
frame.setResizable(true);
frame.setBounds(1000, 1000, 2250, 1000);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,frame1);
this.revalidate();
this.repaint();
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
/*setup calculate button*/
JButton btnCalculate = new JButton("calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*setup calculations*/
double rad;
double ans1;
double ans2;
double pi=3.1415926535897932384626433832795;
try {
rad=Double.parseDouble(txtRadius.getText()) ;
ans1= pi*(rad*rad);
ans2= 2*pi*rad;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(25);
txtTheAreaOf.setText("The Area Is "+df.format(ans1));
txtTheCircumfrenceOf.setText("The Circumference Is "+df.format(ans2) );
/*setup error message*/
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please Enter Valid Radius");
}
}
});
/*initialize calculate button*/
btnCalculate.setFont(new Font("Tahoma", Font.PLAIN, 60));
btnCalculate.setBackground(new Color(227, 227, 227));
btnCalculate.setForeground(Color.BLACK);
frame.getContentPane().add(btnCalculate, BorderLayout.SOUTH);
/*setup Radius text box*/
txtRadius = new JTextField();
txtRadius.setFont(new Font("Tahoma", Font.PLAIN, 55));
txtRadius.setCursor(null);
txtRadius.setInputVerifier(null);
txtRadius.setText(" Enter The Radius");
txtRadius.setBackground(SystemColor.controlHighlight);
frame.getContentPane().add(txtRadius, BorderLayout.CENTER);
txtRadius.setColumns(10);
/*setup Area text box*/
txtTheAreaOf = new JTextField();
txtTheAreaOf.setEditable(false);
txtTheAreaOf.setText("The Area Of The Circle Is ");
txtTheAreaOf.setBackground(SystemColor.control);
txtTheAreaOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
frame.getContentPane().add(txtTheAreaOf, BorderLayout.WEST);
/*setup Circumference text box*/
txtTheCircumfrenceOf =new JTextField();
txtTheAreaOf.setEditable(false);
txtTheCircumfrenceOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
txtTheCircumfrenceOf.setText("The Circumfrence Of The Circle Is ");
txtTheCircumfrenceOf.setBackground(SystemColor.control);
frame.getContentPane().add((Component) txtTheCircumfrenceOf, BorderLayout.EAST);
}
}
class2.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class area_c {
private JFrame frame1;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
area_c window = new area_c();
window.frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public area_c() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame1 = new JFrame();
frame1.setResizable(true);
frame1.setBounds(1000, 1000, 2250, 1000);
frame1.pack();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
frame1.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame1.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
System.out.println("Hello World!");
I need the menu tab to change it from class1.java to class2.java with an action listener.
is this possible, if so how do I do it.
I recommend to implement your two classes as JPanels. Then you can add these JPanels to your JFrame. Have a look at this small example, that shows the principle in a short and quick way. Hope it helps:
package test;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class TestFrame extends JFrame {
private Container contentPane;
private JPanel panel1,panel2;
public TestFrame() {
super("Test");
this.setJMenuBar(menubar());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = this.getContentPane();
createPanels();
contentPane.setLayout(new BorderLayout());
this.add(BorderLayout.CENTER,panel1);
this.pack();
this.setVisible(true);
}
private JMenuBar menubar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem m1 =new JMenuItem("Selection 1");
JMenuItem m2 =new JMenuItem("Selection 2");
m1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
refresh();
}
});
m2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
refresh();
}
});
fileMenu.add(m1);
fileMenu.add(m2);
menubar.add(fileMenu);
return menubar;
}
private void refresh() {
this.revalidate();
this.repaint();
}
private void createPanels() {
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(BorderLayout.CENTER,new JLabel("Hello World"));
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
panel2.add(BorderLayout.CENTER,new JLabel("Goodbye World"));
}
public static void main(String[] args) {
TestFrame t = new TestFrame();
}
}
In most of the IDE's, when you right-click on the Button in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
When you are in one frame, you can set it's visibility off to hide it, like this:
this.setVisible(false);
And you can create the object of another class (of the other frame where you want to redirect) and set it's visibility on to display it, like this:
area_c of = new area_c();
of.setVisible(true);
So, you will be transitioning from one class to another of different frames.
You can achieve the same using the object of JMenuItem object:
class1 = new JPanel();
class1.setLayout(new BorderLayout());
class1.add(BorderLayout.CENTER,new JLabel("Label_Name"));
class2 = new JPanel();
class2.setLayout(new BorderLayout());
class2.add(BorderLayout.CENTER,new JLabel("Label_Name"));
JMenuItem JMenuItemObject1 =new JMenuItem("Class 1");
JMenuItem JMenuItemObject2 =new JMenuItem("Class 2");
JMenuItemObject1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
this.revalidate();
this.repaint();
}
});
JMenuItemObject2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
this.revalidate();
this.repaint();
}
});
area.add(JMenuItemObject1);
area.add(JMenuItemObject2);
menubar.add(area);
I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...
This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().
I created a main window where the user will click if he's a system admin, an employee or a member a finance, one of my problem is that they are not centered in the screen, how would I do that? Second, I want it to work like, when I click the Finance Button, the Mainwindow Will close and it will bring me to my log in screen, how would I do that?? Here's my MainWindow Code
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JEditorPane;
import javax.swing.SpringLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFormattedTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow frame = new MainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 333, 191);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JButton btnNewButton = new JButton("Employee");
contentPane.add(btnNewButton, BorderLayout.WEST);
JButton btnNewButton_1 = new JButton("Finance");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
}
});
contentPane.add(btnNewButton_1, BorderLayout.CENTER);
JButton btnNewButton_2 = new JButton("System Admin");
contentPane.add(btnNewButton_2, BorderLayout.EAST);
JLabel lblNewLabel = new JLabel("Welcome");
contentPane.add(lblNewLabel, BorderLayout.NORTH);
}
}
here is my code for a login form
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Login extends JFrame {
private JLabel label1, label2;
private JButton submit;
private JTextField textfield1;
private JPasswordField passfield;
private JPanel panel;
public Login() {
setSize(300, 100);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
label1 = new JLabel("User ID:");
textfield1 = new JTextField(15);
label2 = new JLabel("Password:");
passfield = new JPasswordField(15);
submit = new JButton("Submit");
panel = new JPanel(new GridLayout(3, 1));
panel.add(label1);
panel.add(textfield1);
panel.add(label2);
panel.add(passfield);
panel.add(submit);
add(panel, BorderLayout.CENTER);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}// end login constructor
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String user = textfield1.getText();
char[] passChars = passfield.getPassword();
Connection conn = Jdbc.dbConn();
PreparedStatement ps = null;
ResultSet rs = null;
String pass = new String(passChars);
if (passChars != null) {
String sql = "SELECT employee_ID, employee_password FROM user WHERE employee_ID = ? AND employee_password = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null,"Welcome! "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}// end actionPerformed
}// End ButtonHandler
}// End of class
}
Some suggestions:
Do not use setBounds() for MainWindow (JFrame). Use some Layout and at end use pack(). If you want to set size manually then you can also use setSize().
To close current window and open Login frame add setVisible(false) or dispose() and create Login object and make it visible.
For making frame to be at center try setLocationRelativeTo(null);.
Do not use variable names like label1, textFiled2, btnNewButton, etc... Use proper names for proper variable that reflects it usage.
Example for point 2:
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
Login login = new Login();
}
});
You need to carefully choose a layout manager to suit your needs. You are currently using BorderLayout which doesn't seem to do what you want.
Try adding your three buttons to a JPanel and then setting that panel as your frame's content pane. JPanel uses FlowLayout by default which should do the trick.