该程序应该转换用户输入的里程并使用GUI界面转换为公里。程序目前无法编译。
aaaaa.java:10:错误:方法声明无效;需要返回类型 public CalcPanel(){ ^ 1错误
无论我在哪里查找此类程序的示例,我都看不到使用该方法的返回类型。有任何想法吗?感谢
以下是该计划:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class aaaaa extends JFrame {
private JLabel messageLabel= new JLabel("Enter distance in miles");
private JTextField milesTextField = new JTextField(10);;
private JButton calcButton = new JButton("Calculate");
public CalcPanel() {
JPanel panel = new JPanel();
panel.add(messageLabel);
panel.add(milesTextField);
panel.add(calcButton);
calcButton.addActionListener(new CalcButtonListener());
}
public static void main(String[] args) {
JFrame frame = new CalcPanel();
frame.setTitle("M to Km Converter");
frame.setLocationRelativeTo(null);
frame.setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) {
String input = milesTextField.getText();
double kilometers = Double.parseDouble(input) * 1.6023;
JOptionPane.showMessageDialog(null, input + " miles is " + kilometers + " kilometers.");
}
}
}
所以问题解决了,但这是另一个问题。该面板弹出,但我的messageLabel milesTextField calcButton没有显示。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Aaaa extends JFrame {
private JPanel panel;
private JLabel messageLabel= new JLabel("Enter distance in miles");
private JTextField milesTextField = new JTextField(10);;
private JButton calcButton = new JButton("Calculate");
public Aaaa() {
JPanel panel = new JPanel();
panel.add(messageLabel);
panel.add(milesTextField);
panel.add(calcButton);
setVisible(true);
calcButton.addActionListener(new CalcButtonListener());
}
public static void main(String[] args) {
JFrame frame = new Aaaa();
frame.setTitle("M to Km Converter");
frame.setLocationRelativeTo(null);
frame.setSize(300, 150);
}
class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) {
String input = milesTextField.getText();
double kilometers = Double.parseDouble(input) * 1.6023;
JOptionPane.showMessageDialog(null, input + " miles is " + kilometers + " kilometers.");
}
}
}
答案 0 :(得分:2)
您正在尝试创建构造函数,但构造函数的名称与类的名称不匹配。
改为public CalcPanel
改为public aaaaaa
。
答案 1 :(得分:1)
似乎是一个拼写错误,类和构造函数名称不匹配。您的类名是aaaaa,而构造函数名称是CalcPanel。