Home >Java >I want to use the input from jtextfield as an array list in another class

I want to use the input from jtextfield as an array list in another class

WBOY
WBOYforward
2024-02-08 21:20:20843browse

php editor Baicao is here to answer your question: If you want to use the content input from JTextField as an array list in another class, you can follow the steps below. First, get the content entered in the JTextField and save it to a variable. Then, create an ArrayList object in another class and add the saved content to the list. This way you can use the array list in another class. Remember to perform appropriate exception handling and data type conversion to ensure that the input content is added to the list correctly. Hope this short answer helps!

Question content

If I try to add the jtextfield to another class after clicking the submit button, it won't work because the other class tries to get the array list before updating

import java.util.*;
import java.io.*;
import javax.swing.swingutilities;

public class blackjackmain { 
    public static void main(string [] args) {
          blackjackguiclass content = new blackjackguiclass();
     
          arraylist<string> hi = new arraylist<string>();
          content.outputgui();
          hi = content.newacc;
    }
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;



public class BlackjackGUIClass implements ActionListener {
    
    GridBagLayout ez;
    GridBagConstraints gg;
    private JFrame gui;
    private JPanel content;
    private JLabel title;
    private JTextField usern;
    private JLabel userent;
    private JButton login;
    private JTextField passw;
    private JLabel passent;  
    private JButton create;
    ArrayList<String> logacc = new ArrayList<String>();
    ArrayList<String> newacc = new ArrayList<String>();
    int check = 0;
    
