[英]How can I fix this error for Flow Layout in java?
我不知道為什么,但每次運行此代碼時都會出錯。
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)
我正在學習 Java 並且我是初學者,所以我真的不知道該怎么做。 請幫我。
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);
}
}
您創建的gui.FlowLayout
和java.awt.FlowLayout
之間存在潛在沖突,您必須為框架提供布局。
該錯誤是由於JFrame.setLayout()
方法需要java.awt.FlowLayout
而不是gui.FlowLayout
,這是您的代碼中唯一可用的 FlowLayout 。
為了解決這個問題,我會做以下
FlowLayoutExample
)。java.awt.FlowLayout
。代碼應變為:
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);
}
}
注意:還有另一種可能:可以跳過導入,直接提及完整的 class 名稱(帶包):
frame.setLayout(new java.awt.FlowLayout());
我傾向於更喜歡第一種解決方案,因為:
FlowLayout
不能反映您的 class 所做的事情,而FlowLayoutExample
恕我直言更明確。只需添加庫: import java.awt.FlowLayout
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.