How to set frame visibility conditionally in JSwing? - java

I'm trying to create a login panel in Java Swing where the user will first get a screen that requires them to enter the credentials and if they match the correct credentials, they will be directed to another java GUI class called UserManager. I'm not sure how I can set the current frame (of the login panel) to be false and the set the frame visible of the new panel that I want to switch to (the UserManger panel) to be true.
Here is what I have so far but it's not working:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
public class Main implements ActionListener {
private static JLabel label;
private static JTextField userText;
private static JLabel passwordLabel;
private static JPasswordField passwordText;
private static JButton button;
private static JLabel success;
private static boolean loggedIn = false;
public static void main(String[] args) {
// JOptionPane.showMessageDialog(null, "Login");
JFrame f = new JFrame();
JPanel panel = new JPanel();
f.setSize(100, 100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
panel.setLayout(null);
// username text label
label = new JLabel("User");
label.setBounds(10, 20, 80, 25);
panel.add(label);
userText = new JTextField(20);
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
// pasword label
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField(20);
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
button = new JButton("Login");
button.setBounds(10, 80, 80, 25);
button.addActionListener(new Main());
panel.add(button);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
f.setVisible(true);
if (loggedIn) {
UserManager frame = new UserManager();
f.setVisible(false);
frame.setVisible(true);
}
}
#Override
public void actionPerformed(ActionEvent e) {
String user = userText.getText();
String password = passwordText.getText();
System.out.println(user + ", " + password);
if(user.equals("John") && password.equals("hello")) {
success.setText("Login successful");
loggedIn = true;
}
else {
success.setText("Incorrect credentials.");
}
}
}

Use a CardLayout
See for How to Use CardLayout more details.
This will encourage you to isolate you functionality into individual components, there by isolating the workflows and supporting the "single responsibility" concept.
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
private UserPane userPane;
private LoginPane loginPane;
public MainPane() {
setLayout(new CardLayout());
userPane = new UserPane();
loginPane = new LoginPane(new AuthenticationListener() {
#Override
public void authenticationWasSuccessful(User user) {
userPane.setUser(user);
// The user pane's content size will have changed
SwingUtilities.windowForComponent(userPane).pack();
((CardLayout) getLayout()).show(MainPane.this, "USER");
}
#Override
public void authenticationDidFail() {
JOptionPane.showMessageDialog(MainPane.this, "Authentication failed", "Error", JOptionPane.ERROR_MESSAGE);
}
});
add(userPane, "USER");
add(loginPane, "LOGIN");
((CardLayout) getLayout()).show(this, "LOGIN");
}
}
public interface User {
public String getName();
}
public class DefaultUser implements User {
private String name;
public DefaultUser(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public interface AuthenticationListener {
public void authenticationWasSuccessful(User user);
public void authenticationDidFail();
}
public class LoginPane extends JPanel {
private JTextField user;
private JPasswordField password;
private JButton login;
private AuthenticationListener loginListener;
public LoginPane(AuthenticationListener listener) {
setBorder(new EmptyBorder(32, 32, 32, 32));
this.loginListener = listener;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("User name:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
user = new JTextField(12);
password = new JPasswordField(12);
add(user, gbc);
gbc.gridy++;
add(password, gbc);
login = new JButton("Login");
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(login, gbc);
login.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean accept = (boolean) (((int) Math.round(Math.random() * 1)) == 0 ? true : false);
if (accept) {
loginListener.authenticationWasSuccessful(new DefaultUser(user.getText()));
} else {
loginListener.authenticationDidFail();
}
}
});
}
}
public class UserPane extends JPanel {
private JLabel userLabel;
public UserPane() {
JLabel label = new JLabel("Welcome!");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.BOLD, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
add(label, gbc);
userLabel = new JLabel();
add(userLabel, gbc);
}
public void setUser(User user) {
userLabel.setText(user.getName());
}
}
}
Use a modal JDialog
See How to Make Dialogs for more details.
More windows isn't always a good choice, but in the context of gathering user credentials, I think you can make an argument.
This makes use of a modal dialog to stop the code execution at the point that the window is made visible and it won't continue until the window is closed. This allows you an opportunity to get and validate the user credentials before the code continues (it's black magic in how it works, but it's a very common workflow)
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
User user = LoginPane.showLoginDialog();
if (user != null) {
JFrame frame = new JFrame();
frame.add(new UserPane(user));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} else {
// Well, you really don't know do you? Did they cancel
// the dialog or did authentication fail?
}
}
});
}
public interface User {
public String getName();
}
public static class DefaultUser implements User {
private String name;
public DefaultUser(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public static class LoginPane extends JPanel {
public interface AuthenticationListener {
public void authenticationWasSuccessful(User user);
public void authenticationDidFail();
}
private JTextField userTextField;
private JPasswordField passwordField;
private JButton loginButton;
private User user;
public LoginPane(AuthenticationListener listener) {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("User name:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
userTextField = new JTextField(12);
passwordField = new JPasswordField(12);
add(userTextField, gbc);
gbc.gridy++;
add(passwordField, gbc);
loginButton = new JButton("Login");
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(loginButton, gbc);
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean accept = (boolean) (((int) Math.round(Math.random() * 1)) == 0 ? true : false);
if (accept) {
user = new DefaultUser(userTextField.getText());
listener.authenticationWasSuccessful(user);
} else {
user = null;
listener.authenticationDidFail();
}
}
});
}
public User getUser() {
return user;
}
public static User showLoginDialog() {
JDialog dialog = new JDialog();
dialog.setTitle("Login");
dialog.setModal(true);
LoginPane loginPane = new LoginPane(new LoginPane.AuthenticationListener() {
#Override
public void authenticationWasSuccessful(User user) {
dialog.dispose();
}
#Override
public void authenticationDidFail() {
JOptionPane.showMessageDialog(dialog, "Authentication failed", "Error", JOptionPane.ERROR_MESSAGE);
}
});
dialog.add(loginPane);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
return loginPane.getUser();
}
}
public class UserPane extends JPanel {
public UserPane(User user) {
setBorder(new EmptyBorder(32, 32, 32, 32));
JLabel label = new JLabel("Welcome!");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.BOLD, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
add(label, gbc);
JLabel userLabel = new JLabel();
userLabel.setText(user.getName());
add(userLabel, gbc);
}
}
}

