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));
}
}
答案 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界面并添加任意数量的按钮或用鼠标移动它们。它更容易,尤其是如果您是新手,并且您将从生成的代码中学到很多东西。