我正在为即将到来的考试而学习,教授除了给这本书学习以外,什么也没给我们学习,到目前为止我正在学习,但是我在本书提供的Jlabel代码上遇到了错误
码:
import javax.swing.*;
import java.awt.*;
public class JLabel extends JFrame
{
private int Width = 400;
private int Height = 300;
private JLabel LengthL, WidthL, AreaL, PerimeterL;
public JLabel()
{
setTitle("Area and Perimeter of a Rectangle");
LengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
WidthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
AreaL = new JLabel("Area: ", SwingConstants.RIGHT);
PerimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
Container Pane = getContentPane();
Pane.setLayout(new GridLayout(4,1));
Pane.add(LengthL);
Pane.add(WidthL);
Pane.add(AreaL);
Pane.add(PerimeterL);
setSize(Width, Height);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String [] args)
{
JLabel JL = new JLabel();
}
}
错误:
Constructor Jlabel in class JLabel cannot be applied to given types;
required: no arguments
found: java.lang.String, int
reason: actual and formal argument list differ in length
根据书的预期输出:
抱歉,对于初学者来说,我正在查看此示例代码,但似乎找不到该错误
最佳答案
这里的问题是您已经调用了类JLabel。然后,编译器将尝试在编译时使用此类,而不是您的书希望使用的javax.swing。*包中的JLabel。
我们可以说是这种情况,因为在错误消息中它指出required: no arguments
。您实现的构造函数没有任何参数,并且您没有可用的参数String, int
构造函数,因此编译器正在寻找不存在的构造函数。
要解决此问题,只需将您的类的名称更改为其他名称(如LabelTest或MyLabel等)。
现在,编译器将使用java.swing中的JLabel类,该类具有一些可用的构造函数,其中包括本书期望使用的构造函数。
关于通常被认为是好的做法的简要说明:
导入时,您的目标应该是仅导入所需的类,而不是整个包。
import javax.swing.*;
是导入整个javax.swing包,而实际上您只需要其中的几个类。相反,您应该尝试使用:
import javax.swing.JLabel;
这将导入特定的类,并有助于使其更清楚地导入和使用哪些类。它还可以帮助您在代码中识别所使用的每个类的来源。
给出完整的解决方法:
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class LabelTest extends JFrame
{
private int Width = 400;
private int Height = 300;
private JLabel LengthL, WidthL, AreaL, PerimeterL;
public LabelTest()
{
setTitle("Area and Perimeter of a Rectangle");
LengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
WidthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
AreaL = new JLabel("Area: ", SwingConstants.RIGHT);
PerimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
Container Pane = getContentPane();
Pane.setLayout(new GridLayout(4,1));
Pane.add(LengthL);
Pane.add(WidthL);
Pane.add(AreaL);
Pane.add(PerimeterL);
setSize(Width, Height);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String [] args)
{
LabelTest JL = new LabelTest();
}
}
希望这可以帮助!
关于java - 无法应用Jlabel;原因: actual and formal argument list differ in length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61903436/