尝试使用JMenuBar和JMenu制作转换计算器,但是我似乎无法让动作侦听器工作,因为当用户从菜单中选择一个选项时,我的GUI不会执行任何操作。我感觉它与Object源或我的if语句有问题,但我真的不确定,因为这是我第一次使用JMenus。有人能告诉我我做错了什么吗?非常感谢!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import java.awt.event.*;
public class ConversionMenu extends JFrame implements ActionListener
{
Object[] choice;
double input;
double peso1, yen1, euro1;
String output;
JLabel num = new JLabel("How much would you like to convert: ");
JTextField n1 = new JTextField(10);
JLabel money = new JLabel();
JFrame frame = new JFrame();
JLabel result = new JLabel("");
JButton clear = new JButton("Clear");
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Convert");
JMenu peso = new JMenu("To Mexican Peso");
JMenu yen = new JMenu("To Japanese Yen");
JMenu euro = new JMenu("To European Euro");
JMenu close = new JMenu("Close");
public ConversionMenu()
{
FlowLayout flow = new FlowLayout();
JPanel pane = new JPanel();
pane.setLayout(flow);
pane.add(num);
pane.add(n1);
pane.add(clear);
pane.add(result);
frame.setJMenuBar(menubar);
menubar.add(menu);
menu.add(peso);
peso.addActionListener(this);
menu.add(yen);
yen.addActionListener(this);
menu.add(euro);
euro.addActionListener(this);
JMenu exit = new JMenu("Exit");
menubar.add(exit);
exit.add(close);
close.addActionListener(this);
setJMenuBar(menubar);
setContentPane(pane);
}
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
choice = menu.getSelectedObjects();
input = Double.parseDouble(n1.getText());
if(source == peso);
{
peso1 = input*19.08;
output = String.format("$" + n1 + "American dollars is
equal to " + peso1 + "Mexican pesos.");
result.setText(output);
}
if (source == yen)
{
yen1 = input*113.78;
output = String.format("$" + n1 + "American dollars is equal
to " + yen1 + "Japanese yen.");
result.setText(output);
}
else if (source == euro)
{
euro1 = input*0.86;
output = String.format("$" + n1 + "American dollars is
equal to " + euro1 + "European euro.");
result.setText(output);
}
else if (source == close)
{
System.exit(0);
}
if(source == clear)
{
n1.setText("");
result.setText("");
}
}
public static void main(String[] args)
{
ConversionMenu con = new ConversionMenu();
con.setTitle("Money Conversion Calculator");
con.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con.setSize(500, 500);
con.setVisible(true);
}
}