How to create a lock with user input on JPanel? - java

I am a beginner at Java so if there are some simple problems that are in my code please tell me. Thank you in advance!
In Java I have a "login" JPanel which I want the user to enter in a password they like, then have them enter the password on another JPanel (the same password that they created). If it is right and they click the login button again then it would bring them to a screen which says "Welcome" and if they don't, then a screen that says "False. Error". However something on Eclipse is saying that something is wrong and that I can't run it. Please tell me where I went wrong and if you can tell me how to fix it. I would appreciate it!
There are two problems with my code. Both of them are "Syntax error, insert "}" to complete ClassBody" but every time I add one in, it says "Syntax error on token "}", delete this token"
Here is my code:
package Button;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.util.Scanner;
#SuppressWarnings("unused")
public class Login {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("Pasword");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JButton loginButton = new JButton("Create");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
#SuppressWarnings("resource")
Scanner user = new Scanner (System.in);
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
loginButton.setVisible(false);
registerButton.setVisible(false);
userText.setVisible(false);
userLabel.setVisible(false);
JTextField userText1 = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText1);
JButton loginButton1 = new JButton("Password");
loginButton1.setBounds(10, 80, 80, 25);
panel.add(loginButton1);
});
loginButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
String name = userText.getText();
String accept = name;
String good;
if (accept.equals(name)) {
good = "Welcome";
} else {
good = "False. Error";
}
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
label1.setVisible(true);
panel.add(label1);
}
});
}

loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//...
}
);
Is missing a closing embrace (}) - one thing you will learn to do is count brackets and braces
It should look more like
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//...
}
});
registerButton and loginButton1 are undefined and you seem to be missing closing brace (}) at the end of the file as well
I would also highly recommend that you make use of layout managers, they will make life a lot easier for you. I'd recommend starting with How to use CardLayout as it will allow you to switch between multiple views simply

Thank you for helping me fix the problem. In the end I was able to fix it and it now works. Here it is:
package Button;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.util.Scanner;
#SuppressWarnings("unused")
public class AddOnButton {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("Password");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JButton loginButton = new JButton("Create");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
String name = userText.getText();
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loginButton.setVisible(false);
userText.setVisible(false);
userLabel.setVisible(false);
JTextField userText1 = new JTextField(20);
userText1.setBounds(100, 10, 160, 25);
panel.add(userText1);
JLabel userLabel1 = new JLabel("Password");
userLabel1.setBounds(10, 10, 80, 25);
panel.add(userLabel1);
JButton loginButton1 = new JButton("Enter");
loginButton1.setBounds(10, 80, 80, 25);
panel.add(loginButton1);
String check = userText1.getText();
loginButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userText1.setVisible(false);
userLabel1.setVisible(false);
loginButton1.setVisible(false);
String good;
if (name.equals(check)) {
good = "Welcome";
} else {
good = "False. Error";
}
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
label1.setVisible(true);
panel.add(label1);
}
});
}
});
}
}

Related

JTextField setText()

I was making a GUI to reverse an input string, I am taking input from the first textfield, then reversing the string using my function strRev() then trying to produce the result on the second textfield. But am not getting any output on 2nd textfield.
package com.awt;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.InputMethodEvent;
public class Buttons{
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Buttons window = new Buttons();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Buttons() {
initialize();
}
public String strRev(String s) {
char a;
String ans="";
for(int i=0;i<s.length();i++) {
a=s.charAt(i);
ans=a+ans;
}
return ans;
}
private void initialize() {
frame = new JFrame("Label Demo");
frame.setBounds(150, 200, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton okButton = new JButton("Reverse");
frame.getContentPane().add(okButton);
textField_1 = new JTextField();
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
String str=textField.getText();
final String ans=strRev(str);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_1.setText(ans);
}
});
}
}
The GUI looks like this:-
Please let me know my mistake, Thanks
You need to read the contents of textField only when the user clicks on the Reverse button. At the moment, you read the contents when the GUI loads at which time there is nothing in the textField. So calling a reverse on empty string is going to give you an empty string and that is what you see in your textField_1. Move the code where you read the textField into your addActionListener.
private void initialize() {
frame = new JFrame("Label Demo");
frame.setBounds(150, 200, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
textField = new JTextField();
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton okButton = new JButton("Reverse");
frame.getContentPane().add(okButton);
textField_1 = new JTextField();
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// THIS BLOCK IS RUN EVERYTIME THE BUTTON IS CLICKED!
// Read the contents of textField
String str=textField.getText();
// Reverse the string you just read
final String ans=strRev(str);
// Set the answer on the other textField.
textField_1.setText(ans);
}
});
}

