【发布时间】:2020-04-12 09:56:10
【问题描述】:
我正在制作一个棋盘游戏,8X8 矩阵,在一个框架中有 64 个JButtons。
到目前为止,我的代码是这样的:
public class Main {
static JFrame f = new JFrame();;
static JButton btn;
static JButton btnTemp;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout((new GridLayout(8,8)));//size of the board
f.setTitle("ex");
f.setSize(800,800);
for (int i=0;i<=7;i++)
{
for (int j = 0; j<=7;j++)
{
btn=new JButton();
btn = new JButton(new SoliderW());
btn.setName("btn"+i+""+j);
btn.setBackground(Color.BLACK);
btn.addActionListener(actionListener); // make a listener to the button
f.add(btn);
}
}
f.setVisible(true);
我正在尝试使用此代码判断点击了哪个 JButoon:
Component[] components = f.getContentPane().getComponents();
ActionListener actionListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Hello");
}
};
for (Component component : components)
{
if (component instanceof JButton)
{
((JButton) component).addActionListener(actionListener);
}
}
但是,我不明白如何判断点击了哪个 Jbutton。
【问题讨论】:
-
这能回答你的问题吗? How can I find out which button was clicked?
-
不是,我已经试过了
-
@Or.muha,“不是真的”是什么意思。您尝试了什么,遇到了什么问题?该链接向您展示了如何做您想做的事。如果不是,那么您需要澄清您的问题。
标签: java swing user-interface jframe jbutton