You need to unset visibility of this frame and set visible User manager at the action performed level:
private navigateToNextFrame(){
f.dispose(false);
UserManager frame = new UserManager();
frame.setVisible(true);
}
Now you need to call this method in the action performed method instead of loggedin=true and delete block in main main method (if (loggedIn))
A little suggestion : User Manager could be a singleton so you can create it at least 1 time.

Related

How to use a jbutton that is not loaded at the beginning in Java Swing?

I'm learning java swing, I have many buttons, but I need to put some new buttons in the red zone when I select something on my combobox, the problem is that I don't know how to use the buttons if those are not created at the beginning.
Here some buttons loaded when I select in the combobox, I need to make some actions with them:
thanks
Your question leaves a lot open to interpretation.
So, for example, if the values are fixed, I would start by separating them into individual panels, isolating their functionality and workflow, and simple swap them based on what is selected.
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JComboBox<String> comboBox = new JComboBox<>();
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement("Option A");
model.addElement("Option B");
comboBox.setModel(model);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(8, 8, 8, 8);
add(comboBox, gbc);
CardLayout cardLayout = new CardLayout();
JPanel buttonOptions = new JPanel(cardLayout);
buttonOptions.add(new OptionAPane(), "optionA");
buttonOptions.add(new OptionBPane(), "optionB");
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(buttonOptions, gbc);
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
switch (comboBox.getSelectedIndex()) {
case 0:
cardLayout.show(buttonOptions, "optionA");
break;
case 1:
cardLayout.show(buttonOptions, "optionB");
break;
}
}
});
}
}
public class OptionAPane extends JPanel {
public OptionAPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
JButton btnThis = new JButton("This");
btnThis.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Do this");
}
});
JButton btnThat = new JButton("That");
btnThis.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Do that");
}
});
add(new JLabel("A Options"), gbc);
add(btnThis, gbc);
add(btnThat, gbc);
}
}
public class OptionBPane extends JPanel {
public OptionBPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
JButton btnOther = new JButton("Other");
btnOther.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Do other");
}
});
JButton btnSomethingElse = new JButton("Something else");
btnOther.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Do something else");
}
});
add(new JLabel("B Options"), gbc);
add(btnOther, gbc);
add(btnSomethingElse, gbc);
}
}
}
But how do I know when a button is clicked.
This is where an observer pattern would be used. You'd define one or more listeners, based on the needs of each panel and when a button on a panel is clicked, this listener would trigger an event and you could make use of it
If, on the other hand, you need something a little more dynamic (ie each option can have different actions based on some other configuration), you might be able to make use of the Action API
For example...
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ActionGroup {
private String description;
private List<Action> actions;
public ActionGroup(String description) {
this.description = description;
this.actions = new ArrayList<>(25);
}
public ActionGroup(String description, List<Action> actions) {
this.description = description;
this.actions = actions;
}
public String getDescription() {
return description;
}
public void add(Action action) {
actions.add(action);
}
public void remove(Action action) {
actions.remove(action);
}
public List<Action> getActions() {
return Collections.unmodifiableList(actions);
}
}
public class SimpleAction extends AbstractAction {
// You have a number of choices when using something like Action,
// You can create a custom Action based on your needs and pass
// in the information it needs to do it's job OR, you can use
// a observer pattern to get notified when the ActionListener
// is triggered
public SimpleAction(String name) {
putValue(NAME, name);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(getValue(NAME) + " was triggered");
}
}
public class ActionGroupCellRenderer extends DefaultListCellRenderer {
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof ActionGroup) {
value = ((ActionGroup)value).getDescription();
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
ActionGroup optionA = new ActionGroup("Option A");
optionA.add(new SimpleAction("Cat"));
optionA.add(new SimpleAction("Doggy"));
optionA.add(new SimpleAction("Bunny"));
optionA.add(new SimpleAction("Rat"));
optionA.add(new SimpleAction("Cow"));
ActionGroup optionB = new ActionGroup("Option B");
optionB.add(new SimpleAction("Banana"));
optionB.add(new SimpleAction("Apple"));
optionB.add(new SimpleAction("Pear"));
optionB.add(new SimpleAction("Orange"));
optionB.add(new SimpleAction("Lemon"));
JComboBox<ActionGroup> comboBox = new JComboBox<>();
comboBox.setRenderer(new ActionGroupCellRenderer());
DefaultComboBoxModel<ActionGroup> model = new DefaultComboBoxModel<>();
model.addElement(optionA);
model.addElement(optionB);
comboBox.setModel(model);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(8, 8, 8, 8);
add(comboBox, gbc);
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
ActionGroupPane buttonOptions = new ActionGroupPane();
buttonOptions.setActionGroup(optionA);
add(buttonOptions, gbc);
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object item = comboBox.getSelectedItem();
if (item instanceof ActionGroup) {
System.out.println(item);
buttonOptions.setActionGroup((ActionGroup)item);
}
}
});
}
}
public class ActionGroupPane extends JPanel {
public ActionGroupPane() {
setLayout(new GridBagLayout());
}
public void setActionGroup(ActionGroup actionGroup) {
removeAll();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
add(new JLabel(actionGroup.getDescription()), gbc);
for (Action action : actionGroup.getActions()) {
add(new JButton(action), gbc);
}
revalidate();
repaint();
}
}
}
Action is very powerful and I would recommend taking some time to have look at How to Use Actions

