How to give a preffered size to the JButton?

后端 未结 2 825
囚心锁ツ
囚心锁ツ 2021-01-27 13:49
   import javax.swing.*;
   import java.awt.*;
   class MainGui{
         JFrame frame = new JFrame();
         JPanel mainPanel = new JPanel();
         JButton newBut          


        
2条回答
  •  误落风尘
    2021-01-27 14:43

    You should take a look at A Visual Guide to Layout Managers and choose the most appropriate one for your situation. You should also avoid explicitly setting sizes (ie: setSize, setMinimumSize, setMaximumSize, and setPreferredSize) because those methods are the responsibility of the layout manager. You may also be interested in reading this question on whether or not the use of the different set size methods should be avoided or not.

    Finally, you should not be calling your MainGUI class outside of the Event Dispatch Thread (EDT). Most Swing GUI-related methods are not thread safe and therefore require being executed in the EDT. Below is a corrected version of your main method:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MainGui mainGui = new MainGui();
            }
        });
    }
    

提交回复
热议问题