我在Java中有这个功能:
public int[] getProperties() {
properties = new JFrame();
properties.setSize(400, 200);
properties.setVisible(true);
properties.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
propertiesPanel = new JPanel();
propertiesPanel.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 10, 5);
properties.add(propertiesPanel);
heightText = new JLabel("Height (squares)");
constraints.gridx = 0;
constraints.gridy = 0;
propertiesPanel.add(heightText, constraints);
heightField = new JTextField(5);
heightField.setText(Integer.toString(board.getHeight()));
constraints.gridx = 1;
constraints.gridy = 0;
propertiesPanel.add(heightField, constraints);
widthText = new JLabel("Width (squares)");
constraints.gridx = 0;
constraints.gridy = 1;
propertiesPanel.add(widthText, constraints);
widthField = new JTextField(5);
widthField.setText(Integer.toString(board.getWidth()));
constraints.gridx = 1;
constraints.gridy = 1;
propertiesPanel.add(widthField, constraints);
multText = new JLabel("Pixels per Square");
constraints.gridx = 0;
constraints.gridy = 2;
propertiesPanel.add(multText, constraints);
multField = new JTextField(5);
multField.setText(Integer.toString(board.getMultiplier()));
constraints.gridx = 1;
constraints.gridy = 2;
propertiesPanel.add(multField, constraints);
confirm = new JButton("Ok");
constraints.gridx = 1;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
propertiesPanel.add(confirm, constraints);
final int[] dimensions = new int[3];
confirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dimensions[0] = Integer.parseInt(heightField.getText());
dimensions[1] = Integer.parseInt(widthField.getText());
dimensions[2] = Integer.parseInt(multField.getText());
properties.dispose();
}
});
return dimensions;
}
(JFrame
, JPanel
, JLabel
s 和JTextField
s 都在其他地方定义)。但是,该函数总是返回一个像这样的数组:{0, 0, 0}
因为confirm
从不立即按下。dimensions
那么,只有在confirm
按下后我才能返回?