我想通过Swing创建一个简单的桌上游戏。我有一个JFrame和一个JPanel变量。
我想将JButton添加到此JPanel中,但是我想创建一个自己的类。
我做了一个扩展JButton(继承)的类:
public class GameField extends JButton {...}
因此,我可以将GameFields添加到JPanel。
但是我想按组成创建GameFields:
public class GameField{
private JButton button;
}
但是在这种情况下,如何将GameField添加到JPanel?
我可以通过解决办法解决这个问题吗?
最佳答案
但是在这种情况下,如何将GameField添加到JPanel?我能解决这个问题吗
问题是由竞争引起的吗?
您可以通过添加一个简单的getter来做到这一点,例如:
public class GameField{
private JButton button;
public GameField(String text) {
button = new JButton(text);
// do your stuff here
}
public JButton getButton() {
return button;
}
}
然后在您的GUI中:
public void createAndShowGUI() {
JPanel panel = new JPanel(new GridLayout(5,5));
panel.add(new GameField("Button # 1").getButton());
panel.add(new GameField("Button # 2").getButton());
...
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
编辑
您在评论中表示:
谢谢,但是在这种情况下,如果我想访问此字段(即
panel.getComponent(i)),我只能得到一个JButton,而不能得到GameField。
您可以保留包含
GameField
对象的列表,也可以使用putClientProperty()方法保留对GameField
对象的引用,如下例所示:import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Demo {
private void createAndShowGUI() {
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
GameField gameField = (GameField)button.getClientProperty("GameField");
if(gameField != null) {
System.out.println(gameField.getText());
}
}
};
GameField gameField1 = new GameField("Button # 1");
gameField1.getButton().addActionListener(actionListener);
GameField gameField2 = new GameField("Button # 2");
gameField2.getButton().addActionListener(actionListener);
JPanel content = new JPanel(new GridLayout());
content.add(gameField1.getButton());
content.add(gameField2.getButton());
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class GameField {
private String text;
private JButton button;
public GameField(String text) {
this.text = text;
button = new JButton(text);
button.putClientProperty("GameField", GameField.this);
}
public JButton getButton() {
return button;
}
public String getText() {
return text;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Demo().createAndShowGUI();
}
});
}
}