簡體   English   中英

JLabels到JFrame

[英]JLabels into JFrame

我是JAVA的新手,並且需要以下代碼的幫助。 我寫了兩節課。 在其中一個中,我聲明了JFrame,在另一個中,我聲明了JLabel。 我想通過此方法將Label添加到Frame,但出現錯誤。 我應該做些什么改變才能使其正常工作:

import java.awt.*;
import javax.swing.*;

public class test {

    public static void main (String[] args) {

        JLabel l1 = new JLabel("Label into Frame");
        Frame f1 = new Frame();
        f1.displayFrame.add(l1);
        f1.displayFrame();      
    }   
}

class Frame {

    void displayFrame() {

        JFrame frame = new JFrame("Test");
        frame.setVisible(true);
    }   
}

您不能像這樣創建它。 如果要構建自定義框架類,則必須像

public class MyFrame extends JFrame

獲取所有的JFrame方法等等。 在上面的代碼中,您先調用displayFrame ,然后再嘗試調用方法add ,這將無法正常工作。 要使其工作(以最簡單的形式),請嘗試以下操作:

public static void main(String[] args) {

    JLabel l1 = new JLabel("Label into Frame");
    JFrame f1 = new JFrame();
    f1.setSize(100, 100);
    f1.add(l1);
    f1.setVisible(true);
}

我建議您嘗試閱讀一些不錯的Java教程,以了解基礎知識。

-它總是好的,以保持UI的工作UI線程, Non-UI的工作Non-UI線程。

-現在在Java GUI應用程序中, main()方法已經存在很長一段時間了,在Event Dispatcher Thread安排了GUI的構造之后,它退出了,現在EDT負責處理該GUI。

-不要直接放置 JLableJFrame ,請嘗試使用JPanelJFrame ,然后將一個JLable就可以了。

-但為了簡單起見,在這里我將不使用 JPanel。

例如:

class MyFrame extends JFrame {

    JLabel l1;

    public MyFrame() {

        this.setSize(400,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setComponent();
        setHandling();

    }   

    public void setComponent(){

    l1 = new JLabel("Label into Frame");
    this.add(l1);

    }

    public void setHandling(){

      // Use this to handle the Events on the EventSources.
    }

    public static void main(String[] args){

       EventQueue.invokeLater(new Runnable(){

         MyFrame frame = new MyFrame("Test");
        frame.setVisible(true);

       });

    }
}

方法displayFrame不返回任何內容

void displayFrame() {...}

方法減速遵循{accessibility} [type] [name({parameter {,parameter ...}}})]的模式

可訪問定義了誰可以訪問該方法,並包括publicprotectedprivatepackage-private

類型是指此方法將返回的值的類型。 特殊類型的void表示該方法將不返回值

名稱是方法的名稱,這是您識別方法和訪問方法的方式

參數是您要傳遞給方法的任意數量的可選值。

有了這些信息,讓我們仔細看看該方法。

void displayFrame() {...}

這意味着該方法是程序包專用的 (這意味着該方法只能從同一程序包中的with進行訪問,而不能由子類擴展),並且將不返回任何內容。

f1.displayFrame.add(l1);

因此,當您調用此方法時,Java無法弄清楚如何將ad(...)應用於所有內容,這沒有任何意義。

更好的解決方案是提供getter方法以獲取幀或從displayFrame方法返回幀。 兩者都有很好的論據,但我個人更喜歡使用吸氣劑

public class test {

    public static void main (String[] args) {

        JLabel l1 = new JLabel("Label into Frame");
        Frame f1 = new Frame();
        JFRame myFrame = f1.getFrame();
        myFrame.add(l1);
        f1.displayFrame(); // there's actually no need for this 
    }   
}

class Frame {
    private JFrame frame = new JFrame("Test");

    public JFrame getFrame() {
        return frame;
    }

    void displayFrame() {
        frame.setVisible(true);
    }   
}

我會花時間通讀《 學習Java語言》

暫無
暫無

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

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