gpt4 book ai didi

java - 如何从另一个类获取有条件分配的值

转载 作者:行者123 更新时间:2023-12-01 09:27:27 27 4
gpt4 key购买 nike

我在多个类中使用条件分配值时遇到一些问题。我想当且仅当满足条件时才在一个类中应用某个值,然后在其他类中使用它来累加总分。这是我的代码!

@SuppressWarnings("serial")
public class Beginner extends JPanel {

static JButton quest;
Random rand = new Random();

int n = 10;

static List <Point> points = new ArrayList<Point> ();

int scores;
int fails;

public Beginner() {

int radius = 200;
Point center = new Point (250, 250);

double angle = Math.toRadians(360 / n);

points.add(center);

for (int i = 0; i < n; i++) {
double theta = i * angle;

int dx = (int) (radius * Math.sin(theta));

int dy = (int) (radius * Math.cos(theta));

Point p = new Point (center.x + dx , center.y + dy);

points.add(p);

}

draw (points);
}

public void draw (List<Point> points) {

JPanel panels = new JPanel();

SpringLayout spring = new SpringLayout();

int count = 1;
for (Point point: points) {

quest = new JButton("Question " + count);
quest.setForeground(Color.BLACK);
Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
quest.setFont(fonte);

add (quest);
count++;

spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels );

spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels );

setLayout(spring);

panels.setOpaque(false);
panels.setVisible(true);
panels.setLocation(5,5);

add(panels);

quest.addActionListener(new java.awt.event.ActionListener(){
@Override
public void actionPerformed (ActionEvent p) {

if (point.equals(points.get(0))) {

new Quest1();

JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);

}
else if (point.equals(points.get(1))) {

new Quest2();

JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}
else if (point.equals(points.get(2))) {

new Quest3();

JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);

}
else if (point.equals(points.get(3))) {

new Quest4();

JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}

else if (point.equals(points.get(4))) {

new Quest5();

JButton source = (JButton) p.getSource();
source.setEnabled(false);
source.setBackground(Color.GREEN);
}

现在,这就是我的第一个调用的类(名为 Quest1)的样子

    public class Quest1 {
//sound files to be shuffled and played!
String [] word = { "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/audio.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/bomb.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/baby.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/gym.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/hearing.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/goal.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/manifest.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/mountain.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/market.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/debate.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/election.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/number.wav",
};
//matching strings for each file
String [] words = { "Audio", "Bomb", "Baby", "Gym", "Hearing", "Goal", "Manifest","Mountain", "Market", "Debate", "Election", "Number" };

Random rand = new Random();
int random = rand.nextInt(word.length);
String temp = word[random];

int scores;
int fails;


public Quest1 () {

//announcing the JComponents to be used
JFrame frame = new JFrame ();
JButton click = new JButton("Play");
JTextField type = new JTextField(15);
JLabel pic = new JLabel(new ImageIcon("C:\\Users\\HP\\Desktop\\Sample pics\\1.png"));
JButton score = new JButton ("Check My Answer");
JPanel cont = new JPanel ();

//set up frame properties
frame.getContentPane().setBackground(Color.WHITE);
frame.setLayout(new FlowLayout());
frame.setUndecorated(true);
frame.setResizable(false);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.add(cont, BorderLayout.CENTER);
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
frame.setVisible(true);

//setting layout of JPanel
cont.setLayout(new GridBagLayout());
cont.setOpaque(false);
cont.setPreferredSize(new Dimension(500,500));
cont.setLocation(100, 50);
GridBagConstraints g = new GridBagConstraints();
g.anchor = GridBagConstraints.WEST;
g.gridx = 4;
g.gridy = 2;
g.gridwidth = 2;
g.insets = new Insets (70, 2, 2, 2);
cont.add(pic , g);


g.anchor = GridBagConstraints.WEST;
g.gridx = 4;
g.gridy = 5;
g.gridwidth = 2;
g.insets = new Insets (50, 2, 2, 2);
cont.add(click, g);


click.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {
//sound file shuffled and played
}
});
g.anchor = GridBagConstraints.EAST;
g.gridx = 10;
g.gridy = 4;
g.gridwidth = 5;
g.insets = new Insets(30, 2, 2, 10);
Font fonty = new Font("Lucida", Font.PLAIN, 15);
type.setFont(fonty);
cont.add(type, g);

g.anchor = GridBagConstraints.SOUTH;
g.gridx = 9;
g.gridy = 8;
g.gridwidth = 2;
g.insets = new Insets(2, 2, 2, 50);
cont.add(score, g);

score.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent tx) {

if (type.getText().equals(words[random])) {

//sound file played
scores+= 3;
String a = "Correct!..... The answer is " + words[random];
JOptionPane.showMessageDialog(null, a);

frame.dispose();
return;
}

else {
//sound file played again
fails+=0;
// This is where my problem is: The other 10 classes are like
//this, I want to get this value and that of scores (depending on the
//condition that is met), and add them up in the class beginner! )
String a = "Sorry, The Answer is " + words[random];
JOptionPane.showMessageDialog(null, a);

frame.dispose();
}
}
});
//sound file played
}

}