Java Swing press the right button when I type a number key

I'm writing a code using Java Swing to press the right button when I type a number key.
But I can't find what I want through search.
This is my code and I can't understand why this isn't working.
Please help me..
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
class class01 {
public static void main(String[] args) {
JFrame f = new JFrame("Key event test");
f.setSize(230, 500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
JButton button1 = new JButton("Coffe");
button1.setSize(100, 100);
button1.setLocation(0, 0);
JButton button2 = new JButton("Latte");
button2.setSize(100, 100);
button2.setLocation(0, 100);
JButton button3 = new JButton("Espresso");
button3.setSize(100, 100);
button3.setLocation(100, 100);
JButton button4 = new JButton("Vanilla Latte");
button4.setSize(100, 100);
button4.setLocation(100, 0);
f.add(button1);
f.add(button2);
f.add(button3);
f.add(button4);
// Show message when the corresponding button is pressed.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button2.keyPressed(KeyEvent.VK_2);
JOptionPane.showMessageDialog(f.getComponent(0), "Latte selected");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button3.keyPressed(KeyEvent.VK_3);
JOptionPane.showMessageDialog(f.getComponent(0), "Espresso selected");
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button4.keyPressed(KeyEvent.VK_4);
JOptionPane.showMessageDialog(f.getComponent(0), "Vanilla Latte selected");
}
});
}
}
The code you are showing does exactly one thing: attach action listeners to your buttons..
Meaning: when you click the button, then the listener will be called.
You need a generic keyboard listener that translates key events into calls to the appropriate button, respectively action listener instead.
From what I understand, essentially you want to have the same operation of a button assigned to a specific key stroke.
Things you want to avoid are KeyListener, especially because you have other focusable components in the view, namely buttons, which will steal keyboard focus and render the KeyListener useless. This is why, in almost all cases, you want to avoid KeyListener.
A better and more reliable solution would be to use the Key Bindings API, which overcomes this focus related issue, but it also encourages the use of reusable components of work through the Actions API
Something like...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.StringJoiner;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(10);
field.setEditable(false);
field.setFocusable(false);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "Pressed.One");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), "Pressed.Two");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), "Pressed.Three");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_4, 0), "Pressed.Four");
am.put("Pressed.One", new OrderAction(1, field));
am.put("Pressed.Two", new OrderAction(2, field));
am.put("Pressed.Three", new OrderAction(3, field));
am.put("Pressed.Four", new OrderAction(4, field));
JButton btnOne = new JButton(new OrderAction(1, field));
JButton btnTwo = new JButton(new OrderAction(2, field));
JButton btnThree = new JButton(new OrderAction(3, field));
JButton btnFour = new JButton(new OrderAction(4, field));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
add(btnOne, gbc);
gbc.gridx++;
add(btnTwo, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(btnThree, gbc);
gbc.gridx++;
add(btnFour, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
add(field, gbc);
}
protected class OrderAction extends AbstractAction {
private int value;
private JTextField field;
public OrderAction(int value, JTextField field) {
this.value = value;
this.field = field;
switch (value) {
case 1:
putValue(NAME, "Coffe");
break;
case 2:
putValue(NAME, "Latte");
break;
case 3:
putValue(NAME, "Espresso");
break;
case 4:
putValue(NAME, "Vanilla Latte");
break;
}
}
#Override
public void actionPerformed(ActionEvent e) {
StringJoiner sj = new StringJoiner("; ");
if (field.getText() != null && field.getText().length() > 0) {
sj.add(field.getText());
}
sj.add(Integer.toString(value));
field.setText(sj.toString());
}
}
}
}
Note, you could apply the key bindings directly to each button instead
Now, if you want to "visually" press the button on a key stroke, I would recommend either creating a custom JButton or factory method, which could allow for a more simplified implementation, but the basic idea would be to define a key binding and Action which simply called the buttons doClick method, for example
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.StringJoiner;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(10);
field.setEditable(false);
field.setFocusable(false);
JButton btnOne = new JButton(new OrderAction(1, field));
JButton btnTwo = new JButton(new OrderAction(2, field));
JButton btnThree = new JButton(new OrderAction(3, field));
JButton btnFour = new JButton(new OrderAction(4, field));
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "Pressed.One");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), "Pressed.Two");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), "Pressed.Three");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_4, 0), "Pressed.Four");
am.put("Pressed.One", new ProxyAction(btnOne));
am.put("Pressed.Two", new ProxyAction(btnTwo));
am.put("Pressed.Three", new ProxyAction(btnThree));
am.put("Pressed.Four", new ProxyAction(btnFour));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
add(btnOne, gbc);
gbc.gridx++;
add(btnTwo, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(btnThree, gbc);
gbc.gridx++;
add(btnFour, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
add(field, gbc);
}
protected class ProxyAction extends AbstractAction {
private JButton btn;
public ProxyAction(JButton btn) {
this.btn = btn;
}
#Override
public void actionPerformed(ActionEvent e) {
btn.doClick();
}
}
protected class OrderAction extends AbstractAction {
private int value;
private JTextField field;
public OrderAction(int value, JTextField field) {
this.value = value;
this.field = field;
switch (value) {
case 1:
putValue(NAME, "Coffe");
break;
case 2:
putValue(NAME, "Latte");
break;
case 3:
putValue(NAME, "Espresso");
break;
case 4:
putValue(NAME, "Vanilla Latte");
break;
}
}
#Override
public void actionPerformed(ActionEvent e) {
StringJoiner sj = new StringJoiner("; ");
if (field.getText() != null && field.getText().length() > 0) {
sj.add(field.getText());
}
sj.add(Integer.toString(value));
field.setText(sj.toString());
}
}
}
}
When you do this:
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
You are telling button1 what to do when somebody clicks on the button. The line with keyPressed should not be there (it does not compile even).
What you need to do is listen for key presses by adding a KeyListener to the frame like this:
f.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
if( e.getKeyChar() == KeyEvent.VK_1) {
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
}
});
I repeated the showMessageDialog, but you should extract the actual logic into a method and call that method from within the KeyListener on the frame and the ActionListener on the button.

