Reputation: 39
When I run this code my Panel instance inner comes out about 20 by 20 pixels instead of the 300, 400 I'm trying to set it as. Can someone please help me find out why ? Obviously I'm not very experienced with swing or java2D. Thanks
edit: I'm trying to display the Board at size 600, 600 and inside that a blue panel of size 300, 400
//Application.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.*; //for Color
public class Application extends JFrame {
public Application() {
initUI();
}
private void initUI() {
//to put panels in here I have to write the class that defines them
//such as Board. Theyll all extend JPanel and import it!
Board brd = new Board();
setSize(600, 600);
setTitle("Application");
Panels inner = new Panels(300, 400);
brd.add(inner);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); //Performed on JFrame
getContentPane().add(brd);
}
public static void main (String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Application ex = new Application();
ex.setVisible(true);
}
});
} //end main()
}
//Board.java
import javax.swing.JPanel;
public class Board extends JPanel {
public Board() {}
} //end Board
//Panels.java
import javax.swing.JPanel;
import java.awt.*;
public class Panels extends JPanel {
public int width;
public int height;
public Panels(int w, int h) {
width = w;
height = h;
setSize(w, h);
setBackground(Color.BLUE);
}
//methods
}
Upvotes: 0
Views: 66
Reputation: 39
I think that when Swing is used for games or 'fun' sort of animation the premise is ... you paint components on the JPanel. Not instantiate lots of JPanels and move them around. It's what I misunderstood!
Upvotes: 0
Reputation: 347334
First you will want to read and understand Laying Out Components Within a Container...
The problem you're facing is the fact that Board
is using a FlowLayout
by default. You could change it's layout manager to something like BorderLayout
and Panels
will fill the available space.
Pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
If you want to affect the size of your component during the layout manager, you should override the getPreferredSize
method and return a default size you want.
You should use pack
on your windows, as this will pack the window around the content so that the content area meets the requirements as specified by the layout manager(s)
Upvotes: 2