[英]How can I fix this error for Flow Layout in java?
I don't know why but I get an error everythime I run this code.我不知道为什么,但每次运行此代码时都会出错。
The error is: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setLayout(LayoutManager) in the type JFrame is not applicable for the arguments (FlowLayout) at gui.FlowLayout.main(FlowLayout.java:14) The error is: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setLayout(LayoutManager) in the type JFrame is not applicable for the arguments (FlowLayout) at gui.FlowLayout.main(FlowLayout.java: 14)
I'm learning Java and I'm a beginner so I don't really know what to do.我正在学习 Java 并且我是初学者,所以我真的不知道该怎么做。 Please help me.
请帮我。
package gui;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FlowLayout {
public static void main(String[] args) {
JFrame frame = new JFrame(); //cerates frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit out of application
frame.setSize(500, 500); //sets x-dimesion, and y-dimension of frame
frame.setLayout(new FlowLayout());
frame.add(new JButton("1"));
frame.setVisible(true);
}
}
There is a potential conflict between the class you created gui.FlowLayout
and java.awt.FlowLayout
, the layout you have to give to your frame.您创建的
gui.FlowLayout
和java.awt.FlowLayout
之间存在潜在冲突,您必须为框架提供布局。
The error is due to the fact the JFrame.setLayout()
method expects a java.awt.FlowLayout
and not a gui.FlowLayout
which is the only FlowLayout available in your code.该错误是由于
JFrame.setLayout()
方法需要java.awt.FlowLayout
而不是gui.FlowLayout
,这是您的代码中唯一可用的 FlowLayout 。
To fix that, I'd do the following为了解决这个问题,我会做以下
FlowLayoutExample
for example).FlowLayoutExample
)。java.awt.FlowLayout
you actually need.java.awt.FlowLayout
。 The code should become:代码应变为:
package gui;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame(); //cerates frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit out of application
frame.setSize(500, 500); //sets x-dimesion, and y-dimension of frame
frame.setLayout(new FlowLayout());
frame.add(new JButton("1"));
frame.setVisible(true);
}
}
Note: there is also another possibility: you can skip the import and directly mention the complete class name (with the package):注意:还有另一种可能:可以跳过导入,直接提及完整的 class 名称(带包):
frame.setLayout(new java.awt.FlowLayout());
I tend to prefer the first solution because:我倾向于更喜欢第一种解决方案,因为:
FlowLayout
doesn't reflect what your class does while FlowLayoutExample
is IMHO more explicit.FlowLayout
不能反映您的 class 所做的事情,而FlowLayoutExample
恕我直言更明确。 Just add the library: import java.awt.FlowLayout只需添加库: import java.awt.FlowLayout
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.