簡體   English   中英

如何修復 java 中的流布局錯誤?

[英]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.FlowLayoutjava.awt.FlowLayout之間存在潛在沖突,您必須為框架提供布局。

該錯誤是由於JFrame.setLayout()方法需要java.awt.FlowLayout而不是gui.FlowLayout ,這是您的代碼中唯一可用的 FlowLayout 。

為了解決這個問題,我會做以下

  1. 通過重命名您創建的 class 來消除歧義(例如,改為FlowLayoutExample )。
  2. 導入你實際需要的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恕我直言更明確。
  • 始終使用完整的 class 名稱會使您的代碼更冗長,從而降低可讀性。

只需添加庫: import java.awt.FlowLayout

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM