Search code examples
javaswingprogram-entry-point

how can i use setPreferredSize in java?


I have a problem: I want to create a small game, I have to make a window like the following:

enter image description here

When I tried to change the font size of "Fun With Words", it wasn't changed ...

What should I do?

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



public class GameWords extends JFrame 

{
    private static int W = 800 ;
    private static int H = 600 ;



    public GameWords ()
    {
         setTitle ( " Word Order Game " ) ;
         setSize ( H , W ) ;
         setLayout ( new FlowLayout() ) ;
         setDefaultCloseOperation ( EXIT_ON_CLOSE ) ;
         createContent () ;
         setVisible ( true ) ;
    }

    public void createContent ()
    {
        JLabel heading = new JLabel (" Fun With Words ") ;
        heading.setFont ( heading.getFont().deriveFont ( 26f ) );
        heading.setPreferredSize ( new Dimension ( H , 4 * W ) ) ;
        JLabel h1 = new JLabel ( " Hey Kids! Want to prictice your typing and word-ordering Skills ? \n" ) ;
        add ( heading ) ;
        add ( h1 ) ;


    }


    public static void main(String[] args) 

    {
        new GameWords () ;

    }

}

Solution

  • The short answer is don't, the API is quite capable of calculating the desired size it self.

    The longer answers is, don't use setSize, use pack instead, which uses the containers preferred size to calculate the size of the window

    public GameWords ()
    {
         setTitle ( " Word Order Game " ) ;
         setLayout ( new FlowLayout() ) ;
         setDefaultCloseOperation ( EXIT_ON_CLOSE ) ;
         createContent () ;
         pack();
         setVisible ( true ) ;
    }
    
    public void createContent ()
    {
        JLabel heading = new JLabel (" Fun With Words ") ;
        heading.setFont ( heading.getFont().deriveFont ( 26f ) );
        JLabel h1 = new JLabel ( " Hey Kids! Want to prictice your typing and word-ordering Skills ? \n" ) ;
        add ( heading ) ;
        add ( h1 ) ;
    
    
    }
    

    As a general recommendation, you shouldn't extend directly from a JFrame, you're not adding any new functionality to the class and you're locking yourself into a single use case. As a general recommendation, you should start by extending from JPanel and then add this to whatever container you want to use