我正在上课的纸牌游戏需要一个DealButton来处理一手牌并在框架中显示它们。我有一个循环遍历给定的手并正确创建和显示卡片,但是当该代码从构造函数移动到dealButton的ActionListener时,没有任何内容显示。
有没有办法将JButtons添加到构造函数外的框架?
以下是应该展示指针的代码:
deck.shuffle();
Hand hands[] = deck.deal(4, 13);
GridBagConstraints handCon1 = new GridBagConstraints();
handCon1.insets = new Insets(0, 0, 0, 0);
handCon1.gridy = 10;
int handSize = hands[0].getCards().length;
Card cards[] = hands[0].getCards();
for(int i = 0 ; i < handSize ; i++){
JButton card = new JButton();
PlayCardListener playCard = new PlayCardListener(deck, cards[i], card);
card.addActionListener(playCard);
card.setIcon(new ImageIcon(cards[i].getImg()));
card.setBorder(null);
handCon1.gridx = i;
add(hand1);
hand1.add(card, handCon1);
答案 0 :(得分:0)
肯定有可能:
public class Deal {
public static void main(String[] args) {
new Deal();
}
private JFrame frame;
private JTextField statusField;
private JButton dealButton;
private JPanel buttonsPanel;
private Deal() {
statusField = new JTextField("starting - press DEAL");
statusField.setEditable(false);
dealButton = new JButton("DEAL");
dealButton.addActionListener(this::doDeal);
buttonsPanel = new JPanel();
frame = new JFrame();
frame.add(dealButton, BorderLayout.PAGE_START);
frame.add(buttonsPanel, BorderLayout.CENTER);
frame.add(statusField, BorderLayout.PAGE_END);
frame.setSize(600, 200);
frame.validate();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void doDeal(ActionEvent ev) {
buttonsPanel.removeAll();
List<String> cards = Arrays.asList("A", "2", "3", "4", "5");
Collections.shuffle(cards);
for (String text : cards) {
JButton button = new JButton(text);
button.addActionListener(this::doCard);
button.setActionCommand(text);
buttonsPanel.add(button);
}
statusField.setText("new buttons");
frame.validate();
}
private void doCard(ActionEvent ev) {
String text = ev.getActionCommand();
statusField.setText(text); // just demo
}
}
我怀疑代码的以下部分:
for (...) {
...
add(hand1);
hand1.add(card, handCon1);
检查是否真的需要在循环中添加hand1
(多次) - 但只是猜测而不知道它是什么。
需要考虑的一些要点:
validate
方法(重新)布局组件