简体   繁体   中英

How to change the icon of a dynamically generated JButton

在此处输入图像描述

I have this java swing program, and im trying to figure out how can i create a button that upon clicking it will clear the text areas & change the icon of the person to put their hand down.

The buttons are dynamically generated using a for loop And this

       // 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("");
        });

Okay, this is going to be a bit of fun.

The following example decouples much of the concept and makes use of a basic "observer pattern" to notify interested parties that the state has changed (ie, the chat's been cleared).

This is a basic concept where by you decouple the "what" from the "how", ie, "what" it is you want done (update the model) from the "how" it gets done (ie, button push). This makes it easier to adapt to more complex systems.

The example contains a ChatService , which has a single listener, which, for this example, simple tells interested parties that the chat has been cleared.

A more complex solution might have the ChatService generating events for when a user "raises" their hand, which allows the interested parties to deal with it in what ever way is relevant to them.

The example makes use of the Action API to decouple the work performed by each action from the UI itself. This helps create a single unit of work which is easier to deal with when you have a dynamic data set.

点击巨星

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();
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM