java JPanel setSize和setLocation

时间:2013-08-07 14:20:48

标签: java swing layout jframe jpanel

嘿,这是我的第二篇文章,所以不要生我的气,但我在java中遇到了JPanel的问题。我试图设置大小和位置,但它不会工作,我尝试了repaint(); 但这不起作用。有什么帮助吗?

这是我的代码:

package test.test.test;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.TextField;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame  {

  JPanel colorPanel = new JPanel();

  public Display(){
    super("JPanel test");
    setLayout(new FlowLayout());
    add(colorPanel);
    colorPanel.setBackground(Color.CYAN);
    colorPanel.setSize(300, 300);
    repaint();
  } 
}

2 个答案:

答案 0 :(得分:2)

为了以后阅读此问题的任何人的利益,这里是一个简短,自包含,正确的示例,用于定义具有背景颜色的JPanel。

几乎所有时候,都应该让Swing组件布局管理器确定Swing组件的大小。在这种情况下,我们定义JPanel的首选大小,因为JPanel不包含任何其他Swing组件。

JFrame的默认布局管理器是BorderLayout。 JPanel位于BorderLayout的中心。

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class SimplePanel implements Runnable {

    @Override
    public void run() {
        JFrame frame = new JFrame("JPanel Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel colorPanel = new JPanel();
        colorPanel.setBackground(Color.CYAN);
        colorPanel.setPreferredSize(new Dimension(300, 300));

        frame.add(colorPanel);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new SimplePanel());
    }

}

答案 1 :(得分:1)

使用Flowlayout时,您应该设置首选大小(您添加到面板的组件)而不是大小,因为布局管理器会为您处理大小的位置。

public class Test extends JFrame  {

  JPanel colorPanel = new JPanel();

  public Display(){
    super("JPanel test");
    getContentPane().setLayout(new FlowLayout());
    colorPanel = new JPanel
    colorPanel.setPreferedSize(new Dimension(300,300));
    colorPanel.setBackground(Color.CYAN);
    getContentPane().add(colorPanel);
    pack();
    repaint();
  } 
}

并且不要忘记将JFrame设置为可见且大小(使用pack());)