JButton not appearing on JFrame

若如初见. 提交于 2019-12-11 14:12:23

问题


Following is the code in which the jbutton is not showing on the frame. I have also set visible to true. Even then the button doesn't appear.

class gui{
        public static void main(String args[]){
            layoutBorder lb=new layoutBorder("check");
        }
    }

class layoutBorder extends JFrame{
    layoutBorder(String title){
        super(title);
        setLayout(null);
        setSize(200, 200);
        JButton jb=new JButton("JB");
        add(jb);
        setVisible(true);
    }
}

回答1:


If you want null layouts then you need to set sizes and position by yourself. Using the setLocation and setSize methods.

class gui{
        public static void main(String args[]){
            layoutBorder lb=new layoutBorder("check");
        }
    }

class layoutBorder extends JFrame{
    layoutBorder(String title){
        super(title);
        setLayout(null);
        setSize(200, 200);
        JButton jb=new JButton("JB");
        jb.setLocation(10, 10);
        jb.setSize(40, 30);
        add(jb);
        setVisible(true);
    }
}



回答2:


Don't use a null layout!!!

Swing was designed to be used with layout managers.

Read the section from the Swing tutorial o Layout Managers for more information.

I suggest you download the working examples and play with them. The example will also show you how to better structure your code. Maybe start with the code from How to Use Buttons, which has a simple example that adds 3 buttons to a panel and then the panel to the frame.

Also, class names should start with an upper case character. Have you even seen a class in the API that doesn't??? Learn Java conventions and follow them.




回答3:


camickr is right. Also, always use the AWT event dispatching thread when an application thread needs to update the GUI.

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

public class Gui {
    public static void main(String args[]) {
        SwingUtilities.invokeLater(() -> {
            MyFrame frame = new MyFrame("check");
        });
    }
}

class MyFrame extends JFrame {
    MyFrame(String title){
        super(title);
        setLayout(new BorderLayout());
        setSize(200, 200);
        JButton jb = new JButton("JB");
        add(jb);
        setVisible(true);
    }
}


来源:https://stackoverflow.com/questions/50065116/jbutton-not-appearing-on-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!