    public BlackjackGUIClass() {
    }
    
            
    public void outputGUI () {
    
    
    gui = new JFrame("Blackjack Menu");
    content = new JPanel();
     gui.add(content);
     
     
     ez = new GridBagLayout();    
     gg = new GridBagConstraints();
     content.setLayout(ez);
   
     
    title = new JLabel ("Abel's Blackjack Casino");
    usern = new JTextField(30);
    usern.setPreferredSize(new Dimension(10, 60));
    userent = new JLabel ("Enter Username: ");
    login = new JButton("Login");
    login.setPreferredSize(new Dimension(300, 50));
    create = new JButton("Create Account");
    create.setPreferredSize(new Dimension(300, 50));
    
    passw = new JTextField(30);
    passw.setPreferredSize(new Dimension(10, 60));
    passent = new JLabel ("Enter Password: ");
    
    login.addActionListener(this);
    create.addActionListener(this);
    passw.addActionListener(this);
    usern.addActionListener(this);
     
    Font createSize = new Font("Times New Roman", Font.PLAIN, 50);
    Font second = new Font("", Font.PLAIN, 30);
    
    title.setFont(createSize);
    userent.setFont(second);
    passent.setFont(second);
     gg.insets = new Insets(5, 5, 5, 5);
   
    gg.gridx = 1;
    gg.gridwidth = 3;
    gg.gridy = 0;
    content.add(title, gg);
    
    
    gg.gridx = 2;
    gg.gridwidth = 1;
    gg.gridy = 1;
    content.add(usern, gg);
    
    
    gg.gridx = 1;
    content.add(userent, gg);
    
   
   
   gg.gridy = 2;
   gg.gridx = 1;
   content.add(passent, gg);
   
   gg.gridx = 2;
   content.add(passw, gg);
   
   gg.gridy = 3;
   gg.gridx = 1;
   gg.gridwidth = 1;
   content.add(login, gg);
   
   gg.gridy = 3;
   gg.gridx = 2;
   gg.gridwidth = 1;
   content.add(create, gg);
   
    
    
    gui.setExtendedState(JFrame.MAXIMIZED_BOTH);    
    gui.setLocationRelativeTo(null);
    gui.setVisible(true);
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public void actionPerformed(ActionEvent e) {
        BlackjackMain wow = new BlackjackMain();
        
        if (e.getSource() == login) {
            logacc.add(usern.getText());
            logacc.add(passw.getText());
            
        } else if (e.getSource() == create) {
            newacc.add(usern.getText());
            newacc.add(passw.getText());
        }
        gui.dispose();
    }
    
}

I tried setting an arraylist in the main class that is equal to the arraylist in the gui class that is being updated, but it tries to update before adding the input from the jtextfield

Workaround

Like most GUIs, swing is an event driven environment, that is, something happens and you respond to it (see actionlistener, you don't know when it might be operation, knowing only that it may be operated on at some point in the future).

When you call setvisible on a jframe, the call will return immediately, and at some point in the future, the window will become visible.

This means that in your code you are trying to get the details before the user has a chance to enter anything.

Instead, use pattern jdialog (see How to use dialogs for more details) and/or Observer pattern to determine when to respond Take action on user input.

import java.awt.Dimension;
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 static java.lang.ref.Cleaner.create;
import java.util.ArrayList;
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;

/**
 *
 * @author Mad
 */
public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new BlackjackGUIClass(new BlackjackGUIClass.Observer() {
                    @Override
                    public void createUser(String name, char[] password) {
                        frame.dispose();
                        JOptionPane.showMessageDialog(null, "A new user will be created", "Make it so", JOptionPane.PLAIN_MESSAGE);
                    }

                    @Override
                    public void authenticateUser(String name, char[] password) {
                        frame.dispose();
                        JOptionPane.showMessageDialog(null, "You will be authenticated", "Make it so", JOptionPane.PLAIN_MESSAGE);
                    }
                }));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class BlackjackGUIClass extends JPanel {

        public interface Observer {
            public void createUser(String name, char[] password);
            public void authenticateUser(String name, char[] password);
        }

        private Observer observer;

        public BlackjackGUIClass(Observer observer) {
            this.observer = observer;
            GridBagLayout ez = new GridBagLayout();
            GridBagConstraints gg = new GridBagConstraints();
            setLayout(ez);

            JLabel title = new JLabel("Abel's Blackjack Casino");
            JTextField usern = new JTextField(30);
            JLabel userent = new JLabel("Enter Username: ");
            JButton login = new JButton("Login");
            JButton create = new JButton("Create Account");

            JPasswordField passw = new JPasswordField(30);
            JLabel passent = new JLabel("Enter Password: ");

            login.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // This is a repeating pattern and you should consider taking
                    // the time make a re-usable solution
                    String userName = usern.getText();
                    char[] password = passw.getPassword();                    
                    // Could make use of a delegate to validate the password
                    if (userName.isBlank()) {
                        JOptionPane.showMessageDialog(BlackjackGUIClass.this, "User name can't be empty", "Error", JOptionPane.PLAIN_MESSAGE);
                        return;
                    }
                    if (password.length == 0) {
                        JOptionPane.showMessageDialog(BlackjackGUIClass.this, "User name can't be empty", "Error", JOptionPane.PLAIN_MESSAGE);
                        return;
                    }
                    observer.authenticateUser(userName, password);
                }
            });
            create.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // This is a repeating pattern and you should consider taking
                    // the time make a re-usable solution
                    String userName = usern.getText();
                    char[] password = passw.getPassword();                    
                    // Could make use of a delegate to validate the password
                    if (userName.isBlank()) {
                        JOptionPane.showMessageDialog(BlackjackGUIClass.this, "User name can't be empty", "Error", JOptionPane.PLAIN_MESSAGE);
                        return;
                    }
                    if (password.length == 0) {
                        JOptionPane.showMessageDialog(BlackjackGUIClass.this, "User name can't be empty", "Error", JOptionPane.PLAIN_MESSAGE);
                        return;
                    }
                    observer.createUser(userName, password);
                }
            });

            Font createSize = new Font("Times New Roman", Font.PLAIN, 50);
            Font second = new Font("", Font.PLAIN, 30);

            title.setFont(createSize);
            userent.setFont(second);
            passent.setFont(second);
            gg.insets = new Insets(5, 5, 5, 5);

            gg.gridx = 1;
            gg.gridwidth = 3;
            gg.gridy = 0;
            add(title, gg);

            gg.gridx = 2;
            gg.gridwidth = 1;
            gg.gridy = 1;
            add(usern, gg);

            gg.gridx = 1;
            add(userent, gg);

            gg.gridy = 2;
            gg.gridx = 1;
            add(passent, gg);

            gg.gridx = 2;
            add(passw, gg);

            gg.gridy = 3;
            gg.gridx = 1;
            gg.gridwidth = 1;
            add(login, gg);

            gg.gridy = 3;
            gg.gridx = 2;
            gg.gridwidth = 1;
            add(create, gg);
        }
    }
}

I also don't encourage you to use setpreferredsize, which can have adverse effects on different platforms.

The above is the detailed content of I want to use the input from jtextfield as an array list in another class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete