0

I am trying to make it so the methode makes a window with buttons and returns a Player corresponding to the pushed button but it always gets stuck on the wait without showing the buttons.

static Player proxy = new Player("Proxy");
private static Player pReturn = proxy;


public static Player playerSelection(ArrayList<Player> players, String title) {
    int playerNum = players.size();
    final Object o = new Object();
    JFrame frame = new JFrame(title);
    JPanel panel = new JPanel(new GridLayout(-1, 1, 5, 5));
    JButton[] btn = new JButton[playerNum];
    frame.add(panel);
    for (int i = 0;i < playerNum;i++) {
        btn[i] = new JButton(players.get(i).getName());
        panel.add(btn[i]);
        btn[i].addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                synchronized (o) {
                    for (int i = 0;i < playerNum;i++) {
                        if (e.getSource().equals(btn[i])) {
                            pReturn = players.get(i);
                        }
                    }
                    o.notify();
                    // also supposed to close the window
                }
            }
        });
    }
    frame.pack();
    frame.setVisible(true);
    synchronized (o) {
        while (pReturn.equals(proxy)) {
            try {
                o.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    return pReturn;
}

without the wait it just returns the proxy.

  • 1
    is the `wait` being executed on the Event Dispatch Thread (EDT)? – user85421 Jan 26 '18 at 14:08
  • yes that seems to be the case @Carlos Heuberger. and i just noticed that i know next to nothing about threads. – BurningToast Jan 26 '18 at 14:20
  • in short: "do not block the EDT" - Here some hopefully helpfull links: https://stackoverflow.com/q/7217013/85421 , https://stackoverflow.com/a/782309/85421 **and** [Swing's Threading Policy](https://docs.oracle.com/javase/9/docs/api/javax/swing/package-summary.html#threading) – user85421 Jan 26 '18 at 15:13
  • Yes after realizing what the problem was i got it to work by putting the entire methode in a different thread. thank you for the material – BurningToast Jan 26 '18 at 15:21

0 Answers0