I wrote a very simple logon JPanel following the demo in http://download.oracle.com/javase/tutorial/uiswing/components/passwordfield.html
it has three components,
JTextField to get username
JPasswordField to get password
JButton to logon
then the JPanel is shown in the JFrame when the application starts. the issue is, I found if I click on password field first, i can enter password without problem. however if I enter username first then I can't enter anything in the password field. anyone knows what might be going wrong here?
here is the the code I wrote for the logon panel, this code can be compiled and run, but the password can't be entered. is there something I missed?
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class Logon extends javax.swing.JPanel implements ActionListener {
private JTextField fldName;
private JPasswordField fldPasswd;
private JButton btnLogon;
public Logon() {
JLabel labTitle = new JLabel("title");
labTitle.setText("EMT Monitor v.1.0");
// username
fldName = new JTextField(10);
JLabel labName = new JLabel("Username");
labName.setText("Username:");
labName.setLabelFor(fldPasswd);
// passwd
fldPasswd = new JPasswordField(10);
fldPasswd.setActionCommand("Logon");
fldPasswd.addActionListener(this);
fldPasswd.requestFocusInWindow();
JLabel labPasswd = new JLabel("Password");
labPasswd.setText("Password:");
labPasswd.setLabelFor(fldPasswd);
// botten
btnLogon = new JButton("Logon");
btnLogon.setActionCommand("Logon");
btnLogon.addActionListener(this);
JPanel mainPanel = new JPanel();
btnLogon.setPreferredSize(new Dimension(200, 30));
mainPanel.setPreferredSize(new Dimension(340, 190));
mainPanel.add(labName);
mainPanel.add(fldName);
mainPanel.add(labPasswd);
mainPanel.add(fldPasswd);
mainPanel.add(btnLogon);
JPanel outPanel = new JPanel();
outPanel.setPreferredSize(new Dimension(400, 300));
outPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
outPanel.add(mainPanel);
add(outPanel);
setAlignmentX(Component.CENTER_ALIGNMENT);
setAlignmentY(Component.CENTER_ALIGNMENT);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Logon")) { //Process the password.
String user = fldName.getText();
String passwd = new String(fldPasswd.getPassword());
System.out.println(user + " " + passwd);
}
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Logon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
final Logon newContentPane = new Logon();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
There is no problem as described in the question. This works fine. Once you enter the username and password, and click logon, the given username and password is printed.
Related
I have been experimenting with making GUIs in java as opposed to just using "static" all the time and come across the "SwingUtilities.invokeLater()" method. I manage to get everything setup but when it comes to run the application, nothing appears on the JPanel until I resize the window. Is there a fix for this or am I doing it wrong?
Heres my code:
public class main extends JPanel implements ActionListener{
public JLabel userLabel;
public JLabel passLabel;
public JTextField userField;
public JTextField passField;
public JButton login;
public JButton closeLogin;
public JButton help;
public main(){
userLabel = new JLabel("Username: ");
passLabel = new JLabel("Password: ");
userField = new JTextField(16);
passField = new JTextField(16);
login = new JButton("Login");
login.setActionCommand("login");
login.setMnemonic(KeyEvent.VK_L);
closeLogin = new JButton("Close");
closeLogin.setActionCommand("closeLogin");
closeLogin.setMnemonic(KeyEvent.VK_E);
help = new JButton("Help");
help.setActionCommand("helpLogin");
help.setMnemonic(KeyEvent.VK_H);
login.addActionListener(this);
closeLogin.addActionListener(this);
help.addActionListener(this);
add(userLabel);
add(userField);
add(passLabel);
add(passField);
add(login);
add(help);
add(closeLogin);
}
public void actionPerformed(ActionEvent e){
}
public static void initComponents(){
JFrame loginFrame = new JFrame("Encrypted Chat - Login");
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main loginPanel = new main();
loginPanel.setLayout(new FlowLayout());
loginFrame.setSize(300, 125);
loginFrame.setResizable(false);
loginFrame.setVisible(true);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
initComponents();
}
});
}
}
EDIT: I know the password JTextField is meant to be a JPasswordField.. so ignore it :P
Two basic advices:
1.) When you use swing, and stuff doesnt show up/update, you should call JPanel.revalidate() and JPanel.repaint() These two functions will update your panel.
If you are using a JFrame and you didn't add any extra panels to it, then you can get the content panel by JFrame.getContentPane()
2.) When you finished adding Components to a panel/frame you should also call pack() on the frame, this will ensure, that all your Components have the prefered size.
You never add your content to the JFrame. The minimal set of changes you need:
public static void main(String args[]){
final main main = new main();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
initComponents(main);
}
});
}
And then modify initComponents to take a main object:
public static void initComponents(main main){
JFrame loginFrame = new JFrame("Encrypted Chat - Login");
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main loginPanel = new main();
loginPanel.setLayout(new FlowLayout());
loginFrame.setSize(300, 125);
loginFrame.setResizable(false);
loginFrame.setVisible(true);
loginFrame.add(main); // <----- this line is added
}
for built_in FlowLayout (for JPanel) I don't suggest to use pack() for JFrame, sure correct way could be to use proper and better LayoutManager for this job, GridBagLayout or SpringLayout
output by using JFrame#setSize() and without pack()
for example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MainLogin implements ActionListener {
private JFrame loginFrame = new JFrame("Encrypted Chat - Login");
private JPanel pnl = new JPanel();
private JLabel userLabel;
private JLabel passLabel;
private JTextField userField;
private JTextField passField;
private JButton login;
private JButton closeLogin;
private JButton help;
public MainLogin() {
userLabel = new JLabel("Username: ");
passLabel = new JLabel("Password: ");
userField = new JTextField(16);
passField = new JTextField(16);
login = new JButton("Login");
login.setActionCommand("login");
login.setMnemonic(KeyEvent.VK_L);
closeLogin = new JButton("Close");
closeLogin.setActionCommand("closeLogin");
closeLogin.setMnemonic(KeyEvent.VK_E);
help = new JButton("Help");
help.setActionCommand("helpLogin");
help.setMnemonic(KeyEvent.VK_H);
login.addActionListener(this);
closeLogin.addActionListener(this);
help.addActionListener(this);
pnl.add(userLabel);
pnl.add(userField);
pnl.add(passLabel);
pnl.add(passField);
pnl.add(login);
pnl.add(help);
pnl.add(closeLogin);
loginFrame.add(pnl);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.setSize(300, 125);
loginFrame.setResizable(false);
loginFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainLogin mainLogin = new MainLogin();
}
});
}
}
Put
JFrame.setVisible(true); on the last line after adding all components to it.
package me.daniel.practice;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Switch
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Password Login System");
frame.setSize(400, 100);
frame.setResizable(false);
frame.setVisible(true);
frame.setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Password: ");
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.EAST);
frame.add(panel);
}
private static String password = "daniel";
static class AL implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JPasswordField input = (JPasswordField) e.getSource();
char[] passy = input.getPassword();
String p = new String(passy);
if (p.equals(password))
{
JOptionPane.showMessageDialog(null, "Correct");
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
}
}
I want a frame to open and within it, text that says, "Enter Password: " and on its right, a text box that you are able to type you password into. The password in this situation is "daniel."
When you enter the password correctly, another window pops up saying that it's correct. If not, a different window pops up saying that it's incorrect. However, when I run the program, only the frame shows up and not the actual content within the frame.
You should make your frame visible after adding contents to it:
frame.add(panel);
frame.setVisible(true); // move down here
}
P.S. JPanel have default layout manager which is FlowLayout so all the contents would appear inline. In short, panel.add(label, BorderLayout.WEST) won't give the expected output.
You just need to add frame.validate(); after frame.add(panel);.
Although the code you have will most likely work, ideally you should wrap any Java swing initialisation into a SwingUtilities.invokeLater(...) so that it runs on the swing thread:
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
JFrame frame = new JFrame("Password Login System");
frame.setSize(400, 100);
frame.setResizable(false);
frame.setVisible(true);
frame.setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Password: ");
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.EAST);
frame.add(panel);
frame.validate();
}
});
}
See oracle docs here for mode details.
I'm new to programming with Java.
I have these two small projects.
import javax.swing.*;
public class tutorial {
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("hello");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(label);
JButton button = new JButton("Hello again");
panel.add(button);
}
}
and this one:
import java.util.*;
public class Test {
public static void main(String[] args){
int age;
Scanner keyboard = new Scanner(System.in);
System.out.println("How old are you?");
age = keyboard.nextInt();
if (age<18)
{
System.out.println("Hi youngster!");
}
else
{
System.out.println("Hello mature!");
}
}
}
How can I add the second code to the first one, so that the user will see a window that says 'How old are you' and they can type their age.
Thanks in advance!
I'm not sure of all the things you wanted because it was undefined, but as I far as I understand, you wanted a JFrame containing an input field, in which you will be able to input values and display the appropriate answer.
I also suggest you read tutorial , but don't hesitate if you have question.
I hope it's a bit close to what you wanted.
package example.tutorial;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Tutorial extends JPanel {
private static final String YOUNG_RESPONSE = "Hi youngster!";
private static final String ADULT_RESPONSE = "Hello mature!";
private static final String INVALID_AGE = "Invalid age!";
private static final int MIN_AGE = 0;
private static final int MAX_AGE = 100;
private static JTextField ageField;
private static JLabel res;
private Tutorial() {
setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
JLabel label = new JLabel("How old are you ? ");
northPanel.add(label);
ageField = new JTextField(15);
northPanel.add(ageField);
add(northPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
JButton btn = new JButton("Hello again");
btn.addActionListener(new BtnListener());
centerPanel.add(btn);
res = new JLabel();
res.setVisible(false);
centerPanel.add(res);
add(centerPanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.add(new Tutorial());
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String content = ageField.getText();
int age = -1;
try{
age = Integer.parseInt(content);
if(isValid(age)) {
res.setText(age < 18 ? YOUNG_RESPONSE : ADULT_RESPONSE);
} else {
res.setText(INVALID_AGE);
}
if(!res.isVisible())
res.setVisible(true);
} catch(NumberFormatException ex) {
res.setText("Wrong input");
}
}
private boolean isValid(int age) {
return age > MIN_AGE && age < MAX_AGE;
}
}
}
so that the user will see a window that says 'How old are you' and they can type their age.
The easiest way to start would be to use a JOptionPane. Check out the section from the Swing tutorial on How to Use Dialogs for examples and explanation.
Don't forget to look at the table of contents for other Swing related topics for basic information about Swing.
You will need an input field to get the text and then add an ActionListener to the button which contains the logic that is performed when the button is pressed.
I modified your code to implement what you described:
import javax.swing.*;
import java.awt.event.*;
public class tutorial {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("hello");
JPanel panel = new JPanel();
frame.add(panel);
panel.add(label);
final JTextField input = new JTextField(5); // The input field with a width of 5 columns
panel.add(input);
JButton button = new JButton("Hello again");
panel.add(button);
final JLabel output = new JLabel(); // A label for your output
panel.add(output);
button.addActionListener(new ActionListener() { // The action listener which notices when the button is pressed
public void actionPerformed(ActionEvent e) {
String inputText = input.getText();
int age = Integer.parseInt(inputText);
if (age < 18) {
output.setText("Hi youngster!");
} else {
output.setText("Hello mature!");
}
}
});
}
}
In that example we don't validate the input. So if the input is not an Integer Integer.parseInt will throw an exception. Also the components are not arranged nicely. But to keep it simple for the start that should do it. :)
it's not an easy question since you are working on command line in one example, and in a Swing GUI in the other.
Here's a working example, i've commented here and there.
This is no where near java best practises and it misses a lot of validation (just see what happens when you enter a few letters or nothing in the textfield.
Also please ignore the setLayout(null) and setBounds() statements, it's just a simple example not using any layout managers.
I hope my comments will help you discovering java!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//You'll need to implement the ActionListener to listen to buttonclicks
public class Age implements ActionListener{
//Declare class variables so you can use them in different functions
JLabel label;
JTextField textfield;
//Don't do al your code in the static main function, instead create an instance
public static void main(String[] args){
new Age();
}
// this constructor is called when you create a new Age(); like in the main function above.
public Age()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0,0,300,300);
panel.setLayout(null);
label = new JLabel("hello");
label.setBounds(5,5,100,20);
// a JTextfield allows the user to edit the text in the field.
textfield = new JTextField();
textfield.setBounds(5,30,100,20);
JButton button = new JButton("Hello again");
button.setBounds(130,30,100,20);
// Add this instance as the actionlistener, when the button is clicked, function actionPerformed will be called.
button.addActionListener(this);
panel.add(label);
panel.add(textfield);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
//Required function actionPerformed for ActionListener. When the button is clicked, this function is called.
#Override
public void actionPerformed(ActionEvent e)
{
// get the text from the input.
String text = textfield.getText();
// parse the integer value from the string (! needs validation for wrong inputs !)
int age = Integer.parseInt(text);
if (age<18)
{
//instead of writing out, update the text of the label.
label.setText("Hi youngster!");
}
else
{
label.setText("Hello mature!");
}
}
}
I have main class with a main GUI from where I want to activate and get values from a new class with a JOptionPane like the code below. Since I already have a main GUI window opened, how and where should I activate/call the class below and finally, how do I get the values from the JOptionPane? Help is preciated! Thanks!
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class OptionPaneTest {
JPanel myPanel = new JPanel();
JTextField field1 = new JTextField(10);
JTextField field2 = new JTextField(10);
myPanel.add(field1);
myPanel.add(field2);
JOptionPane.showMessageDialog(null, myPanel);
}
Edit:
InputNewPerson nyPerson = new InputNewPerson();
JOptionPane.showMessageDialog(null, nyPerson);
String test = nyPerson.inputName.getText();
I guess looking at your question, you need something like this. I had made a small JDialog, where you will enter a UserName and Answer, this will then be passed to the original GUI to be shown in the respective fields, as you press the SUBMIT JButton.
Try your hands on this code and ask any question that may arise :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* This is the actual GUI class, which will get
* values from the JDIalog class.
*/
public class GetDialogValues extends JFrame
{
private JTextField userField;
private JTextField questionField;
public GetDialogValues()
{
super("JFRAME");
}
private void createAndDisplayGUI(GetDialogValues gdv)
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 2));
JLabel userName = new JLabel("USERNAME : ");
userField = new JTextField();
JLabel questionLabel = new JLabel("Are you feeling GOOD ?");
questionField = new JTextField();
contentPane.add(userName);
contentPane.add(userField);
contentPane.add(questionLabel);
contentPane.add(questionField);
getContentPane().add(contentPane);
pack();
setVisible(true);
InputDialog id = new InputDialog(gdv, "Get INPUT : ", true);
}
public void setValues(final String username, final String answer)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
userField.setText(username);
questionField.setText(answer);
}
});
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
GetDialogValues gdv = new GetDialogValues();
gdv.createAndDisplayGUI(gdv);
}
};
SwingUtilities.invokeLater(runnable);
}
}
class InputDialog extends JDialog
{
private GetDialogValues gdv;
private JTextField usernameField;
private JTextField questionField;
private JButton submitButton;
private ActionListener actionButton = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (usernameField.getDocument().getLength() > 0
&& questionField.getDocument().getLength() > 0)
{
gdv.setValues(usernameField.getText().trim()
, questionField.getText().trim());
dispose();
}
else if (usernameField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Enter USERNAME."
, "Invalid USERNAME : ", JOptionPane.ERROR_MESSAGE);
}
else if (questionField.getDocument().getLength() == 0)
{
JOptionPane.showMessageDialog(null, "Please Answer the question"
, "Invalid ANSWER : ", JOptionPane.ERROR_MESSAGE);
}
}
};
public InputDialog(GetDialogValues gdv, String title, boolean isModal)
{
this.gdv = gdv;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setModal(isModal);
setTitle(title);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
JLabel usernameLabel = new JLabel("Enter USERNAME : ");
usernameField = new JTextField();
JLabel questionLabel = new JLabel("How are you feeling ?");
questionField = new JTextField();
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(questionLabel);
panel.add(questionField);
submitButton = new JButton("SUBMIT");
submitButton.addActionListener(actionButton);
add(panel, BorderLayout.CENTER);
add(submitButton, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
}
JOPtionPane provides a number of preset dialog types that can be used. However, when you are trying to do something that does not fit the mold of one of those types, it is best to create your own dialog by making a sub-class of JDialog. Doing this will give you full control over how the controls are laid out and ability to respond to button clicks as you want. You will want to add an ActionListener for the OK button. Then, in that callback, you can extract the values from the text fields.
The process of creating a custom dialog should be very similar to how you created the main window for your GUI. Except, instead of extending JFrame, you should extend JDialog. Here is a very basic example. In the example, the ActionListener just closes the dialog. You will want to add more code that extracts the values from the text fields and provides them to where they are needed in the rest of your code.
I have designed an applet that is shown in a separate java window (and a blank web browser window also appears) but i'd like it to be displayed in the web browser. I have no clue about it. Should I change the JFrame or is it different stuff?
My code is as follows:
Public class myApplet extends Applet implements ActionListener{
public JPanel createContentPane (){
System.out.println("1");
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
titleLabel = new JLabel("Login");
totalGUI.add(titleLabel);
// Creation of a Panel to contain the JLabels
textPanel = new JPanel();
textPanel.setLayout(null);
totalGUI.add(textPanel);
// Usuario Label
usuarioLabel = new JLabel("User");
textPanel.add(usuarioLabel);
// Password nuevo Label
passwordLabel = new JLabel("Password");
passwordLabel.setHorizontalAlignment(4);
textPanel.add(passwordLabel);
// TextFields Panel Container
panelForTextFields = new JPanel();
panelForTextFields.setLayout(null);
totalGUI.add(panelForTextFields);
// Password viejo Textfield
usuarioField = new JTextField(8);
panelForTextFields.add(usuarioField);
// Password nuevo Textfield
passwordField = new JPasswordField(8);
panelForTextFields.add(passwordField);
// Button for Logging in
loginButton = new JButton("Restore");
loginButton.addActionListener(this);
totalGUI.add(loginButton);
totalGUI.setOpaque(true);
return totalGUI;
}
public void actionPerformed(ActionEvent e) {
//restores password
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Change password");
myApplet demo = new myApplet ();
frame.setContentPane(demo.createContentPane());
frame.setSize(310, 400);
frame.setVisible(true);
}
public void init (){
System.out.println("Applet initializing");
final myApplet rp = new myApplet ();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
rp.createAndShowGUI();
}
});
}
}
Screen Shot
Code
//<applet code='myApplet' width=220 height=100></applet>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** This was terrible code. You should take it back to whoever gave
it to you, and throw it at them. Never get code from them again. */
public class myApplet extends JApplet implements ActionListener{
private JLabel titleLabel;
private JLabel usuarioLabel;
private JLabel passwordLabel;
private JPanel textPanel;
private JPanel panelForTextFields;
private JTextField usuarioField;
private JPasswordField passwordField;
private JButton loginButton;
public JPanel createContentPane (){
System.out.println("1");
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
// Use LAYOUTS!
totalGUI.setLayout(new FlowLayout());
titleLabel = new JLabel("Login");
totalGUI.add(titleLabel);
// Creation of a Panel to contain the JLabels
textPanel = new JPanel();
totalGUI.add(textPanel);
// Usuario Label
usuarioLabel = new JLabel("User");
textPanel.add(usuarioLabel);
// Password nuevo Label
passwordLabel = new JLabel("Password");
passwordLabel.setHorizontalAlignment(4);
textPanel.add(passwordLabel);
// TextFields Panel Container
panelForTextFields = new JPanel();
totalGUI.add(panelForTextFields);
// Password viejo Textfield
usuarioField = new JTextField(8);
panelForTextFields.add(usuarioField);
// Password nuevo Textfield
passwordField = new JPasswordField(8);
panelForTextFields.add(passwordField);
// Button for Logging in
loginButton = new JButton("Restore");
loginButton.addActionListener(this);
totalGUI.add(loginButton);
totalGUI.setOpaque(true);
return totalGUI;
}
public void actionPerformed(ActionEvent e) {
//restores password
}
private void createAndShowGUI() {
add( createContentPane() );
validate();
}
public void init (){
System.out.println("Applet initializing");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
To Run
prompt>appetviewer myApplet.java
Applet initializing
1
prompt>
You should extend JApplet and put your controls directly in the JApplet instance (this).
Click here to get sample source on how to show an applet in web browser.
Thanks
Deepak