问题描述
我想写一些程序。定义了程序应运行的周期数。用户在Jtextfield中插入文本。每次用户点击进入时,都会计算一个周期,并且应再次创建相同的JFrame。重复此过程,直到达到最大值。达到循环数。程序将创建另一个Jframe。我尝试编写代码,但是该程序并没有增加循环数。
public class oneJFrame extends javax.swing.JFrame {
private int Cycles = 0;
public oneJFrame() {
initComponents();
}
private void clsWinBtnActionPerformed(java.awt.event.ActionEvent evt) {
// Todo add your handling code here:
dispose();
}
protected void playerNameFieldActionPerformed(java.awt.event.ActionEvent evt) {
// Todo add your handling code here:
if (Cycles <= 4) {
System.out.println(Cycles );
dispose();
oneJFrame JFrame1 = new oneJFrame();
JFrame1.setVisible(true);
Cycles++;
} else {
anotherJFrame Jframe2 = new anotherJFrame ();
Jframe2.setVisible(true);
}
}
我想我知道我所遇到的问题:每当If语句为true且Jframe被处理并创建一个新的语句时,将int Cycles设置为0。如果这是问题,我不知道解决这个问题。是否需要处置Jframe或是否有一种方法只是将文本保存在文本字段中,然后重新加载框架?还是我还能做些其他事情?
我正在使用NetBeans GUI构建器。
解决方法
之所以发生这种情况,是因为当您创建新的OneFrame
时,会创建新的Cycles
并自动等于0。
要解决此问题,请将变量Cycles
更改为static
,这样将为您将创建的每个OneFrame
分配1个变量,并且不会在每次创建新的{{1 }}。
例如,使用:
OneFrame
代替:
private static int Cycles = 0;