我可以将回报绑定到条件吗?

时间:2018-03-26 15:24:20

标签: return delay imageicon

我有以下问题: 我的方法打开一个带有一堆按钮的JDialog(示例代码中只有一个)。我想单击一个按钮,从而为我的方法选择一个ImageIcon来返回。但是方法不等我点击按钮。它打开窗口,然后返回一个空的ImageIcon。

public class Kartenauswahl {

    ImageIcon bandit;

    public ImageIcon auswahlfenster() {

        int bwidth = new Integer(150);
        int bheight = new Integer(225);

        bandit = new ImageIcon("cover/Bandit.jpe");
        bandit.setImage(bandit.getImage().getScaledInstance(bwidth,bheight,Image.SCALE_DEFAULT));

        final JDialog kartenwahl = new JDialog();
        kartenwahl.setTitle("Kartenwahl");
        kartenwahl.setSize(1500,1000);
        kartenwahl.setVisible(true);
        kartenwahl.setLayout(new FlowLayout());

        ImageIcon returnicon= new ImageIcon();
        final JButton b1 = new JButton(); //just to get the Icon out of the void loop





        JButton B1 = new JButton(bandit); //this is going to be the button I want to click to choose the ImageIcon which is returned
        B1.setContentAreaFilled(false);
        B1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {

                b1.setIcon(bandit);
                kartenwahl.dispose();
            }

        });

        kartenwahl.add(B1);

        returnicon = (ImageIcon) b1.getIcon();

        return returnicon;

    }
}

问题:我可以将return语句绑定到某个条件吗?喜欢"只有在我点击按钮B1"?

后才返回

1 个答案:

答案 0 :(得分:1)

对不起漫长的等待感到抱歉。我写了一个适合你的自定义JDialog。

public class CustomDialog extends JDialog {
    JButton[] buttons;
    ImageIcon selectedImageIcon;

    public CustomDialog() {
        setSize(500, 500);
        setLayout(new GridLayout(4, 6));
        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selectedImageIcon = ((ImageIcon) ((JButton) e.getSource()).getIcon());
                dispose();
            }
        };
        buttons = new JButton[24];
        for(int i = 0; i < 24; i++) {
            buttons[i] = new JButton(new ImageIcon("path_to_your_image_file"));
            buttons[i].addActionListener(actionListener);
            add(buttons[i]);
        }
        setVisible(true);
    }

    public ImageIcon getSelectedImageIcon() {
        return selectedImageIcon;
    }
}

GridLayout的初始大小并不重要。你提到你需要24个按钮,所以我创建了一个包含4行和6列的网格。 然后我在循环中创建按钮并添加相同的Listener以使用按下按钮的图标设置选择图标。然后我处理触发windowClosed事件的屏幕。

你可以简单地从主类创建这个Dialog并等待响应:

public class main {
    public static void main(String[] args) {
        CustomDialog customDialog = new CustomDialog();
        customDialog.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                ImageIcon icon = customDialog.getSelectedImageIcon();
                //do something with your icon
            }
        });
    }
}

如果它解决了您的问题,请不要忘记将此答案标记为正确。 有一个好的!