有多个JButton

时间:2017-12-01 21:53:23

标签: java jbutton

抱歉这个简单的问题,但我真的很陌生,无法找到答案。我对如何添加两个(或更多)JButton感到困惑。我似乎无法同时展示,只有一个展示,这是“分部”之一。 我最近的尝试如下。如何让两个按钮显示在窗口按钮上?

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));
  }
}

2 个答案:

答案 0 :(得分:0)

在将JPanel添加到帧的南方之前,您需要在JPanel中添加两个按钮。

所以而不是

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);

答案 1 :(得分:0)

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