GUI: setSize() method of second window does not work

I have 2 windows at the moment. After a user clicks on the Submit button, the Main window appears but it appears as such:
The codes are:
LoginForm.java
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginForm extends JFrame{
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm()
{
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2,2));
loginArea.add(loginEmail); //add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); //add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1,2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler= new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == submit)
{
dispose();
new Main().setVisible(true);
}
}
}
}
And Main.java:
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JFrame{
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main()
{
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1,3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1,3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
The testMain.java:
package interfaceGUI;
import javax.swing.JFrame;
public class testMain {
public static void main(String[] args) {
Main myFrame = new Main();
myFrame.setSize(300,200); //not working
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Can anybody suggest me what's wrong? Thanks.
I wouldn't call setSize() but rather would let my components and the layout managers set their own sizes by calling pack(). Occasionally you might want to override a component's getPreferredSize() but if you do so, do it with extreme care.
Calling pack() does seem to work for me with your code:
import java.awt.FlowLayout;
import java.awt.GridLayout;
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.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestMain {
private static void createAndShowGui() {
LoginForm loginForm = new LoginForm();
loginForm.pack();
loginForm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class LoginForm extends JFrame {
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm() {
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2, 2));
loginArea.add(loginEmail); // add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); // add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1, 2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == submit) {
dispose();
Main main = new Main();
main.pack();
main.setVisible(true);
}
}
}
}
class Main extends JFrame {
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main() {
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1, 3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1, 3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
Note that if this were my project, I'd change it to use a CardLayout to swap views, something like:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestMain2 extends JPanel {
private static final String GUI_NAME = "My GUI";
private CardLayout cardLayout = new CardLayout();
private LoginPanel loginPanel = new LoginPanel();
private HomePanel homePanel = new HomePanel();
public TestMain2() {
setLayout(cardLayout);
add(loginPanel, LoginPanel.NAME);
add(homePanel, HomePanel.NAME);
for (PartyCategory partyCategory : PartyCategory.values()) {
PartyPanel partyPanel = new PartyPanel(partyCategory.getName());
partyPanel.addPropertyChangeListener(PartyPanel.RETURN, new PartyPanelListener());
add(partyPanel, partyCategory.getName());
}
loginPanel.addPropertyChangeListener(LoginPanel.NAME, new LoginPanelListener());
homePanel.addPropertyChangeListener(HomePanel.PARTY_CATEGORY, new HomeListener());
}
private class LoginPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
System.out.println("Submit Pressed");
System.out.println("Login: " + loginPanel.getLogin());
// TODO: Dangerous code!!! Delete this!!!
System.out.println("Password: " + new String(loginPanel.getPassword()));
cardLayout.show(TestMain2.this, HomePanel.NAME);
} else {
System.out.println("Cancel Pressed");
}
}
}
private class HomeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
PartyCategory partyCategory = (PartyCategory) evt.getNewValue();
cardLayout.show(TestMain2.this, partyCategory.getName());
}
}
private class PartyPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
cardLayout.show(TestMain2.this, HomePanel.NAME);
}
}
}
private static void createAndShowGui() {
TestMain2 mainPanel = new TestMain2();
JFrame frame = new JFrame(GUI_NAME);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings({"serial", "hiding"})
class LoginPanel extends JPanel {
public static final String NAME = "Login";
private static final int COLS = 10;
private static final String EMAIL_PROMPT = "Enter Your Email Address:";
private static final String PASSWORD_PROMPT = "Enter Your Password:";
private boolean submitPressed = false;
private JTextField textField = new JTextField(COLS);
private JPasswordField passField = new JPasswordField(COLS);
public LoginPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
buttonPanel.add(new JButton(new ButtonAction("Submit", KeyEvent.VK_S, true)));
buttonPanel.add(new JButton(new ButtonAction("Cancel", KeyEvent.VK_C, false)));
buttonPanel.add(new JButton(new ExitAction()));
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.setBorder(BorderFactory.createTitledBorder(NAME));
innerPanel.add(new JLabel(EMAIL_PROMPT, JLabel.LEADING), getGbc(0, 0));
innerPanel.add(textField, getGbc(1, 0));
innerPanel.add(new JLabel(PASSWORD_PROMPT, JLabel.LEADING), getGbc(0, 1));
innerPanel.add(passField, getGbc(1, 1));
innerPanel.add(buttonPanel, getGbc(0, 2, 2, 1));
add(innerPanel);
}
public boolean isLoginValid() {
return submitPressed;
}
public void setSubmitPressed(boolean submitPressed) {
this.submitPressed = submitPressed;
firePropertyChange(NAME, null, submitPressed);
}
public String getLogin() {
return textField.getText();
}
public char[] getPassword() {
return passField.getPassword();
}
private class ButtonAction extends AbstractAction {
private boolean submitPressed;
public ButtonAction(String name, int mnemonic, boolean submitPressed) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.submitPressed = submitPressed;
}
#Override
public void actionPerformed(ActionEvent e) {
setSubmitPressed(submitPressed);
}
}
private static GridBagConstraints getGbc(int x, int y, int width, int height) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
if (x == 1) {
gbc.insets = new Insets(5, 15, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.EAST;
} else {
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
}
return gbc;
}
private static GridBagConstraints getGbc(int x, int y) {
return getGbc(x, y, 1, 1);
}
}
#SuppressWarnings({"serial", "hiding"})
class HomePanel extends JPanel {
public static final String NAME = "Home";
public static final String PARTY_CATEGORY = "Party Category";
private static final String PROMPT = "Choose Party Category:";
private PartyCategory partyCategory = null;
public HomePanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
for (PartyCategory partyCategory : PartyCategory.values()) {
buttonPanel.add(new JButton(new ButtonListener(partyCategory)));
}
add(new JLabel(PROMPT));
add(buttonPanel);
}
public PartyCategory getPartyCategory() {
return partyCategory;
}
public void setPartyCategory(PartyCategory partyCategory) {
this.partyCategory = partyCategory;
firePropertyChange(PARTY_CATEGORY, null, partyCategory);
}
private class ButtonListener extends AbstractAction {
private PartyCategory partyCategory;
public ButtonListener(PartyCategory partyCategory) {
super(partyCategory.getName());
this.partyCategory = partyCategory;
int mnemonic = partyCategory.getName().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
setPartyCategory(partyCategory);
}
}
}
enum PartyCategory {
BIRTHDAY_PARTY("Birthday Party"),
SUMMER_FESTIVE_PARTY("Summer/Festive Party"),
HALLOWEEN_PARTY("Halloween Party");
private String name;
private PartyCategory(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#SuppressWarnings("serial")
class PartyPanel extends JPanel {
public static final String RETURN = "return";
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public PartyPanel(String name) {
JLabel label = new JLabel(name, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, 48f));
JPanel returnButtonPanel = new JPanel();
returnButtonPanel.add(new JButton(new ReturnAction()));
returnButtonPanel.add(new JButton(new ExitAction()));
setLayout(new BorderLayout());
add(label);
add(returnButtonPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int prefW = Math.max(superSize.width, PREF_W);
int prefH = Math.max(superSize.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class ReturnAction extends AbstractAction {
public ReturnAction() {
super("Return Home");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
#Override
public void actionPerformed(ActionEvent e) {
PartyPanel.this.firePropertyChange(RETURN, null, true);
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
// this will not work for JMenuItem which would require a test to see if coming
// from a pop up first.
Component source = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(source);
win.dispose();
}
}

How do I reference a string in another class?

I am making a login applet to install on my wireless hardrive and am currently building the frameworks for it, (Every time I try to declare the Strings as anything BUT final it shows an error saying only final permitted) I am trying to use the String user and the String pass in if statements which are found in my Skeleton class:
package open;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Skeleton extends JFrame implements ActionListener{
private static final long serialVersionUID = 1248L;
public static void addComponentsToPane(Container pane, Container container) {
//Adding in text fields for login
JButton b1 = new JButton("Login");
final JTextField field2 = new JTextField(2);
final JTextField field = new JTextField(1);
//Creating Box Layout - Subject to change
GroupLayout layout = new GroupLayout(pane);
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
//Setting alignments
b1.setAlignmentX(Component.CENTER_ALIGNMENT);
field.setAlignmentY(BOTTOM_ALIGNMENT);
field2.setAlignmentY(BOTTOM_ALIGNMENT);
b1.setAlignmentY(CENTER_ALIGNMENT);
//Dimensions for User
field.setMaximumSize(new Dimension(235, 20));
field.setMinimumSize(new Dimension(235, 20));
//Dimensions for Password
field2.setMaximumSize(new Dimension(235, 20));
field2.setMinimumSize(new Dimension(235, 20));
//Dimensions for Button
b1.setMaximumSize(new Dimension(100, 40));
b1.setMinimumSize(new Dimension(100, 40));
//Adding space between components
container.add(Box.createRigidArea(new Dimension(275,20)));
container.add(field);
container.add(Box.createRigidArea(new Dimension(275,10)));
container.add(field2);
container.add(Box.createRigidArea(new Dimension(275,12)));
container.add(b1);
//Listen to the login button
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String user = field.getText();
String pass = field2.getText();
System.out.println("Value: " + user + " " + pass);
};
});
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("User Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
addComponentsToPane(frame.getContentPane(), frame);
//Create a grey label
JLabel greyLabel = new JLabel();
greyLabel.setOpaque(true);
greyLabel.setBackground(new Color(205, 209, 209));
greyLabel.setPreferredSize(new Dimension(300, 400));
//Adding the label to the pane
frame.getContentPane().add(greyLabel, BorderLayout.CENTER);
//Display the window.
frame.setSize(275, 175);
frame.setVisible(true);
}
public static void closer(boolean close, JFrame frame){
System.out.println(close);
if(close == true){
frame.setVisible(false);
frame.dispose();
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void actionPerformed(ActionEvent arg0) {
}
}
In my other class there is almost nothing because the class itself relies on importing the String variables
package password;
import open.Skeleton;
import refrence.Resources;
public class PasswordCompare
{
public static void main(String[] args)
{
System.out.println(user);
System.out.println(pass);
}
}
Myself, I would display the above GUI as a modal JDialog, not as a JFrame, I would use a JPasswordField instead of a 2nd JTextField, and I'd give my class public getter methods that would allow the calling class to query the state of its fields, something like
public String getUserName() {
return userNameTextField.getText();
}
and
public char[] getPassword() {
return passwordField.getPassword();
}
Note that passwords should almost never be handled as Strings because doing so would introduce significant vulnerability to your application making it much easier for others to extract passwords.
So as a modal dialog, the calling code is stopped when the dialog is visible, and then only restarts when the dialog is no longer visible, and it is at this point you can query the state of your dialog with the above methods, extracting the pertinent information.
Note that your code uses static methods, something that you don't want to do, as by doing this, your class has no "state", and so querying for the values held by the JTextFields won't work.
Edit
For example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class MySkeleton extends JPanel {
private static final int COLUMN_COUNT = 10;
private static final int I_GAP = 3;
private JTextField userNameField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
public MySkeleton() {
super(new GridBagLayout());
userNameField.setColumns(COLUMN_COUNT);
passwordField.setColumns(COLUMN_COUNT);
GridBagConstraints gbc = getGbc(0, 0, GridBagConstraints.BOTH);
add(new JLabel("User Name:"), gbc);
gbc = getGbc(1, 0, GridBagConstraints.HORIZONTAL);
add(userNameField, gbc);
gbc = getGbc(0, 1, GridBagConstraints.BOTH);
add(new JLabel("Password:"), gbc);
gbc = getGbc(1, 1, GridBagConstraints.HORIZONTAL);
add(passwordField, gbc);
}
public static GridBagConstraints getGbc(int x, int y, int fill) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
gbc.fill = fill;
return gbc;
}
public String getUserName() {
return userNameField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
}
which can be tested in another class via:
public class MySkeletonTest {
private static void createAndShowGui() {
MySkeleton mainPanel = new MySkeleton();
int input = JOptionPane.showConfirmDialog(null, mainPanel, "Login",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (input == JOptionPane.OK_OPTION) {
System.out.println("User Name: " + mainPanel.getUserName());
// **** for testing purposes only. Never do this in a real app.
System.out.println("Password: " + new String(mainPanel.getPassword()));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Are you really sure you need a class just to compare passwords ? This should be the code of your ActionListener. Plus, you don't even instantiate a Skeleton in your code so there is no way you can access those fields. If you really need to do it, just define some getters on Skeleton.
public String getPassword() {
return field2.getText(); //you should really rename this field
}
public String getUser() {
return field.getText(); //you should really rename this field
}

which layout manager would be appropriate to my design?

I am a beginner to Java. I would like some help in Swings to position my components.
I am not able to decide as which layout manager should I use to position my components in the following order
+-----------------------------------+
| |
| Username Text Field |
| Password Password Field |
| |
| Submit button |
| |
+-----------------------------------+
The following is my code
package ssst;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class Test implements ActionListener{
JButton submit;
JFrame j;
JFrame jf;
public Test()
{
j = new JFrame("PLAIN");
j.setBounds(500,150,300,400);
JPanel panel = new JPanel();
j.add(panel);
GridBagLayout gb = new GridBagLayout();
panel.setLayout(gb);
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel("User Name");
c.gridx=0;
c.gridy=0;
c.fill=GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.WEST;
c.ipadx=5;
c.ipady=5;
c.insets= new Insets(7,7,7,7);
panel.add(label,c);
JTextField username = new JTextField(10);
c.gridx=1;
c.gridy=0;
c.fill=GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.WEST;
c.ipadx=5;
c.insets= new Insets(7,7,7,7);
panel.add(username,c);
JLabel password= new JLabel("Password");
c.gridx=0;
c.gridy=1;
c.fill=GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.WEST;
c.ipadx=5;
c.insets= new Insets(7,7,7,7);
panel.add(password,c);
JPasswordField pass = new JPasswordField(10);
c.gridx=1;
c.gridy=1;
c.fill=GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.WEST;
c.insets= new Insets(7,7,7,7);
panel.add(pass,c);
submit = new JButton("Submit");
c.gridx=1;
c.gridy=6;
c.fill=GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.WEST;
c.insets= new Insets(7,7,7,7);
panel.add(submit,c);
submit.addActionListener(this);
j.setVisible(true);
j.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
j.setVisible(false);
jf = new JFrame("NEw Window");
jf.setVisible(true);
jf.setBounds(500,150,300,400);
JPanel panel2 = new JPanel();
panel2.setLayout(null);
jf.add(panel2);
JButton logout = new JButton("LOGOUT");
logout.setBounds(100, 30, 400, 30);
panel2.add(logout);
logout.addActionListener(new Test2());
jf.setDefaultCloseOperation(j.EXIT_ON_CLOSE);
}
class Test2 implements ActionListener{
public void actionPerformed(ActionEvent e) {
jf.dispose();
j.setVisible(true);
}
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Test();
}
}
);
}
}
You could use a GridBagLayout and a JOptionPane
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LoginPane extends JPanel {
private JTextField userName;
private JPasswordField password;
public LoginPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel("Username:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
userName = new JTextField(10);
password = new JPasswordField(10);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(userName, gbc);
gbc.gridy++;
add(password, gbc);
}
public String getUsername() {
return userName.getText();
}
public char[] getPassword() {
return password.getPassword();
}
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) {
}
LoginPane loginPane = new LoginPane();
int option = JOptionPane.showOptionDialog(
null,
loginPane,
"Login",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
new Object[]{"Submit"},
"Submit");
if (option == 0) {
System.out.println("Happy");
}
}
});
}
}
You could possibly use GridLayout with this concept as well.
Take a look at http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html for more ideas and links to other layout managers
go for GridBagLayout, logic of layout is simple. It works on X and Y co-ordinates.
here
Also you should go through other layout as well, it will help you decide in future designs.
Better to use GridBagLayout, in case if u add new components, Layout manager as to take care to fit the components with in the screen if u (maximized/Restore Down).
It is subjective to say what layout manager is appropriate for a
design. This design is a no-brainer for the MigLayout manager.
For a comparison, I provide a solution with a MigLayout.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutLoginEx extends JFrame {
public MigLayoutLoginEx() {
initUI();
setTitle("Log in");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private void initUI() {
setLayout(new MigLayout("ins 15, wrap 2", "[][grow]"));
JLabel lbl1 = new JLabel("User name:");
JTextField field1 = new JTextField(10);
JLabel lbl2 = new JLabel("Password:");
JPasswordField field2 = new JPasswordField(10);
JButton btn = new JButton("Submit");
add(lbl1);
add(field1, "growx");
add(lbl2);
add(field2, "growx");
add(btn, "span 2, center, gaptop 20");
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutLoginEx ex = new MigLayoutLoginEx();
ex.setVisible(true);
}
});
}
}
The layout is achieved with six lines of layout code.

Categories