我正在努力提高自己的 java 编程水平。
我想要做的是,我有一个菜单和子菜单,例如我点击文件菜单,然后选择转换器(子菜单),我希望它为我的转换器程序打开新窗口。
这是我的转换器窗口
public class Converter extends JFrame {
private static final long serialVersionUID = 1L;
private MoneyDetails convertMe = new MoneyDetails();
private JLabel tlLabel = new JLabel(" Amount of TL");
private JLabel dollarsLabel = new JLabel("Amount of Dollars");
private JTextField tlField = new JTextField("0.0");
private JTextField dollarsField = new JTextField("0.0");
private JButton tlButton = new JButton("Convert to $");
private JButton dollarsButton = new JButton("<<< Convert to TL");
private JButton setRates = new JButton("Set Rates");
public Converter() {
JPanel dataPanel = new JPanel(new GridLayout(2, 2, 12, 6));
dataPanel.add(tlLabel);
dataPanel.add(dollarsLabel);
dataPanel.add(tlField);
dataPanel.add(dollarsField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(tlButton);
buttonPanel.add(dollarsButton);
Container container = getContentPane();
container.add(dataPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.SOUTH);
tlButton.addActionListener(new TLConverter());
dollarsButton.addActionListener(new DollarsConverter());
buttonPanel.add(setRates);
}
private class TLConverter implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String input = tlField.getText();
double tl = Double.parseDouble(input);
convertMe.setTL(tl);
double dollars = convertMe.getDollars();
dollarsField.setText(String.format("%.2f", dollars));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Please enter the amount that will be converted.");
}
}
}
private class DollarsConverter implements ActionListener {
public void actionPerformed(ActionEvent e) {
String input = dollarsField.getText();
double dollars = Double.parseDouble(input);
convertMe.setDollars(dollars);
double tl = convertMe.getTL();
tlField.setText(String.format("%.2f", tl));
}
}
public static void main(String[] args) {
Converter theGUI = new Converter();
theGUI.setTitle("TL to $ or $ to TL Converter");
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theGUI.pack();
theGUI.setVisible(true);
}
}
这是我的转换器类中的菜单
private JMenuBar menuBar = new JMenuBar(); // Window menu bar
public Converter(String title) {
setTitle(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setJMenuBar(menuBar); // Add the menu bar to the window
JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
JMenuItem subTest = new JMenuItem("Test");
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element menu
fileMenu.add(subTest);
}
public static void main(String [] args)
{
Converter window = new Converter("Para Dönüstürücü");
window.setBounds(30, 30, 300, 300);
window.setVisible(true);
Converter theGUI = new Converter();
}
当我点击我的子菜单时,我希望它打开我的转换窗口。我怎么能做到?