有多个 JButton

Having Multiple JButtons

抱歉这个简单的问题,但我对此很陌生,无法真正找到答案。我对如何添加两个(或更多)JButtons 感到困惑。我似乎无法让两者都显示,只有一个显示,即 "Division" 一个。 我最近的尝试如下。如何让两个按钮都显示在 window 的按钮上?

public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JPanel xpanel;

public Calculator() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    xpanel = new JPanel();
    xpanel.setLayout(new GridLayout(3,2));

    xpanel.add(new JLabel("x:"));
    xfield = new JTextField("0", 5);
    xpanel.add(xfield);

    xpanel.add(new JLabel("y:"));
    yfield = new JTextField("0", 5);
    xpanel.add(yfield);

    xpanel.add(new JLabel("x*y="));
    result = new JLabel("0");
    xpanel.add(result);
    frame.add(xpanel, BorderLayout.NORTH);

    subtractButton = new JButton("Subtract");
    frame.add(subtractButton, BorderLayout.SOUTH);
    subtractButton.addActionListener(this);

    divideButton = new JButton("Division");
    frame.add(divideButton, BorderLayout.SOUTH);
    divideButton.addActionListener(this);

    frame.pack();
    frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent event) {
    int x = 0;
    int y = 0;

    String xText = xfield.getText();
    String yText = yfield.getText();

    try {
        x = Integer.parseInt(xText);
      }
    catch (NumberFormatException e) {
        x = 0;
      }

    try {
        y = Integer.parseInt(yText);
      }
    catch (NumberFormatException e) {
        y = 0;
      }

    result.setText(Integer.toString(x-y));
  }
}

您需要先在 JPanel 中添加这两个按钮,然后再将 JPanel 添加到框架的 SOUTH。

所以

subtractButton = new JButton("Subtract");
frame.add(subtractButton, BorderLayout.SOUTH);
subtractButton.addActionListener(this);

divideButton = new JButton("Division");
frame.add(divideButton, BorderLayout.SOUTH);
divideButton.addActionListener(this);

你可以做到

JPanel southPanel = new JPanel();

subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);

divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);

frame.add(southPanel , BorderLayout.SOUTH);

将 Eclipse 和 WindowBuilder 用于您的 Swing 界面,并根据需要添加任意数量的按钮或使用鼠标移动它们。它更容易,特别是如果你是新手,你会从生成的代码中学到很多东西。