简体   繁体   中英

Accessing a string from another class in Java

This is slightly different from the usual issue. I know how I would do this if I could set the string to public static String passcode; but the problem is I can't. I need a solution from what I am trying to achieve here:

public class EncryptionSubtask {


public static void main(String[] args) {
    Main m2 = new Main();
    m2.setVisible(true);
    m2.setResizable(true);
    m2.setLayout(new FlowLayout());
}

public EncryptionSubtask() {
    log("Running Substask");
    Random rand = new Random();
    int n1 = 33 + rand.nextInt(94);
    int n2 = 33 + rand.nextInt(94);
    int n3 = 33 + rand.nextInt(94);
    int n4 = 33 + rand.nextInt(94);
    int n5 = 33 + rand.nextInt(94);
    int n6 = 33 + rand.nextInt(94);
    int n7 = 33 + rand.nextInt(94);
    int n8 = 33 + rand.nextInt(94);

    String c1 = Character.toString ((char) n1);
    String c2 = Character.toString ((char) n2);
    String c3 = Character.toString ((char) n3);
    String c4 = Character.toString ((char) n4);
    String c5 = Character.toString ((char) n5);
    String c6 = Character.toString ((char) n6);
    String c7 = Character.toString ((char) n7);
    String c8 = Character.toString ((char) n8);


    String passcode = (c1+c2+c3+c4+c5+c6+c7+c8);

    System.out.println(passcode);

}

Where I want to get "passcode" to here:

public class Main extends Frame implements Runnable, KeyListener, MouseListener, WindowListener {

private static final long serialVersionUID = 1L;
Thread thread;
BufferedImage backbuffer;
Graphics2D g2d;
AffineTransform transform = new AffineTransform();

enum Modes {
    Menu, Encrypt, Decrypt
}

Modes mode = Modes.Menu;

public Image background;

public static void main(String[] args) {
    Main m = new Main();
    m.setVisible(true);
    m.setResizable(true);
    m.setLayout(new FlowLayout());
}

@Override
public void windowActivated(WindowEvent e) {
}

@Override
public void windowClosed(WindowEvent e) {
}

@Override
public void windowClosing(WindowEvent e) {
    dispose();
    log("Exiting...");
    System.exit(0);
}

@Override
public void windowDeactivated(WindowEvent e) {
}

@Override
public void windowDeiconified(WindowEvent e) {
}

@Override
public void windowIconified(WindowEvent e) {
}

@Override
public void windowOpened(WindowEvent e) {
}

@Override
public void mouseClicked(MouseEvent e) {
    int x = e.getX() - 8;
    int y = e.getY() - 30;
    // System.out.println(y);
    if (x >= 50 && x <= 143 && y >= 50 && y <= 75) { //if statement for encrypt button bounds
        log("Button Pressed. Encrypt Screen Opened.");
        // Frame f = new Frame();
        // f.setVisible(true);
        // f.setSize(100, 100);
        mode = Modes.Encrypt;
        new EncryptionSubtask();
    }
    if (x >= 500 && x <= 595 && y >= 50 && y <= 75) { // if statement for decrypt button bounds
        log("Button Pressed. Decrypt Screen Opened.");
        mode = Modes.Decrypt;
    }
}

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

@Override
public void mousePressed(MouseEvent e) {
}

@Override
public void mouseReleased(MouseEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    System.out.println("Key pressed = " + key);
    if (key == 27) {
        mode = Modes.Menu;
    }
}

@Override
public void keyReleased(KeyEvent e) {
}

@Override
public void keyTyped(KeyEvent e) {
}

public enum LogLevel {
    Info, Warn
}

private static int width = 300;
private static int height = width / 16 * 9;
private static int scale = 3;

public Main() {
    addWindowListener(this);
    log("Initialising...");
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    this.start();
    log("Setting title...");
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    this.setTitle("LOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOL");
    log("Creating backbuffer for window...");
    setSize(width * scale, height * scale);
    backbuffer = new BufferedImage(640 * 3, 480 * 2, BufferedImage.TYPE_INT_RGB);
    log("Buffering Image, standby...");
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    g2d = backbuffer.createGraphics();

    File fileThis = new File(System.getProperty("java.class.path"));
    File parentFile = fileThis.getAbsoluteFile().getParentFile(); // the
                                                                    // project
                                                                    // folder
    log(parentFile.getAbsolutePath());
    File resources = new File(parentFile.toString() + "/resources/");
    log(resources.getAbsolutePath());
    try {
        background = ImageIO.read(new File(resources + "/guitar.jpg")); // CHANGE
                                                                        // THIS
                                                                        // IMAGE!
        File tempFile = new File(resources + "/guitar.jpg");
        log(tempFile.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }



    addKeyListener(this);
    addMouseListener(this);
}

@Override
public void run() {
    Thread t = Thread.currentThread();

    while (t == thread) {
        try {
            // log("Running...");
            Thread.sleep(20);
        } catch (Exception e) {
            e.printStackTrace();
        }
        repaint();
    }
}

public void start() {
    thread = new Thread(this);
    thread.start();
}

public void stop() {
    try {
        thread.join();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void update(Graphics g) {
    g2d.setTransform(transform);
    g2d.setPaint(Color.black);
    g2d.fillRect(0, 0, getWidth(), getHeight());
    switch (mode) {
    case Menu:
        g2d.drawImage(background, 0, 0, getWidth(), getHeight(), this);
        g2d.setPaint(Color.blue);
        g2d.fillRect(50, 50, 93, 25);
        g2d.fillRect(500, 50, 95, 25);
        g2d.setPaint(Color.red);
        g2d.setFont(new Font("TimesRoman", Font.PLAIN, 30));
        g2d.drawString("Encrypt", 50, 70);
        g2d.drawString("Decrypt", 500, 70);
        break;
    case Encrypt:
        g2d.setPaint(Color.green);
        g2d.drawString("Encrypt screen", 50, 70);
        break;
    case Decrypt:
        g2d.setPaint(Color.green);
        g2d.drawString("Decrypt Screen", 50, 70);
        break;
    }

    paint(g);
}

public void log(String s) {
    log(s, 0, 0);
}

public void log(String s, int i) {
    log(s, i, 0);
}

public void log(String s, int i, int j) {
    String logmsg = "";
    for (int k = 0; k < i; k++) {
        logmsg += "  ";
    }
    if (j == 0) {
        logmsg = "[Info]" + logmsg;
    } else {
        logmsg = "[Warn]" + logmsg;
    }
    System.out.println("[" + System.currentTimeMillis() + "]["
            + Thread.currentThread().getStackTrace()[1].toString() + "]" + logmsg + s);
}

public void paint(Graphics g) {
    g.drawImage(backbuffer, 8, 31, this);
}

}

So that I can use it to be drawn to my frame etc.

Okay, you call the constructor of EncryptionSubtask in the mouseClicked method and you do nothing with it.

First of all, you need to assign it to a variable, like this:

EncryptionSubtask veryStrangeTask = new EncryptionSubtask();

Than have the local variable passcode as a class field like this:

public class EncryptionSubtask {
String passcode;
...
}

Now you can use this field in your "other" class with

veryStrangeTask.passcode;

Maybe an Observer?

You could create an interface which has a method to pass your passcode

public interface PasscodeNotify{
    public void notifyPasscode(String passcode);
}

Then you modify EncryptionSubtask constructor to accept an instance of this class, this way:

public EncryptionSubtask(PasscodeNotify observer) {
    ...
    if(observer != null)
        observer.notifyPasscode(c1+c2+c3+c4+c5+c6+c7+c8);
}

And finally you make that your Main class implements another interface, the PasscodeNotify I just created, and implements the method to retrieve your passcode.

Does it serves your purpose?

Hope it helps!

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