![](/img/trans.png)
[英]How to call second class method from one class and print output of method inside second class in java
[英]Java method call from inside class different output than outside class
我正在制作井字游戲計算機,我需要知道當前字母是O
以便計算機移動。 但是,從main方法來看,當前字母始終看起來像O
,但是在GUI類內部,當前字母會按需更改。
這是GUI類:我嘗試僅包括相關方法。
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class TicGUI extends JPanel {
private JButton btns[] = new JButton[9];
private String xnos[] = new String[9];
private String currentLetter = "X";
public TicGUI() {
initBtns();
initBoard();
}
public String getCurrentLetter() {
return currentLetter;
}
public void initBtns() {
for(int i = 0; i < 9; i++) {
btns[i] = new JButton();
btns[i].addActionListener(new TicListener());
}
}
public void initBoard() {
this.setLayout(new GridLayout(3, 3));
for(int i = 0; i < btns.length; i++) {
this.add(btns[i]);
}
}
private class TicListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if(btn.getText().equals("") && btn.isEnabled()){
btn.setText(currentLetter);
btn.setEnabled(false);
if(currentLetter.equals("X"))
currentLetter = "O";
else
currentLetter = "X";
System.out.println("In class:" + getCurrentLetter());
}
}
}
}
這是帶有main方法的類:
import java.util.Scanner;
import javax.swing.JFrame;
public class TICTICTIC {
public static void main(String[] args) {
TicGUI tic = new TicGUI();
JFrame frame = new JFrame("t");
frame.add(new TicGUI());
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Scanner scan = new Scanner(System.in);
while(true) {
String ans = scan.nextLine();
System.out.println(tic.getCurrentLetter());
}
}
}
我的預期輸出將是:
In main: X // <- pressed enter
In GUI class: O // <- clicked a button, made currentLetter change
In main: O // <- pressed enter
In GUI class: X // <- clicked a button, made currentLetter change
In main: X // <- you get the idea
In GUI class: O
In main: O
“ In main”字母與GUI類輸出交替顯示。
相反,我得到:
In main: X
In GUI class: O
In main: X
In GUI class: X
In main: X
In GUI class: O
In main: X
“ In main”輸出始終保持不變。 為什么?
您正在創建兩個TicGUI
實例...
TicGUI tic = new TicGUI();
JFrame frame = new JFrame("t");
frame.add(new TicGUI());
一個正在添加到GUI中,另一個正在嘗試從中提取值,每個都有其自己的currentLetter
值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.