- How to set specific window (frame) size in java swing?
- Java swing set initial window size
- GUI APP-5 How to set Size and Alignment of a JFrame
- Change the GUI Window size
- General tips
- How do i set the size of a panel to the size of a window, even if the window size changes?
- Java JFrame size: How to set the JFrame size
- A JFrame size example
- More JFrame size information
- Class Window
How to set specific window (frame) size in java swing?
In this example: I click on button btnTest and the size of windows changes to no matter what else size. The 1st is left as an exercise for the reader. Don’t extend frame or other top level containers.
Java swing set initial window size
import java.util.*; public static void main(string args)< JFrame frame = new JFrame(); frame.setSize(200,200); // Where you set size frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); >
// make sure the new size is a float, not an int (add **** the end of the number) label.setFont(label.getFont().deriveFont(newSize));
Java JFrame Size according to screen resolution, Try this Select all components of JFrame, right click, select ‘Auto Resizing’, check for
GUI APP-5 How to set Size and Alignment of a JFrame
Hello Friends Welcome To My Channel.In this session i have discussed what are the different
Duration: 7:39
Change the GUI Window size
The problem and question is in line 50-51:
package exercise1; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; public class MainFrame extends JFrame < // ------------------------------------------------------------------------- public static void main(String[] args) < MainFrame frame = new MainFrame(); frame.pack(); frame.setVisible(true); >public MainFrame() < this.setTitle("Exercise 1"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocation(300, 200); this.getContentPane().setPreferredSize(new Dimension(400, 150)); this.getContentPane().setLayout(null); this.initContent(); >// ------------------------------------------------------------------------- private final JButton btnCombine = new JButton(); private void initContent() < this.add(btnTest); btnTest.setText("Change Size"); btnTest.setSize(100, 25); btnTest.setLocation(150, 100); btnTest.addActionListener(action); >// ------------------------------------------------------------------------- private final Controller action = new Controller(); private class Controller implements ActionListener < @Override public void actionPerformed(ActionEvent e) < if (e.getSource() == btnTest) < //CHANGE THE WINDOWS SIZE HERE; MainFrame.getContentPane().setPreferredSize(new Dimension(100, 200)); >> > >
How I can change the size of windows, if I have code like this?
There is one condition: I want to change the size of it on the button click. In this example: I click on button btnTest and the size of windows changes to no matter what else size.
I decided that instead of further critique on the accepted answer, it would be better to show what I mean (‘put your code where your mouth is’). See comments in source for more details.
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class MainFrame extends JFrame < JButton btnTest; JPanel btnContainer; // --------------------------------------------------------------- public static void main(String[] args) < Runnable r = new Runnable() < public void run() < JFrame frame = new MainFrame(); frame.pack(); frame.setVisible(true); >>; SwingUtilities.invokeLater(r); > public MainFrame() < this.setTitle("Exercise 1"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //this.setLocation(300, 200); BETTER TO.. this.setLocationByPlatform(true); // THESE NUMBERS ARE NOT MUCH BETTER THAN 'MAGIC NUMBERS' //this.getContentPane().setPreferredSize(new Dimension(400, 150)); // DON'T DO THIS - IT WILL CAUSE MORE PROBLEMS THAN IT FIXES //this.getContentPane().setLayout(null); this.initContent(); >// --------------------------------------------------------------- private final JButton btnCombine = new JButton(); private void initContent() < btnTest = new JButton("Change Size"); //btnTest.setSize(100, 25); DON'T GUESS COMPONENT SIZES! //btnTest.setLocation(150, 100); ADD A BORDER INSTEAD! // WE ACTUALLY ADD THE BORDER TO A CONTAINER THAT HOLDS THE BUTTON. // THIS WAY IT RETAINS THE USUAL BORDERS ON FOCUS, PRESS ETC. btnContainer = new JPanel(new GridLayout()); btnContainer.add(btnTest); btnContainer.setBorder(new EmptyBorder(100,150,100,150)); btnTest.addActionListener(action); add(btnContainer); >// --------------------------------------------------------------- private final Controller action = new Controller(); private class Controller implements ActionListener < @Override public void actionPerformed(ActionEvent e) < if (e.getSource() == btnTest) < //CHANGE THE WINDOWS SIZE HERE; btnContainer.setBorder(new EmptyBorder(30,20,30,20)); MainFrame.this.pack(); >> > >
General tips
The 2nd point is implemented in the above source. The 1st is left as an exercise for the reader.
- Don’t extend frame or other top level containers. Instead create & use an instance of one.
- Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space .
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them 1 , along with layout padding & borders for white space 2 .
MainFrame.getContentPane().setPreferredSize(new Dimension(100, 200));
setSize(new Dimension(100, 200));
You need to call the setSize method on your outer class object (which is the main frame).
Java swing set initial window size Code Example, import java.util.*; public static void main(string args)< JFrame frame = new JFrame(); frame.setSize(200200); // Where you set size frame.
How do i set the size of a panel to the size of a window, even if the window size changes?
This is my code. I would like to set the size of the box the ball bounces in to that of the window size, even if the window is resized by the user, such as making the window restored, or dragging it to a size. Thanks a lot.
import java.awt.*; import javax.swing.*; import java.awt.event.*; /** * One ball bouncing inside a rectangular box. * All codes in one file. Poor design! */ // Extends JPanel, so as to override the paintComponent() for custom rendering codes. public class BouncingBallSimple extends JPanel < // Container box's width and height private final int BOX_WIDTH = 700; private final int BOX_HEIGHT = 700; // Ball's properties private float ballRadius = 15; // Ball's radius private float ballX = ballRadius + 50; // Ball's center (x, y) private float ballY = ballRadius + 20; private float ballSpeedX = 60; // Ball's speed for x and y private float ballSpeedY = 60; private static final int UPDATE_RATE = 30; // Number of refresh per second /** Constructor to create the UI components and init game objects. */ public BouncingBallSimple() < this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT)); // Start the ball bouncing (in its own thread) Thread gameThread; gameThread = new Thread() < @Override public void run() < while (true) < // Execute one update step // Calculate the ball's new position ballX += ballSpeedX; ballY += ballSpeedY; // Check if the ball moves over the bounds // If so, adjust the position and speed. if (ballX - ballRadius < 0) < ballSpeedX = -ballSpeedX; // Reflect along normal ballX = ballRadius; // Re-position the ball at the edge >else if (ballX + ballRadius > BOX_WIDTH) < ballSpeedX = -ballSpeedX; ballX = BOX_WIDTH - ballRadius; >// May cross both x and y bounds if (ballY - ballRadius < 0) < ballSpeedY = -ballSpeedY; ballY = ballRadius; >else if (ballY + ballRadius > BOX_HEIGHT) < ballSpeedY = -ballSpeedY; ballY = BOX_HEIGHT - ballRadius; >// Refresh the display repaint(); // Callback paintComponent() // Delay for timing control and give other threads a chance try < Thread.sleep(1000 / UPDATE_RATE); // milliseconds >catch (InterruptedException ex) < >> > >; gameThread.start(); // Callback run() > /** Custom rendering codes for drawing the JPanel */ @Override public void paintComponent(Graphics g) < super.paintComponent(g); // Paint background // Draw the box g.setColor(Color.CYAN); g.fillRect(0, 0, getWidth(), getHeight()); // Draw the ball g.setColor(Color.BLUE); g.fillOval((int) (ballX - ballRadius), (int) (ballY - ballRadius), (int)(2 * ballRadius), (int)(2 * ballRadius)); Graphics2D comp2D = (Graphics2D) g; comp2D.drawRect(0, 645, 1365, 100); comp2D.setColor(Color.GREEN); comp2D.fillRect(0, 645, 1365, 100); Graphics2D stand = (Graphics2D) g; stand.setColor(Color.BLACK); stand.fillRect(80, 575, 30, 70); Graphics2D sling = (Graphics2D) g; sling.drawArc(15, 570, 90, 50, 50, 250); >/** main program (entry point) */ public static void main(String[] args) < // Run GUI in the Event Dispatcher Thread (EDT) instead of main thread. javax.swing.SwingUtilities.invokeLater(new Runnable() < @Override public void run() < // Set up main window (using Swing's Jframe) JFrame frame = new JFrame("Angry Birds for Annie May Tion"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new BouncingBallSimple()); frame.pack(); frame.setVisible(true); >>); > >
- Drop this line: this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
- Wherever you used BOX_WIDTH replace it with getWidth()
- Wherever you used BOX_HEIGHT replace it with getHeight()
It should be as simple as removing the call to this.setPreferredSize() in your constructor. When the window is resized, it will request the panel to resize itself. In your paint routine, you’re getting the current bounds of the panel and bouncing between them, so it should just work.
On an unrelated note: you should replace your aameThread with a javax.swing.Timer. As it is, you’re invoking paint requests from outside the event dispatch thread, which is a bad idea.
There is no simple answer here because you have hard coded x,y,w,h values. The not-so-simple answer is to use variables instead of hard coded values and dynamically adjust those values inside the paintComponent() method.
JFrame window size too big for screen?, getDisplayMode().getWidth(); int height = gd.getDisplayMode().getHeight(); frame.setSize(width, height); System.out.
Java JFrame size: How to set the JFrame size
Solution: There are several different ways to set the size of a Java JFrame , but I generally use the setPreferredSize method of the JFrame class in combination with the Java Dimension class, like this:
jframe.setPreferredSize(new Dimension(400, 300));
A JFrame size example
Here’s the source code for a complete «JFrame set size» example, showing how to use this setPreferredSize method call in an actual Java program.
import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class JFrameSize < public static void main(String[] args) < // schedule this for the event dispatch thread (edt) SwingUtilities.invokeLater(new Runnable() < public void run() < displayJFrame(); >>); > static void displayJFrame() < // create our jframe as usual JFrame jframe = new JFrame("JFrame Size Example"); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set the jframe size and location, and make it visible jframe.setPreferredSize(new Dimension(400, 300)); jframe.pack(); jframe.setLocationRelativeTo(null); jframe.setVisible(true); >>
More JFrame size information
For more information related to setting the JFrame size, see the Javadoc for the Java Window class (which JFrame inherits from). You’ll want to look at the Javadoc for these methods (part of which I have shown below):
- setSize — Resizes this component so that it has width w and height h. The width and height values are automatically enlarged if either is less than the minimum size as specified by previous call to setMinimumSize.
- setMinimumSize — Sets the minimum size of this window to a constant value. If current window’s size is less than minimumSize the size of the window is automatically enlarged to honor the minimum size. If the setSize or setBounds methods are called afterwards with a width or height less than that specified by setMinimumSize the window is automatically enlarged to honor the minimumSize value. Setting the minimum size to null restores the default behavior.
- setPreferredSize — Sets the preferred size of this component to a constant value. Subsequent calls to getPreferredSize will always return this value. Setting the preferred size to null restores the default behavior.
- setMaximumSize — Sets the maximum size of this component to a constant value. Subsequent calls to getMaximumSize will always return this value. Setting the maximum size to null restores the default behavior.
Note that some of those methods are actually in the Java Component class.
Class Window
A Window object is a top-level window with no borders and no menubar. The default layout for a window is BorderLayout .
A window must have either a frame, dialog, or another window defined as its owner when it’s constructed.
In a multi-screen environment, you can create a Window on a different screen device by constructing the Window with Window(Window, GraphicsConfiguration) . The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.
In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual device coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure.
In such an environment, when calling setLocation , you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Window returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system.
The following code sets the location of a Window at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration . If the bounds of the GraphicsConfiguration is not taken into account, the Window location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration .
Window w = new Window(Window owner, GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); w.setLocation(10 + bounds.x, 10 + bounds.y);
Note: the location and size of top-level windows (including Window s, Frame s, and Dialog s) are under the control of the desktop’s window management system. Calls to setLocation , setSize , and setBounds are requests (not directives) which are forwarded to the window management system. Every effort will be made to honor such requests. However, in some cases the window management system may ignore such requests, or modify the requested geometry in order to place and size the Window in a way that more closely matches the desktop settings.
Visual effects such as halos, shadows, motion effects and animations may be applied to the window by the desktop window management system. These are outside the knowledge and control of the AWT and so for the purposes of this specification are not considered part of the top-level window.
Due to the asynchronous nature of native event handling, the results returned by getBounds , getLocation , getLocationOnScreen , and getSize might not reflect the actual geometry of the Window on screen until the last request has been processed. During the processing of subsequent requests these values might change accordingly while the window management system fulfills the requests.
An application may set the size and location of an invisible Window arbitrarily, but the window management system may subsequently change its size and/or location when the Window is made visible. One or more ComponentEvent s will be generated to indicate the new geometry.
Windows are capable of generating the following WindowEvents: WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.