我在java中制作一个“假病毒”。当你运行它时会弹出一个名为“你的计算机有病毒”的窗口,窗口上有一个按钮,上面写着“你的计算机有(1)个病毒。单击此处卸载它们”但是当你点击它时会弹出另一个窗口。但我想让它像每次点击它一样,“病毒”的数量加1。 (例如,单击按钮后弹出的第二个窗口显示“您的计算机有(2)个病毒”)。我试图添加它但它没有用。 (对不起我可怕的语法)。这是我的代码:
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);
}
}
答案 0 :(得分:2)
只需在构造函数中定义:
public FirstWindow(int i){}
完整示例:
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);
}
}