How do I output to textField?

I'm making a java program to turn any text into capital capital letters.
It worked fine with system.out.print but now I want to turn it into a GUI.
I tried getting the text from the original textField input, turn it into a double, turn the double into a string then I used addText but I don;t think it works.
Here is how it is supposed to work:
I write a bunch a text into a the input box then when I click the GO button it converts every character into capital letters. The output is supposed to to inside another TextField
here is my code (using Eclipse)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Frame1 {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 710, 508);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblInputTextTo = new JLabel("Input Text to Capitalise:");
lblInputTextTo.setFont(new Font("Segoe UI", Font.BOLD, 26));
lblInputTextTo.setBounds(210, 0, 289, 54);
frame.getContentPane().add(lblInputTextTo);
textField = new JTextField();
textField.setBounds(34, 77, 624, 150);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(34, 354, 613, 90);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnGo = new JButton("GO!");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double TextInput = Double.parseDouble(textField.getText());
String Str = String.valueOf(TextInput);
textField_1.setText(Str.toUpperCase());
textField_1.setEditable(false);
}
});
btnGo.setFont(new Font("Segoe UI", Font.BOLD, 18));
btnGo.setBounds(250, 239, 180, 23);
frame.getContentPane().add(btnGo);
JLabel lblOutput = new JLabel("Output:");
lblOutput.setFont(new Font("Segoe UI", Font.BOLD, 26));
lblOutput.setBounds(304, 300, 95, 43);
frame.getContentPane().add(lblOutput);
}}
I'm not done yet if you have some suggestion it would be nice.
You don't need to convert the input String into double to make it uppercase. I did below change to your program and it works now.
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Remove these 2 lines
//double TextInput = Double.parseDouble(textField.getText());
//String Str = String.valueOf(TextInput);
//Directly take input text, make it uppercase and set it in output field.
textField_1.setText(textField.getText().toUpperCase());
textField_1.setEditable(false);
}
});
Additional tip:
Don't do setLayout(null) and use setBounds() to set components in absolute positions. Instead use layout managers. See https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

How to open new window after JProgressBar is completed

