NarinderRSharma NarinderRSharma - 6 months ago 17
Java Question

How to randomly set a JFrame with a simple message

So I've checked out the other post which didn't help on here, I'm trying to get my frame with it's message to randomly appear on an area on the screen but when I run it, it says x and y cannot be resolved to a variable, here's the code:

public class MyFrame extends JFrame{
MyFrame(int width, int height, int x, int y){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("R and Ts Main Frame");
setSize(width, height);

Random random = new Random();
x = random.nextInt();
y = random.nextInt();
setLocation(x, y);

JLabel label = new JLabel("Random Message");
label.setFont(new Font("Impact", Font.BOLD|Font.PLAIN, height/3));
label.setForeground(Color.BLUE);
getContentPane().add(label);
}


}

and this is my main:

public class OurMain {

public static void main(String[] args) {
Dimension sSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = sSize.width;
JFrame f = new MyFrame(w/3, 100, x, y); //my errors are underlined here under the x and y
f.setVisible(true);
}


}

Answer

This will solve your problem. You did not declare/create x and y before using them, but you don't need them, so just use them locally.

public class OurMain {
    public static void main(String[] args) {
        Dimension sSize = Toolkit.getDefaultToolkit().getScreenSize();
        int w = sSize.width;
        JFrame f = new MyFrame(w/3, 100); // No x and/or y needed
        f.setVisible(true);
}

public class MyFrame extends JFrame{
    public MyFrame(int width, int height){ // Erase x and y on the constructor
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("R and Ts Main Frame");
        setSize(width, height);

        Random random = new Random();
        // Create x and y here
        int x = random.nextInt();
        int y = random.nextInt();
        setLocation(x, y);

        JLabel label = new JLabel("Random Message");
        label.setFont(new Font("Impact", Font.BOLD|Font.PLAIN, height/3));
        label.setForeground(Color.BLUE);
        getContentPane().add(label);
    }
}