Java Swing setting JPanel Size

This may not answer your immediate question…but… You set the layout as a GridLayout, but you are using BorderLayout constraints to apply one of the components?? Also, make sure that there are not calls to Test#pack else where in your code, as this will override the values of setSize UPDATED (from changes to question) Remember, … Read more

How can I set size of a button?

The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them … Read more

How does paintComponent work?

The (very) short answer to your question is that paintComponent is called “when it needs to be.” Sometimes it’s easier to think of the Java Swing GUI system as a “black-box,” where much of the internals are handled without too much visibility. There are a number of factors that determine when a component needs to … Read more

KeyPressed event in java

Depending on where you want to trap the “enter” key, you could use an ActionListener (on such components such as text components or buttons) or attach a key binding to you component This will rely on the component being focused.

Java Swing revalidate() vs repaint()

You need to call repaint() and revalidate(). The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by removeAll()); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause children of the panel to repaint, but may not … Read more

Setting background images in JFrame

There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is: Create a subclass of JComponent. Override the paintComponent(Graphics g) method to paint the image that you want to display. Set the content pane of the JFrame to be this subclass. Some sample code: Note that … Read more

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, … Read more