If the code is legible, what would it be, I would not say that it is so terrible.
An alternative is to call JButton in a class that has showDialog (which is allowed). The function can set the instance variable to be returned. But this seems less legible to me, so I would prefer your method.
If you are not creating a deeply hierarchical user interface structure, sometimes these little hacks are exactly what you need to do.
If you're interested, you can basically do the same thing with a private inner class:
private class DialogReturnValue { public int value; } private int showDialog() { final DialogReturnValue myValue = new DialogReturnValue(); JPanel panel = new JPanel(); final JDialog dialog = new JDialog(mainWindow, "Hit the button", true); dialog.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); JButton button = new JButton("Hit me!"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myValue.value = 42; dialog.setVisible(false); } }); panel.add(button); dialog.add(panel); dialog.pack(); dialog.setVisible(true); return myValue.value; }
And there is also an ActionListeners look (which may well be the "right").
source share