How do I reference a string in another class?

Jackson Haile

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);
    }
}
Hovercraft Full Of Eels

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();
         }
      });
   }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

How to reference a class in another project?

분류에서Dev

How do I convert a reference cell to a string in Excel?

분류에서Dev

How do I use a HashMap from another class or function?

분류에서Dev

How can I do an array of object of my class (with inheritance of another custom class)?

분류에서Dev

How do i open a class from within another class by selecting an item on ToolBar?? Python/PyQt

분류에서Dev

How do I return the result of a class-based view from another class-based view in Django?

분류에서Dev

How do I set the value of my field so that I can call it from another class?

분류에서Dev

How to reference another style class for complex selectors with material-ui

분류에서Dev

How do I pass a single Firestore document ID to another class based on a selection using Flutter/Dart?

분류에서Dev

How do i set the text of a TextView to a value of an integer from another class

분류에서Dev

Why do you need to attach or reference and object when accessing another class variable in unity?

분류에서Dev

How do I use the GeometryConstraint class?

분류에서Dev

Excel: How do I reference an entire row except for a couple of cells?

분류에서Dev

How do I reference a subclass's parent view controller?

분류에서Dev

How do I reference a clicked point on a ggvis plot in Shiny

분류에서Dev

Unable to reference one class library from another

분류에서Dev

How do I get a records for a table that do not exist in another table?

분류에서Dev

How can I pass the stringbuilder and display out in another class

분류에서Dev

How do I print the matched string?

분류에서Dev

How do I convert an integer to string in CakePHP?

분류에서Dev

How do I parse a string into a record in Haskell?

분류에서Dev

How do I convert my string?

분류에서Dev

How do I Split a string by empty lines?

분류에서Dev

How to drop all variables that do not cointain a string or another in R

분류에서Dev

How to pass an object of a class with a string data member to another class in C++

분류에서Dev

ON clicking of a span how do I change content of another div?

분류에서Dev

How do i copy files from one directory to another directory?

분류에서Dev

How do I make one thread Kill another?

분류에서Dev

How do I return an object from another model in a scope?

Related 관련 기사

  1. 1

    How to reference a class in another project?

  2. 2

    How do I convert a reference cell to a string in Excel?

  3. 3

    How do I use a HashMap from another class or function?

  4. 4

    How can I do an array of object of my class (with inheritance of another custom class)?

  5. 5

    How do i open a class from within another class by selecting an item on ToolBar?? Python/PyQt

  6. 6

    How do I return the result of a class-based view from another class-based view in Django?

  7. 7

    How do I set the value of my field so that I can call it from another class?

  8. 8

    How to reference another style class for complex selectors with material-ui

  9. 9

    How do I pass a single Firestore document ID to another class based on a selection using Flutter/Dart?

  10. 10

    How do i set the text of a TextView to a value of an integer from another class

  11. 11

    Why do you need to attach or reference and object when accessing another class variable in unity?

  12. 12

    How do I use the GeometryConstraint class?

  13. 13

    Excel: How do I reference an entire row except for a couple of cells?

  14. 14

    How do I reference a subclass's parent view controller?

  15. 15

    How do I reference a clicked point on a ggvis plot in Shiny

  16. 16

    Unable to reference one class library from another

  17. 17

    How do I get a records for a table that do not exist in another table?

  18. 18

    How can I pass the stringbuilder and display out in another class

  19. 19

    How do I print the matched string?

  20. 20

    How do I convert an integer to string in CakePHP?

  21. 21

    How do I parse a string into a record in Haskell?

  22. 22

    How do I convert my string?

  23. 23

    How do I Split a string by empty lines?

  24. 24

    How to drop all variables that do not cointain a string or another in R

  25. 25

    How to pass an object of a class with a string data member to another class in C++

  26. 26

    ON clicking of a span how do I change content of another div?

  27. 27

    How do i copy files from one directory to another directory?

  28. 28

    How do I make one thread Kill another?

  29. 29

    How do I return an object from another model in a scope?

뜨겁다태그

보관