JFrame:setSize(int width, int height)
JFrame:setSize(int width, int height) is a method that is used to set JFrame size.This method takes two integers which represent height and width.Other JFrame methods are setLocation,setJMenuBar etc.
Also JFrame window can implement WindowListener interface.
Also JFrame window can implement WindowListener interface.
JFrame:setSize(int width, int height) Example
[
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Font; import javax.swing.JPanel; import javax.swing.JFrame; public class JFrameSetSize extends JPanel{ public void paint(Graphics g) { Dimension d=this.getPreferredSize(); int fontSize=15; Font f=new Font("TmesRoman",Font.BOLD,fontSize); g.setFont(f); g.setColor(Color.BLUE); g.drawString("I love Programming in Java", 20, 20); } public static void main(String[] args) { JFrame f = new JFrame("JFrame:setSize(int width, int height)"); f.getContentPane().add(new JFrameSetSize()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300,300); f.setLocationRelativeTo(null); f.setVisible(true); } }
]
Code Explanation
- Code [JFrame f = new JFrame("JFrame:setSize(int width, int height)");] creates a new JFrame window with a tittle.
- [ f.getContentPane().add(new JFrameSetSize());]-adds JPanel contents to the JFrame.
- [ f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);]-sets Default close operation when the close button is clicked.
- [f.setSize(300,300);]-sets JFrame window size.
- [f.setLocationRelativeTo(null);]-positions JFrame window at the center of the screen.
- [f.setVisible(true);]-makes the window visible.
Setting JFrame Window size using Dimension class.
[
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Font; import javax.swing.JPanel; import javax.swing.JFrame; public class JFrameSetSize extends JPanel{ public void paint(Graphics g) { Dimension d=this.getPreferredSize(); int fontSize=15; Font f=new Font("TmesRoman",Font.BOLD,fontSize); g.setFont(f); g.setColor(Color.BLUE); g.draw3DRect(100, 100,100, 100, false); } public static void main(String[] args) { JFrame f = new JFrame("JFrame:setSize(int width, int height)"); f.getContentPane().add(new JFrameSetSize()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(new Dimension(400,400)); f.setLocationRelativeTo(null); f.setVisible(true); } }
]
Output
Code Explanation
Above class extends JPanel Swing component and that the reason why we can access [public void paint(Graphics g)] method.
Below code creates a 3D rectangle object.
[public void paint(Graphics g)
{ Dimension d=this.getPreferredSize(); int fontSize=15; Font f=new Font("TmesRoman",Font.BOLD,fontSize); g.setFont(f); g.setColor(Color.BLUE); g.draw3DRect(100, 100,100, 100, false);
}]
[f.setSize(new Dimension(400,400));]-sets JFrame window size using Dimension class.