【发布时间】:2015-06-16 19:03:14
【问题描述】:
感谢您查看我的问题。
我正在开发一个程序,该程序接受用户输入的高度和宽度,并根据从下拉菜单中选择的选项来计算矩形的面积或圆的周长。
到目前为止,我一切正常,但在 ActionEvents 方面遇到了问题。我需要指导的是如何根据从下拉菜单中选择的选项来更改计算公式。
我在设置 computebtn 以根据选择的公式计算面积或周长以及从 JTextFields 获取要在公式中使用的输入时也遇到了麻烦。如果我尝试使用 getText() 我会收到此错误:
error: incompatible types: string cannot be converted to int
TL;DR:需要帮助实现两个 ActionEvent。一种用于更改标签和公式,另一种用于处理computebtn 以获得答案。还需要帮助将用户输入到公式中。
我们将不胜感激。
到目前为止我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class areaOrCircumference extends JFrame implements ActionListener
{
int height;
int width;
int area;
int circumference;
JLabel label = new JLabel("");
JButton computebtn = new JButton("Compute");
JLabel widthlbl = new JLabel("Enter Width:");
JTextField widthfld = new JTextField(10);
JLabel heightlbl = new JLabel("Enter Height:");
JTextField heightfld = new JTextField(10);
JLabel outputlbl = new JLabel();
JPanel labelPanel = new JPanel();
JPanel inputPanel = new JPanel();
JPanel computePanel = new JPanel();
public areaOrCircumference()
{
setLayout(new BorderLayout());
add(labelPanel, BorderLayout.NORTH);
labelPanel.add(label);
add(inputPanel, BorderLayout.CENTER);
inputPanel.setLayout(new GridLayout(3,2));
inputPanel.add(widthlbl);
inputPanel.add(widthfld);
inputPanel.add(heightlbl);
inputPanel.add(heightfld);
inputPanel.add(outputlbl);
add(computePanel, BorderLayout.SOUTH);
computePanel.setLayout(new FlowLayout());
computePanel.add(computebtn);
computebtn.addActionListener(this);
}
public JMenuBar createMenuBar()
{
JMenuBar mnuBar = new JMenuBar();
setJMenuBar(mnuBar);
JMenu mnuType = new JMenu("Type", true);
mnuBar.add(mnuType);
JMenuItem mnuArea = new JMenuItem("Area");
mnuType.add(mnuArea);
mnuArea.setActionCommand("Area");
mnuArea.addActionListener(this);
JMenuItem mnuCirc = new JMenuItem("Circumference");
mnuType.add(mnuCirc);
mnuCirc.setActionCommand("Circumference");
mnuCirc.addActionListener(this);
return mnuBar;
}
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
if(arg == "Area")
{
label.setText("Area of a rectangle");
area = width*height;
}
if(arg =="Circumference")
{
label.setText("Circumference of a Circle");
circumference = 2*width + 2*height;
}
}
public static void main(String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
areaOrCircumference f = new areaOrCircumference();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(f.createMenuBar());
f.setTitle("Area/Circumference Calculator");
f.setBounds(300,300,475,400);
f.setVisible(true);
}
}
【问题讨论】:
-
这,
if(arg == "Area")让我担心。不要将字符串与==进行比较。使用equals(...) -
@HovercraftFullOfEels 这只是下拉菜单中的操作命令,用于确定已做出的选择
-
不管它是干什么用的——它是错误的,会导致程序逻辑无法正常运行。
-
请查看编辑以回答。如有任何问题,请询问。
-
@AndrewThompson 有一个下拉菜单“类型”有两个选项:“面积”或“周长”。用户首先选择这些选项之一,该选项将确定要使用输入的数字进行什么计算。一旦选择了计算类型并输入了数据,computebtn 就会计算用户输入的数据。我的问题是:我将公式放在哪里,以便公式与菜单中的选择相对应,以及如何让 computebtn 然后计算该公式并显示到我的 outputlbl?
标签: java swing awt actionevent