Frame resizing based on screen size
Hi everybody,
I'm trying to make a JFrame and all its contents resize dynamically based on whatever screen size the user has. The text on my JButtons and JLabel won't resize consistently. Screen widths below 2000 and above 3000 pixels cause problems. I tried to scale the fonts based on how big they were when the window was 700 pixels wide.
Can anyone tell me what I'm doing wrong? Here's a self-contained example--
publicclass Test{
publicstaticvoid main( String args[] ){
try{
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
JFrame frame =new JFrame("Test" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize( width / 2, height / 2 );
// Create main label
JLabel label =new JLabel("Test" );
label.setBackground(new Color( 179, 0, 0 ) );
label.setForeground(new Color( 235, 191, 16 ) );
label.setHorizontalAlignment( SwingConstants.CENTER );
label.setOpaque(true );
Font font =new Font("Old English Text MT", 0, 48 );
float fontSize = 48 * ( ( width / 2 ) / 700 );
font = font.deriveFont( fontSize );
label.setFont( font );
frame.add( label, BorderLayout.NORTH );
// Create button panel and buttons
JPanel panel =new JPanel(new GridLayout( 0, 2 ) );
for(int i = 0; i < 2; i++ ){
JButton button;
if( i == 0 ){
button =new JButton("Test Button 1" );
}else{
button =new JButton("Test 2" );
}
button.setBackground(new Color( 104, 17, 2 ) );
button.setForeground(new Color( 212, 212, 212 ) );
Font buttonFont =new Font("Wide Latin", 0, 25 );
float buttonFontSize = 25 * (float)( ( width / 4 ) / 350 );
buttonFont = buttonFont.deriveFont( buttonFontSize );
button.setFont( buttonFont );
panel.add( button );
}
panel.setName("Startup Panel" );
frame.add( panel );
frame.setLocationRelativeTo(null );
frame.setVisible(true );
}catch(Exception e){
e.printStackTrace();
System.exit(-1);
}
}
}
Thank you!
Jezzica85