最佳答案

您的分数和失败是监听器事件中的局部变量。如果您在帮助类中创建实例变量,您可以在监听器中更新它们,但只要您的程序正在运行,它们就会持续存在,然后可以作为构造函数参数传递到更多类中,以达到您可能需要的任何目的。

public class help extends JFrame {
JPanel hold = new JPanel ();
JTextField enter = new JTextField(10);
JButton check = new JButton ("Check answer");
JButton quest = new JButton ("See question");
JLabel lunch = new JLabel ("Who is the current President of the United States?");

//Add fields you want to track here
int scores;
int fails;

public help () {

然后在你的听众内部

     scores += 3; //track them anyway you want

更新:

所以看起来您想将 Quest 类(class)的分数/失败传递回原来的类(class)。您可以通过向 Quest 类添加一些分数和失败的访问器方法来实现此目的。

public int getScores(){ 
return scores;
}

public int getFails(){
return fails;
}

这将允许您在需要时检索值。您只需在您创建的 Quest 对象上调用它们即可。但是还有另一个问题...

new Quest1(); 

任务需要存储在像分数和失败这样的变量中,否则它将被垃圾收集器丢弃。添加一个变量,将当前任务保持在顶部,然后在切换任务时交换它们。

Quest1 q1;
...
...
q1 = new Quest1();
...
...
scores = q1.getScores();
fails = q1.getFails();

更新:按钮标志

您可以通过添加 boolean 变量来添加标志来检查事情是否发生。在这种情况下,您的初级类(class)中可以有 Quest1-5 标志。当用户单击该类时,您可以将其更改为 true,然后检查是否所有操作都已完成。

boolean Q1 = false;
boolean Q2 = false;
...

if (point.equals(points.get(0))) { // User clicks quest 1
Q1 = true;
...

...
if (checkQuests()){
//do stuff if all buttons are clicked
}

...

public boolean checkQuests(){ //cleaner if you use arrays
if(Q1 == false || Q2 == false || ... Q5== false){
return false;
}
else{
return true;
}
}

更新:回调函数

当 GUI 和监听器工作时,并非所有操作都按照您希望的顺序发生。 GUI 和事件发生在它们自己的线程上,通常您希望在另一个事件结束时触发一个事件。您可以通过使用回调函数来做到这一点。

What is a callback function?

以下是您在程序中实现这一功能的方法。

您的任务内部包含一个接口(interface)和接口(interface)变量:

public class Quest{

CallBack cb;

interface CallBack{
public void callBack();
}

//add some way to set the call back, such as setter (or use constructor)
public void setCB(CallBack cb){ this.cb = cb;}

//Inside the action listener of your quest doing something
...
cb.callBack(); //call the callback method when you are done and want to do your check (it calls the beginner class back)

在您的初级类(class)中:

//When creating a quest 
Q1 = new Quest1();
Q1.setCB(new CallBack{
public void callBack(){
CheckQuests(); //this tells the program what to do when it hears back from Q1
}
}

最终发生的情况是,当 Q1 的代码完成时,它会调用 callBack() 方法(可以是任何时间,但在您的情况下,当您完成逻辑时调用它)。

初学者类传入的代码告诉 Q1 在调用该方法时应该做什么。

关于java - 如何从另一个类获取有条件分配的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39730334/

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