I have a problem with a piece of code. When I click on it in my GUI, it reopens once I've inputted text. Can anyone explain to me what is wrong with the code. I'm using this to set a name in a JLabel in my GUI
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom" + "baker";
usernameinput = JOptionPane.showInputDialog(
setNameButton, "Enter a username",
"Set username", JOptionPane.OK_CANCEL_OPTION);
{
username.setText(String.valueOf(usernameinput));
}
});
I've created a simple GUI to test your code and the dialog opens just once.
I have cleaned up a bit your listener, but basically it's the same code.
Your problem may be in another part of your code.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleFrameTest extends JFrame {
JLabel username = new JLabel("Press button to enter your name here");
public SimpleFrameTest() {
setSize(300, 300);
setTitle("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
initComponents();
setVisible(true);
}
private void initComponents() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
username.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton setNameButton = new JButton("Set name");
setNameButton.setAlignmentX(Component.CENTER_ALIGNMENT);
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput = JOptionPane.showInputDialog(setNameButton, "Enter a username", "Set username", JOptionPane.OK_CANCEL_OPTION);
if (usernameinput != null) {
username.setText(String.valueOf(usernameinput));
}
});
panel.add(Box.createRigidArea(new Dimension(5,10)));
panel.add(username);
panel.add(Box.createRigidArea(new Dimension(5,10)));
panel.add(setNameButton);
add(panel);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleFrameTest();
}
});
}
}
your code is behaving like that because of this
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom"
+ "baker";
usernameinput = JOptionPane.showInputDialog(null,
as you can see, the JOptionPane.showInputDialog(setNameButton is taking the setNameButton as a parameter so you are in some kind of recursive infinite loop
use another button for the modalDialog:
Example:
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom"
+ "baker";
usernameinput = JOptionPane.showInputDialog(null, "Enter a username", "Set username", JOptionPane.OK_CANCEL_OPTION);
{
username.setText(String.valueOf(usernameinput));
}
});
Related
I made a BoxLayout GUI and i'm wondering how i'd use an actionlistener to make the button close the window. If I try to put in RegisterNew.setVisible(false); in an actionlistener, it gives me an error
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RegisterNew extends JFrame
{
public RegisterNew(int axis){
// creates the JFrame
super("BoxLayout Demo");
Container con = getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(new JTextField());
con.add(new JLabel("Enter your password"));
con.add(new JTextField());
con.add(new JButton("Create Account"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[])
{
RegisterNew newDemo = new RegisterNew(BoxLayout.Y_AXIS);
}
}
I'm also trying to link this to ANOTHER GUI so that when you press a button, this one appears, but it gives me the same error as if i put
RegisterNew.setVisible(true); into the action listener
If that's a subordinate dialog window, then use a JDialog, not a JFrame.
If your ActionListener is an inner class then use RegisterNew.this.close();
Else you can get the window ancestor for the JButton using SwingUtilities.getWindowAncestor(button) and call close() or better dispose() on the Window returned.
Note that BoxLayout and layout managers in general have nothing to do with your current problem.
e.g.,
Test class that shows the new register dialog and that extracts information from it.
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestRegistration extends JPanel {
private JTextArea textArea = new JTextArea(30, 60);
public TestRegistration() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ShowRegisterNewAction()));
textArea.setFocusable(false);
textArea.setEditable(false);
setLayout(new BorderLayout());
add(new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
add(bottomPanel, BorderLayout.PAGE_END);
}
private class ShowRegisterNewAction extends AbstractAction {
private RegisterNew registerNew = null;
public ShowRegisterNewAction() {
super("Show Register New Dialog");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
if (registerNew == null) {
JButton btn = (JButton) e.getSource();
Window window = SwingUtilities.getWindowAncestor(btn);
registerNew = new RegisterNew(window, BoxLayout.PAGE_AXIS);
}
registerNew.setVisible(true);
String userName = registerNew.getUserName();
String password = new String(registerNew.getPassword());
textArea.append("User Name: " + userName + "\n");
textArea.append("Password: " + password + "\n");
textArea.append("\n");
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestRegistration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestRegistration());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
New Register class that holds the dialog and has code for displaying it and for extracting information from it. Uses BoxLayout.
import java.awt.Container;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class RegisterNew {
private JDialog dialog = null;
private JTextField nameField = new JTextField(10);
private JPasswordField passField = new JPasswordField(10);
public RegisterNew(Window window, int axis) {
dialog = new JDialog(window, "Register New", ModalityType.APPLICATION_MODAL);
Container con = dialog.getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(nameField);
con.add(new JLabel("Enter your password"));
con.add(passField);
con.add(new JButton(new AcceptAction()));
dialog.pack();
dialog.setLocationRelativeTo(window);
}
public char[] getPassword() {
return passField.getPassword();
}
public String getUserName() {
return nameField.getText();
}
public void setVisible(boolean b) {
dialog.setVisible(b);
}
private class AcceptAction extends AbstractAction {
public AcceptAction() {
super("Accept");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
}
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
}
}
This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().
Using pure java, I would like to have a player press a JButton, have a text box pop up which they can type in, and then have a certain action happen when the player presses "Enter".
How could I do this?
I have not yet attempted this because I do not know where to start, however my current code is
package Joehot200;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main extends JFrame {
static boolean start = false;
private JPanel contentPane;
/**
* Launch the application.
*/
static Main frame = null;
String version = "0.4";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Main();
frame.setVisible(true);
frame.setTitle("Privateers");
} catch (Exception e) {
e.printStackTrace();
}
}
});
TerrainDemo.startGame();
}
boolean cantConnect = false;
/**
* Create the frame.
*/
public Main() {
setExtendedState(JFrame.MAXIMIZED_BOTH);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
final JButton btnEnterBattlefield = new JButton("Enter battlefield!");
btnEnterBattlefield.setForeground(Color.red);
//btnEnterBattlefield.setBackground(Color.green);
//btnEnterBattlefield.setOpaque(true);
menuBar.add(btnEnterBattlefield);
btnEnterBattlefield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println(new File(System.getProperty("user.dir") + "res/images/heightmap.bmp").getAbsolutePath());
//System.out.println("You clicked the button");
if (cantConnect){
btnEnterBattlefield.setText("Unable to connect to the server!");
}else{
btnEnterBattlefield.setText("Connecting to server...");
}
start = true;
}
});
//JMenu mnLogIn = new JMenu("Log in");
JMenu mnLogIn = new JMenu("Currently useless button");
mnLogIn.setForeground(Color.magenta);
menuBar.add(mnLogIn);
JButton btnLogIntoGame = new JButton("Log into game.");
mnLogIn.add(btnLogIntoGame);
JButton btnRegisterNewAccount = new JButton("Register new account");
mnLogIn.add(btnRegisterNewAccount);
final JButton btnGoToWebsite = new JButton("We currently do not but soon will have a website.");
btnGoToWebsite.setForeground(Color.BLUE);
//btnGoToWebsite = new JButton("Go to website.");
btnGoToWebsite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("Going to website!");
try {
java.awt.Desktop.getDesktop().browse(new URI("www.endcraft.net/none"));
} catch (Exception e1) {
btnGoToWebsite.setText("Error going to website!");
}
}
});
menuBar.add(btnGoToWebsite);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
FlowLayout flowLayout = (FlowLayout) contentPane.getLayout();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
ImageIcon icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
Image img = icon.getImage() ;
Image newimg = img.getScaledInstance(this.getWidth()*3, this.getHeight()*3, java.awt.Image.SCALE_SMOOTH ) ;
icon = new ImageIcon( newimg );
JLabel background=new JLabel(icon);
getContentPane().add(background);
background.setLayout(new FlowLayout());
//JProgressBar progressBar = new JProgressBar();
//contentPane.add(progressBar);
//JMenu mnWelcomeToA = new JMenu("Welcome to a pirate game!");
//contentPane.add(mnWelcomeToA);
//JButton btnStartGame = new JButton("Start game");
//mnWelcomeToA.add(btnStartGame);
//JSplitPane splitPane = new JSplitPane();
//mnWelcomeToA.add(splitPane);
//JButton btnRegister = new JButton("Register");
//splitPane.setLeftComponent(btnRegister);
//JButton btnLogin = new JButton("Login");
//splitPane.setRightComponent(btnLogin);
}
}
It is the "Register account" and "Log into game" button that I would like to have the above described action happen on.
Would be great if someone could tell me how to do this.
If you decide to implement a new frame (not best practice), with a new panel, and the JTextField or JTextArea within, you must bind a listener to the button that calls setVisible() on the newly created frame..
For example:
public void actionPerformed(ActionEvent e) {
yourFrame.setVisible(true);
}
Further, you could create the frame everytime the button is clicked, within the actionPerformed method aswell, however this is also not best practice..
A better alternative may be to implement a JOptionPane, see here or here..
I am currently working on an applet and am having a bit of trouble finishing it off. My code works just fine however I need to change the final portion from a JOptionDialog Message Dialog into just a JLabel that gets added to the applet. I've tried every way I can think of and am still coming up short. My current code looks as followed:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
JOptionPane.showMessageDialog(null, "Access Granted");
return
}
else {
JOptionPane.showMessageDialog(null, "Access Denied");
}
}
}
}
Please help!
Try this one:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
JLabel message = new JLabel();
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.add(message);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
message.setText("Access Granted");
return;
}
else {
message.setText("Access Denied");
}
}
}
}
Its sample code so no alignment is done it will show message next to button. You can change alignment as you wish ;)
when I click the OK button in second.java program, the program exit the program. I want it not to exit (since there is a thread running). I tried removing setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).
CODE
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.JTextField;
public class second extends JFrame implements ActionListener {
JLabel enterName;
JTextField name;
JButton click;
String storeName;
public second(){
setLayout(null);
setSize(300,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
enterName = new JLabel("Enter Your Name: ");
click = new JButton("Click");
name = new JTextField();
enterName.setBounds(60,30,120,30);
name.setBounds(80,60,130,30);
click.setBounds(100,190,60,30);
click.addActionListener(this);
add(click);
add(name);
add(enterName);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == click) {
storeName = name.getText();
JOptionPane.showMessageDialog(null, "Hello" + storeName);
System.exit(0);
}
}
public static void main(String args[]){
second s = new second();
s.setVisible(true);
}
}
Many Thanks
You'll need to remove the System.exit(0); line. That's all.