[英]Passing data from GUI to another class in Java
我正在做一个创建战舰游戏的项目。 我有以下课程:
Battleship
(主舱) Player
Game
Board
Visualisation
(GUI类在那里我有一个gridLayout
的JButtons
在用户按下) JButton
地方要插入的船。 首先,创建一个带有一些参数(例如棋盘尺寸)的新Game
。 然后在类Game
,进行新的Visualisation
。 在此类中,我完成了actionListener
和actionPerformed
。
我的问题是我如何将信息(例如,我按下的JButton
(将飞船插入到gridLayout
该单元格中))传递给Game
类? 这就是我所拥有的:
Class Game
private Player _user;
private Player _computer;
然后,我想检查_user
是否可以插入船。 _user.MethodOfClassPlayer();
Class Player
private int id;
private String name;
private Board _boardPlayer
Class Board
private int size;
private int[][] _board = null ;
执行的功能
public void actionPerformed(ActionEvent e) {
for ( int i = 0; i < tUsuariCPU.length; i++ ){
for ( int j = 0; j < tUsuariCPU[i].length; j++ ){
if ( e.getSource() == tUsuariCPU[i][j] ){
buttonPressedUser(i,j);
JButton temp = (JButton) e.getSource() ;
temp.setBackground(java.awt.Color.ORANGE);
}
我想将按JButton的信息传递给Game类,以了解该玩家是否可以使用该位置放置飞船。 如果可用,那么我将绘制JButton,希望您理解我。
考虑到其他答案,您可能需要使用Observers
和Observable
。 一个Observable是可以由一个或几个Observer观察到的类。 观察者可以观察几个观察对象。
例:
public class Visualisation extends JFrame {
private Integer num;
private A myInnerClass;
public Visualisation(Observer o) {
num = 8;
myInnerClass = new A();
myInnerClass.setObserver(o);
}
public onButtonPressed(Event e) {
myInnerClass.notifyMyObservers();
}
public class A extends Observable {
public A() {
}
public void notifyMyObservers() {
this.setChanged();
this.notifyObservers(num); // the parameter can be any object
}
}
}
public class B implements Observer {
public B() {
}
public void update(Observable observed, Object arg) {
if (observed instance of A) {
if (arg instance of Integer) {
// ...
}
}
}
}
这是您如何将它们连接到示例主函数中的方法
public static main(String[] args) {
B observer = new B();
Visualisation v = new Visualisation(observer);
}
您可以使用如下对话框类:
public class Visualisation extends JDialog {
private Board board;
public Game(Frame owner, boolean modal) {
super(owner, modal);
// add a Listener to your button to dispose the dialog after you save your data in board
JButton yourButton = new JButton();
yourButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
board = ....;
dispose();
}
});
}
public Board show(){
setVisible(true);
return Board ;
}
}
并在游戏类中调用它,请使用:
Visualisation visualisationDialog = new Visualisation(null, true);
Board board = visualisationDialog .show();
//do whatever you want with the board from here now
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.