簡體   English   中英

在JFrame構造函數之外添加JButton

[英]Adding JButtons Outside the JFrame Constructor

我正在上課的紙牌游戲,需要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);

肯定有可能:

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 (多次)-但這只是一個猜測而不知道它是什么。

需要考慮的幾點:

  • 僅應在事件調度線程(EDT)上更改Swing組件(JPanel,JButton等),在ActionListener中執行的代碼就是這種情況
  • 與布局相關的更改后,應調用validate方法對組件進行(重新)布局

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM