gpt4 book ai didi

java - 如何从java中另一个类的主类访问int?

转载 作者:行者123 更新时间:2023-12-01 22:31:25 24 4
gpt4 key购买 nike

我有一个 int a;在主类中,我想在 Action Listner 类中使用它。我已经检查了答案,但并没有真正理解我必须做什么,因为我仍然只是任何类型编程的初学者,所以如果可能的话,我真的很感激一个简单的解决方案。

这是我的代码:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;

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


public class Start {
public static void main(String[] args){
JFrame okno = new JFrame("Nonogram");
okno.setVisible(true);
okno.setSize(700, 700);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
okno.add(panel);

JButton [][] gumbi = new JButton[15][15];

JPanel polje = new JPanel(new GridLayout(15, 15));
panel.add(polje, BorderLayout.CENTER);
int a = 1;
int b = 1;

for(int i = 0; 0 < 15; i++){
for(int j = 0; j < 15; j++){
if(i < 5 && j < 5){
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.RED);
//gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
}else if(i < 5 || j < 5){
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.YELLOW);

//gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
gumbi[i][j].setEnabled(false);

}else{
if(Math.random() <= 0.6){
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("3");
polje.add(gumbi[i][j]);
}else {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("4");
polje.add(gumbi[i][j]);
}
}

if(gumbi[i][j].getText() == "3"){
a += 1;

}
if(i == 14 && j == 14){
gumbi[i][j].setText("" + a);
}
}
}


}
}

这就是我在 Action Listener 中的内容

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

import javax.swing.JButton;


public class Listener implements ActionListener {
JButton[][] gumbi;

public Listener(JButton[][] gumbi) {
this.gumbi = gumbi;

}

public void actionPerformed(ActionEvent e){

JButton gumb = (JButton) e.getSource();

if( gumb.getBackground() == Color.WHITE){
gumb.setBackground(Color.BLACK);
} else if (gumb.getBackground() == Color.BLACK){
gumb.setBackground(Color.WHITE);
}
}


}

感谢您的宝贵时间。

最佳答案

int a 定义为具有公共(public)访问权限的静态,并从主方法中删除它的定义,如下所示:

public class Start {
public static int a = 1;//static since you want to use in static method
public static void main(String[] args){

然后在监听器调用中,您可以使用 .variable ,如下所示:

int number = Start.a;

关于java - 如何从java中另一个类的主类访问int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27677141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com