I created FlashScreen.java as loading screen consist of JProgressBar.
I want that after progressbar percentage is completed current window should be closed and new window should be open.
I made it but after closing first window in next window there is no component in window. Empty window is opening.
Here is code:
FlashScreen.java
package crimeManagement;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FlashScreen extends JFrame{
JProgressBar jb;
JLabel lblStat;
int i=0,num=0;
FlashScreen(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(new Rectangle(400, 200, 0, 0));
jb=new JProgressBar(0,2000);
jb.setBounds(100,219,579,22);
jb.setValue(0);
jb.setStringPainted(true);
getContentPane().add(jb);
setSize(804,405);
getContentPane().setLayout(null);
lblStat = new JLabel("");
lblStat.setForeground(Color.CYAN);
lblStat.setHorizontalAlignment(SwingConstants.CENTER);
lblStat.setHorizontalTextPosition(SwingConstants.CENTER);
lblStat.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblStat.setBounds(229, 252, 329, 14);
getContentPane().add(lblStat);
JLabel lblBackGround = new JLabel("");
lblBackGround.setHorizontalTextPosition(SwingConstants.CENTER);
lblBackGround.setHorizontalAlignment(SwingConstants.CENTER);
lblBackGround.setIcon(new ImageIcon(FlashScreen.class.getResource("/Images/FlashImage.jpg")));
lblBackGround.setBounds(0, 0, 798, 376);
getContentPane().add(lblBackGround);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{
Thread.sleep(50);
if(i==20)
{
lblStat.setText("Loading...");
}
if(i==500)
{
lblStat.setText("Please Wait...");
}
if(i==1000)
{
Thread.sleep(100);
lblStat.setText("Loading Police Station Management System...");
}
if(i==1200)
{
lblStat.setText("Please Wait...");
}
if(i==1600)
{
lblStat.setText("Almost Done...");
}
if(i==1980)
{
lblStat.setText("Done");
}
if(i==2000)
{
this.dispose();
LoginPage lp=new LoginPage();
lp.setVisible(true);
}
}
catch(Exception e){}
}
}
public static void main(String[] args) {
FlashScreen fs=new FlashScreen();
fs.setVisible(true);
fs.iterate();
}
}
**LoginPage.java**
package crimeManagement;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.*;
public class LoginPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField txtUserName;
private JPasswordField txtPass;
public static void main(String[] args) {
LoginPage window = new LoginPage();
window.frame.setVisible(true);
}
public LoginPage() {
frame = new JFrame();
frame.setResizable(false);
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 16));
frame.setBounds(100, 100, 554, 410);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLoginType = new JLabel("Login Type");
lblLoginType.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblLoginType.setBounds(97, 53, 99, 20);
frame.getContentPane().add(lblLoginType);
JLabel lblUsename = new JLabel("User Name");
lblUsename.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblUsename.setBounds(97, 177, 99, 26);
frame.getContentPane().add(lblUsename);
JLabel lblPaaword = new JLabel("Password");
lblPaaword.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPaaword.setBounds(97, 223, 99, 26);
frame.getContentPane().add(lblPaaword);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(210, 47, 143, 93);
frame.getContentPane().add(panel);
TitledBorder tb=new TitledBorder( "Login");
tb.setTitleJustification(TitledBorder.CENTER);
tb.setTitlePosition(TitledBorder.CENTER);
panel.setBorder(BorderFactory.createTitledBorder(tb));
JRadioButton rdbAdmin = new JRadioButton("Admin");
rdbAdmin.setBackground(SystemColor.inactiveCaption);
rdbAdmin.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbAdmin.setSelected(true);
panel.add(rdbAdmin);
JRadioButton rdbOthers = new JRadioButton("Others");
rdbOthers.setBackground(SystemColor.inactiveCaption);
rdbOthers.setFont(new Font("Tahoma", Font.PLAIN, 13));
panel.add(rdbOthers);
txtUserName = new JTextField();
txtUserName.setBackground(UIManager.getColor("TextField.background"));
txtUserName.setBounds(210, 177, 158, 26);
frame.getContentPane().add(txtUserName);
txtUserName.setColumns(30);
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnLogin.setBounds(210, 286, 71, 23);
frame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnExit.setBounds(297, 286, 71, 23);
frame.getContentPane().add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(210, 226, 158, 26);
frame.getContentPane().add(txtPass);
}
}
You're displaying the wrong JFrame. Yes the LoginPage extends JFrame, and yes you display it, but you add no components to it, and instead add all components to a private JFrame field of the class named, frame.
A quick solution is to change your LoginPage class so that it doesn't extend JFrame and then give this class a public getFrame() method:
public JFrame getFrame() {
return frame;
}
and when wanting to show it, call
this.dispose();
LoginPage lp = new LoginPage();
// lp.setVisible(true);
lp.getFrame().setVisible(true);
but having said this, there are still some serious threading issues with your code that you'll eventually want to fix, including trying to avoid calling Thread.sleep() in code that risks being called on the Swing event thread.
Also please check out The Use of Multiple JFrames: Good or Bad Practice? to see why it is often a bad practice to display a bunch of JFrames in your app, and ways around this.
Other issues include use of null layouts. Yes they may seem like an easy way to create complex GUI's quickly -- until you try to show the GUI on another platform and find that they don't look so nice, or have to enhance, debug or change it, and find it very tricky and easy to mess up. Much better to use layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FlashScreenTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainFrame = new JFrame("Main App");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainAppPanel());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
FlashScreenPanel dialogPanel = new FlashScreenPanel();
JDialog dialog = new JDialog(mainFrame, "Flash Screen", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialogPanel.startProgress();
dialog.setVisible(true);
mainFrame.setVisible(true);
});
}
}
class FlashScreenPanel extends JPanel {
public static final String LOADING = "Loading...";
public static final String PLEASE_WAIT = "Please Wait...";
public static final String LOADING_POLICE_STATION = "Loading Police Station...";
public static final String ALMOST_DONE = "Almost Done...";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 50;
private JProgressBar jb = new JProgressBar(0, 2000);
private JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
public FlashScreenPanel() {
setPreferredSize(new Dimension(800, 400));
statusLabel.setForeground(Color.CYAN);
statusLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
jb.setStringPainted(true);
JPanel bottomPanel = new JPanel(new BorderLayout(20, 20));
bottomPanel.add(jb, BorderLayout.PAGE_START);
bottomPanel.add(statusLabel, BorderLayout.CENTER);
int eb = 40;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new GridLayout(0, 1));
add(new JLabel()); // dummy component to move prog bar lower
add(bottomPanel);
}
public void startProgress() {
statusLabel.setText(LOADING);
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
i += 20;
jb.setValue(i);
if (i == 500) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1000) {
statusLabel.setText(LOADING_POLICE_STATION);
} else
if (i == 1200) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1600) {
statusLabel.setText(ALMOST_DONE);
} else
if (i == 1980) {
statusLabel.setText(DONE);
} else
if (i == 2000) {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(FlashScreenPanel.this);
win.dispose();
}
}
}).start();
}
}
class MainAppPanel extends JPanel {
public MainAppPanel() {
setPreferredSize(new Dimension(600, 400));
}
}

