我希望能够在我的JFrame中拥有一个固定大小为400x400的JPanel。
我还希望它周围有一个20px宽的边框。
主要问题是以下代码没有坚持它的大小.JScrollPane runningAni = new JScrollPane(new views.cRunningAnimation( 模型));
runningAni.setMaximumSize(new Dimension(400,400));
this.setSize(new Dimension(600,600));
this.add(runningAni,BorderLayout.CENTER);`
执行此操作时,runningAni面板只会在整个帧中延伸。
public void paint(Graphics g) {
this.setBackground(new Color(0,255,0));
}
我知道这是因为我的全帧画自己绿色而不仅仅是JPanel(上面的油漆代码是我的面板而不是框架)
我如何创建面板以使其始终保持相同的尺寸,因此它周围总是有20px的彩色边框?
答案 0 :(得分:3)
BorderLayout
忽略了大小。您需要设置一个LayoutManager
,允许您将大小设置为固定大小,或者设置一个关注大小设置的大小。有不同的布局管理器允许这样做(例如GrindBagLayout
或根本没有布局管理器)。有些不是那么容易使用(例如GridBagLayout
)。使用什么取决于布局的其余部分。
您可以使用包含自定义面板的布局面板。布局面板需要适当的布局管理器,并且可以放在BorderLayout
的中心。这意味着几乎不会修改现有的布局代码。
BorderLayout
的重点是用中心组件填充中心。
答案 1 :(得分:1)
答案 2 :(得分:1)
只需将您的布局设置为null,即可添加JPanel。 然后使用setBounds()方法设置您的位置和大小!
例如:
public class Main extends JFrame{
YourPanelClass panel = new YourPanelClass();
public Main(){
// I didn't want to put all the, everyday JFrame methods...
setLayout(null);
/*
First two coordinates indicate the location of JPanel inside JFrame.
The seconds set of coordinates set the size of your JPanel.
(The first two coordinates, 0 and 0, tell the JPanel to start at the
top left of your JFrame.)
*/
panel.setBounds(0, 0, 100, 100);
add(panel);
}
}
我会 GREATLY 推荐使用paintComponent()方法。
例如: (显然你把它放在JPanel的课上。)
public void paintComponent(Graphics g){
super.paintComponent(g); // don't forget this if you are going to use this method.
//Basically this makes your JPanel's background green(I did it this way because I like doing it this way better.)
g.setColor(new Color(0, 255, 0));
g.fillRect(0, 0, getWidth(), getHeight());
}
如果这有帮助,请不要忘记竖起大拇指!
答案 3 :(得分:-1)
setPreferredSize()
setMinimumSize()
setMaximumSize()
应该做的伎俩