将两个简单的JLabel添加到jframe

时间:2013-01-13 02:05:53

标签: java swing jframe jlabel layout-manager

我到处都搜索过,而且有大量的文档,但是这些都令人困惑,而且有一半的测试代码无法正常工作,所以我在问。制作jlabel的最简单方法是什么,设置其位置(使用整数或维度),并将其添加到JFrame

package com.notelek.notify;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Gui {



    public static void main(String[] args){

    }

    public static void notify(String line1, String line2, String imagepath, int style){
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        int width = gd.getDisplayMode().getWidth();
        int swidth = width - 320;

        JFrame notification = new JFrame();
        notification.setSize(new Dimension(320,64));
        notification.setLocation(swidth, 0);
        notification.setUndecorated(true);
        notification.setVisible(true);

        JPanel main = new JPanel();

        JLabel notifyline1 = new JLabel();
        notifyline1.setText("test");
        notifyline1.setLocation(0, 0);
        main.add(notification);
    }

}

2 个答案:

答案 0 :(得分:3)

您需要将JLabel添加到可见容器中,否则它无法显示在屏幕上。

我还猜你确实打算将JPanel添加到JFrame而不是反之亦然 - 就像这样:

...
main.add(notifyline1);
...    
notification.add(main);
...

答案 1 :(得分:2)

我认为你的意思是notification.add(main);,订单很重要:

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

public class Gui {

    public static void main(String[] args){
        notify("", "", "", 0);
    }

    public static void notify(String line1, String line2, String imagepath, int style){
        JFrame notification = new JFrame();
        JPanel main = new JPanel();
        JLabel notifyline1 = new JLabel();
        notifyline1.setText("test");
        main.add(notifyline1);
        notification.add(main);
        notification.setSize(new Dimension(320,64));
        notification.setLocationRelativeTo(null);
        notification.setUndecorated(true);
        notification.setVisible(true);
    }
}