java鸡兔同笼制作UI界面代码
时间: 2023-10-03 14:07:02 浏览: 91
以下是一个简单的 Java 程序,用于模拟鸡兔同笼问题并在 UI 界面中显示结果:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChickenRabbitUI extends JFrame implements ActionListener {
private JTextField txtHead, txtFoot;
private JLabel lblResult;
public ChickenRabbitUI() {
setTitle("鸡兔同笼");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pnlInput = new JPanel(new GridLayout(2, 2));
pnlInput.add(new JLabel("头数:"));
txtHead = new JTextField();
pnlInput.add(txtHead);
pnlInput.add(new JLabel("脚数:"));
txtFoot = new JTextField();
pnlInput.add(txtFoot);
JButton btnCalc = new JButton("计算");
btnCalc.addActionListener(this);
lblResult = new JLabel();
JPanel pnlMain = new JPanel(new BorderLayout());
pnlMain.add(pnlInput, BorderLayout.CENTER);
pnlMain.add(btnCalc, BorderLayout.EAST);
pnlMain.add(lblResult, BorderLayout.SOUTH);
setContentPane(pnlMain);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int heads = Integer.parseInt(txtHead.getText());
int feet = Integer.parseInt(txtFoot.getText());
int rabbits = (feet - 2 * heads) / 2;
int chickens = heads - rabbits;
if (rabbits < 0 || chickens < 0 || (feet - rabbits * 4 - chickens * 2) != 0) {
lblResult.setText("无解");
} else {
lblResult.setText("鸡:" + chickens + "只,兔:" + rabbits + "只");
}
}
public static void main(String[] args) {
new ChickenRabbitUI();
}
}
```
这个程序创建了一个简单的 UI 界面,用于输入鸡和兔的头数和脚数,并在计算按钮被点击时计算鸡和兔的数量,并在界面中显示结果。
阅读全文