繁体   English   中英

具有多个JButton

[英]Having Multiple JButtons

对于这个简单的问题,很抱歉,但是我对此很陌生,无法真正找到答案。 我对如何添加两个(或更多)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));
  }
}

您需要先在JPanel中添加两个按钮,然后再在框架的SOUTH中添加该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);

将Eclipse和WindowBuilder用于您的Swing界面,并根据需要添加任意数量的按钮,或使用鼠标来移动它们。 这要容易得多,尤其是如果您不熟悉它,并且将从生成的代码中学到很多东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM