简体   繁体   中英

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM