2013-03-25 122 views
0

我希望能够在我的JFrame中有一个固定大小的400x400的JPanel。Java Swing JPanel大小

我也想要成为一个20px的宽边框。主要问题是下面的代码不会粘到它的大小。“JScrollPane runningAni = new JScrollPane(new views.cRunningAnimation( model));

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的彩色边框?

回答

3

BorderLayout忽略的大小。您需要设置一个LayoutManager,它允许您将尺寸设置为固定尺寸或设置尺寸。有不同的布局管理器允许这样做(例如GrindBagLayout 或者根本没有布局管理器 )。有些不易使用(例如GridBagLayout)。要使用什么取决于其他布局。

您可以使用包含自定义面板的布局面板。布局面板需要适当的布局管理器,并可以放置在BorderLayout的中心。这意味着几乎不会修改现有的布局代码。

BorderLayout整点是用中心组件填充中心。

+0

我喜欢+1!我将如何能够设置我的Jpanel e ..g边框边框添加边框在里面添加? – LmC 2013-03-25 16:58:32

+0

+1,用于使用合适的布局管理器。 – camickr 2013-03-25 17:04:44

+3

不要建议不要使用LayoutManager,请!!! – 2013-03-25 17:19:47

-1
setPreferredSize() 
setMinimumSize() 
setMaximumSize() 

应该做的伎俩

+0

坏主意,差建议。这些方法应该被遗忘 – 2013-03-25 17:20:08

+0

这个答案甚至不是很正确。使用这些方法的必要性很少,但我认为他们不需要像上面提到的那样被遗忘。他们仍然有其用途偶尔进行调整。 – Michael 2013-03-25 18:43:42

1

请勿重写paint()方法来设置面板的颜色。使用:

panel.setBackground(...); 

当您创建面板。

我会怎么能够设置一个边界在我的JPanel

How to Use Borders

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); 
     } 
} 

,我会不胜推荐使用的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()); 
} 

如果这有帮助,请不要忘记竖起大拇指!