将JLabel添加到JFrame

时间:2017-05-24 16:15:26

标签: java swing jframe jlabel

我在将JLabel添加到JFrame时遇到问题。我使用了几个教程中描述的JPanel,但Label没有在框架中弹出;与其他摆动组件相同的问题,如JTextField,JButton等。绘图线,矩形等确实有效。我希望有人知道,我在这里犯了什么样的错误:

package plot1;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class Gui extends JFrame {

    private JPanel contentPane;

    public Gui(){

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);    

        setSize(1200, 600);
        setLayout(null);
        setLocationRelativeTo(null);
        setTitle("Plot");
        addWindowListener(new WindowAdapter(){
            public void windowClosed(WindowEvent evnt){
                System.exit(0);
            }
        }); 
        setResizable(false);    

        JLabel lblStanFunc = new JLabel("Die Funktionssyntax lautet:");
        lblStanFunc.setBounds(800, 40, 300, 30);
        lblStanFunc.setVisible(true);
        add(lblStanFunc);

    }

}

main-method在另一个类中:

   package plot1;

   public class Main {
       public static void main(String[] args){

           new Gui().setVisible(true);;

       }
   }

框架按预期弹出,但JLabel丢失。感谢所有有用的评论。

2 个答案:

答案 0 :(得分:3)

只需添加setVisible(true)

import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class GUI extends JFrame {
     private JPanel contentPane;

        public GUI(){

            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new BorderLayout(0, 0));
            setContentPane(contentPane);    

            setSize(1200, 600);
            setLayout(null);
            setLocationRelativeTo(null);
            setTitle("Plot");
            addWindowListener(new WindowAdapter(){
                public void windowClosed(WindowEvent evnt){
                    System.exit(0);
                }
            }); 
            setResizable(false); 
            setVisible(true);

            JLabel lblStanFunc = new JLabel("Die Funktionssyntax lautet:");
            lblStanFunc.setBounds(800, 40, 300, 30);
            lblStanFunc.setVisible(true);
            add(lblStanFunc);

        }

        public static void main(String[] args) {
            new GUI();
        }
}

答案 1 :(得分:0)

我也无法重现它。正如扫描者所提到的,如果您的屏幕不够大,请将框架大小更改为setSize(800, 600)并将位置标记为lblStanFunc.setBounds(300, 250, 300, 30)。标签应位于屏幕的中心。