当我为我的 s 数组设置 X 和 Y 值时JButton
,我得到的只是乘以 93 的正确值。我可以通过将该值除以 93 来解决问题,但我宁愿首先找出错误的位置。
我在代码中有两个类,一个用于实际程序,一个用于按钮对象以及坐标。
这是代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
import java.io.*;
public class ConnectFour implements ActionListener
{
JFrame frame = new JFrame();
Button [][] buttons = new Button[6][7];
public ConnectFour()
{
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(6,7));
frame.setLocationRelativeTo(null);
frame.setTitle("Connect Four");
for(int filler = 0; filler <= 5; filler++)
{
for(int filler2 = 0; filler2 <= 6; filler2++)
{
buttons[filler][filler2] = new Button();
buttons[filler][filler2].setX(filler2);
buttons[filler][filler2].setY(filler);
//System.out.println(buttons[filler][filler2].getX());
//System.out.print(buttons[filler][filler2].getY());
frame.add(buttons[filler][filler2].button);
buttons[filler][filler2].button.addActionListener(this);
}
}
frame.setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
JButton pressedButton = (JButton)a.getSource();
System.out.print(pressedButton.getY() / 93);
System.out.print(pressedButton.getX() / 93);
}
public static void main(String args[])
{
ConnectFour gameplay = new ConnectFour();
}
}
这是Button
课程:
import javax.swing.JButton;
public class Button
{
JButton button;
private int x = 0;
private int y = 0;
public Button()
{
button = new JButton();
}
public int getX() {return x;}
public int getY() {return y;}
public void setX(int xIndex)
{
x = xIndex;
}
public void setY(int yIndex)
{
y = yIndex;
}
}