Passing info from one Jframe to another

I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.

Focus on Keylistener

So what I've got is that I would love to try and make an little login applet. I'm using Java Windowsbuilder for it, to make it easyer for me. I hope the code isn't to messy, because I'm just a starter.
The problem I've got is that My JButton "login" only registers a keyevent when it's selected trought tab, or when you first click it. What I want is that I can use the button always just by pressing the "ENTER" key.
Hope you guys solve my problem :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.event.KeyAdapter;
public class nummer1 extends JFrame{
private JPanel contentPane;
public static nummer1 theFrame;
private JTextField textFieldUsername;
private JTextField textFieldPass;
private nummer1 me;
private JLabel lblCheck;
private String password = "test", username = "test";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nummer1 frame = new nummer1();
nummer1.theFrame = frame;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Check(){
String Pass = textFieldPass.getText();
String Username = textFieldUsername.getText();
System.out.println(Pass);
if (Pass.equals(password) && Username.equals(username)){
lblCheck.setText("Correct Login");
}else{
lblCheck.setText("Invalid username or password");
}
}
/**
* Create the frame.
*/
public nummer1() {
me = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 356, 129);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 61, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 61, 14);
contentPane.add(lblPassword);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(81, 8, 107, 20);
contentPane.add(textFieldUsername);
textFieldUsername.setColumns(10);
me.textFieldUsername = textFieldUsername;
textFieldPass = new JTextField();
textFieldPass.setBounds(81, 33, 107, 20);
contentPane.add(textFieldPass);
textFieldPass.setColumns(10);
me.textFieldPass = textFieldPass;
JButton btnLogin = new JButton("Login");
contentPane.requestFocusInWindow();
btnLogin.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
me.Check();
System.out.println("hi");
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
me.Check();
}
});
btnLogin.setBounds(198, 7, 89, 23);
contentPane.add(btnLogin);
JLabel lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.TRAILING);
lblCheck.setBounds(10, 65, 264, 14);
contentPane.add(lblCheck);
me.lblCheck = lblCheck;
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new
Component[]{lblUsername, lblPassword, textFieldUsername, textFieldPass, btnLogin, lblCheck}));
}
}
Thanks Emil!
What I want is that I can use the button always just by pressing the "ENTER" key
Sounds like you want to make the "login" button the default button for the dialog.
See Enter Key and Button for the problem and solution.
When using panels KeyListeners won't work unless the panel is focusable. What you can do is make a KeyBinding to the ENTER key using the InputMap and ActionMap for your panel.
public class Sample extends JPanel{
//Code
Sample() {
//More code
this.getInputMap().put(KeyStroke.getKeyStroke((char)KeyEvent.VK_ENTER), "Enter" );
this.getActionMap().put("Enter", new EnterAction());
}
private class EnterAction extends AbstractAction(){
#Override
public void ActionPerformed(ActionEvent e){
//Acion
}
}
}

Categories

Resources