-5

I am making a "fake virus" in java. when you run it a window called "Your computer has a virus" pops up and the window has a button that says "Your computer has (1) viruses. Click here to uninstall them" but when you click it one more window pops up. but i want it to be like each time you click it the number of "viruses" is added 1 to. (For example the second window that pops up after clicking button says "Your computer has (2) viruses"). I have tried to add it but it didn't work. (sorry for my terrible grammar). Here is my code:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;


    public class FirstWindow extends JFrame {

    int virusAmount = 1;
    private static final long serialVersionUID = 1L;

    public FirstWindow(){
        super("Your computer has a virus");
        setSize(400, 75);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel p = new JPanel();
        JButton b = new JButton("Your computer has (" + virusAmount++ + ") virus(es). Click here to uninstall them.");
        b.addActionListener(new ActionListener() {          

            public void actionPerformed(ActionEvent e) {
                FirstWindow f2 = new FirstWindow();
                f2.setVisible(true);
            }
        });     
        p.add(b);       
        add(p); 
     }  
   }
mKorbel
  • 109,525
  • 20
  • 134
  • 319

1 Answers1

2

Just define it in the constructor:

public FirstWindow(int i){}

Full example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FirstWindow extends JFrame {
    int virusAmount;
    private static final long serialVersionUID = 1L;
    public FirstWindow(int i) {
        virusAmount = i;
        setSize(400, 75);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        JButton b;
        if(virusAmount == 1){
            b = new JButton("Your computer has a virus");
        }
        else{
            b = new JButton("Your computer has (" + virusAmount + ") virus(es). Click here to uninstall them.");
        }
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                FirstWindow f2 = new FirstWindow(virusAmount+1);
                f2.setVisible(true);
            }
        });
        p.add(b);
        add(p);
    }
}



public class Main {
    public static void main(String[] args) {
        FirstWindow fw = new FirstWindow(1);
        fw.setVisible(true);
    }
}
Community
  • 1
  • 1
Mansueli
  • 6,223
  • 8
  • 33
  • 57