问题
I decided to write a small Java program to experiment around with BorderLayout, because I'm developing a Java game and I need to have 2 objects placed in a single JFrame at the same time, and everyone I asked said I need BorderLayout to do that.
So the Java program I wrote is supposed to place a JButton on the JFrame and ALSO place a graphic component (a rectangle in this case). The problem is, only the button shows up, as can be seen in the image link below:
http://prntscr.com/3m5ek6
I can't post actual images due to my low reputation statistic.
Here is the code:
main.java --> The main method class + JFrame/JPanel/JButton constructor
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class main {
public static void main(String[] args) {
Infout m = new Infout();
JFrame f = new JFrame();
JPanel start = new JPanel();
JPanel start2 = new JPanel();
start.add(m);
start2.add(new JButton("Hi"));
f.add(start,BorderLayout.LINE_START);
f.add(start2, BorderLayout.LINE_END);
f.setVisible(true);
f.setSize(300, 400);
}
}
Infout.java --> Rectangle constructor class
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
public class Infout extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.fill(new Rectangle2D.Double(140, 270, 5, 300));
}
}
Can someone tell me what's wrong? Also, is using BorderLayout the best option for adding multiple static and/or dynamic objects to a JFrame?
Thanks!
Ab
回答1:
You need to override the getPreferredSize()
method so the layout manager can determine the proper size for the component.
How do I do that?
Read the section from the Swing tutorial on Custom Painting for more information on custom painting, including a working example that shows how to override the getPreferredSize()
method.
来源:https://stackoverflow.com/questions/23847066/borderlayout-only-showing-one-object