簡體   English   中英

如何更改動態生成的 JButton 的圖標

[英]How to change the icon of a dynamically generated JButton

在此處輸入圖像描述

我有這個 java swing 程序,我試圖弄清楚如何創建一個按鈕,單擊它會清除文本區域並更改人的圖標以放下手。

按鈕是使用 for 循環動態生成的 而這個

       // To create buttons
       for(int i=0 ; i < list.length; i++){
            Participant pa = list[i];
            JButton b = new JButton(pa.getNameButton(),participant);

            b.addActionListener(e ->
            {
                String s = pa.toString() + questionPane.getText();
                final ImageIcon raise = resizeIcon(new ImageIcon("src/raise.png"),30,30);
                b.setIcon(raise);
                JOptionPane.showMessageDialog(null,s,"Welcome to Chat Room",JOptionPane.INFORMATION_MESSAGE,pa.getImage());
            });
            p.add(b);
           }


        // Clear button logic
        clearButton.addActionListener(e ->{
            questionPane.setText("");
            hostPane.setText("");
        });

好吧,這會有點有趣。

以下示例將大部分概念解耦,並使用基本的“觀察者模式”來通知感興趣的各方 state 已更改(即,聊天已被清除)。

這是一個基本概念,您可以將“什么”與“如何”分離,即您想要完成的“什么”(更新模型)與“如何”完成(即按鈕按下)。 這使得更容易適應更復雜的系統。

該示例包含一個ChatService ,它有一個偵聽器,在此示例中,它簡單地告訴感興趣的各方聊天已被清除。

更復雜的解決方案可能是讓ChatService在用戶“舉手”時生成事件,這允許相關方以與他們相關的任何方式處理它。

該示例使用Action API 將每個操作執行的工作與 UI 本身分離。 這有助於創建單個工作單元,當您擁有動態數據集時更容易處理。

點擊巨星

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            ChatService chatService = new ChatService();

            JPanel panel = new JPanel();
            String[] names = new String[] {"Bryan", "Alan", "George", "Henry"};
            List<PeopleAction> actions = new ArrayList<>(names.length);
            for (String name : names) {
                PeopleAction action = new PeopleAction(chatService, name, false);
                actions.add(action);
            }

            Random rnd = new Random();
            actions.get(rnd.nextInt(names.length)).setRaised(true);

            for (Action action : actions) {
                JButton btn = new JButton(action);
                panel.add(btn);
            }

            setLayout(new GridLayout(2, 1));
            add(panel);

            JPanel hostPane = new JPanel();
            JButton clearButton = new JButton(new ClearAction(chatService));
            hostPane.add(clearButton);
            add(hostPane);
        }

    }

    public class ChatService {
        private List<ChatListener> listeners = new ArrayList<>(25);

        public void addChatListeners(ChatListener listener) {
            listeners.add(listener);
        }

        public void removeChatListener(ChatListener listener) {
            listeners.remove(listener);
        }

        protected void fireChatCleared() {
            if (listeners.isEmpty()) {
                return;
            }

            for (ChatListener listener : listeners) {
                listener.chatCleared();
            }
        }

        public void clear() {
            // Do what's required
            fireChatCleared();
        }
    }

    public interface ChatListener {
        public void chatCleared();
    }

    public class PeopleAction extends AbstractAction implements ChatListener {

        private String name;
        private boolean raised;

        public PeopleAction(ChatService chatService, String name, boolean raised) {
            // You can use either LARGE_ICON_KEY or SMALL_ICON to set the icon
            this.name = name;
            if (raised) {
                putValue(NAME, "* " + name);
            } else {
                putValue(NAME, name);
            }

            chatService.addChatListeners(this);
        }

        public void setRaised(boolean raised) {
            if (raised) {
                putValue(NAME, "* " + name);
            } else {
                putValue(NAME, name);
            }
        }

        public boolean isRaised() {
            return raised;
        }

        @Override
        public void actionPerformed(ActionEvent evt) {
            // Do what ever needs to be done
            setRaised(!isRaised());
        }

        @Override
        public void chatCleared() {
            setRaised(false);
        }

    }

    public class ClearAction extends AbstractAction {

        private ChatService chatService;

        public ClearAction(ChatService chatService) {
            this.chatService = chatService;
            putValue(NAME, "Clear");
        }

        @Override
        public void actionPerformed(ActionEvent evt) {
            chatService.clear();
        }

    }
}

暫無
暫無

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

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