Java - JPanel只是我JFrame顶部中心的一个小像素

时间:2013-11-08 08:39:50

标签: java swing jpanel layout-manager flowlayout

JPanel称为面板仅显示为顶部中心的一个小红色方块,我试图设置尺寸,但它似乎没有做任何事情。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;   

public class Draw extends JFrame{

private JPanel panel;

    public Draw() {
        super("title");
        setLayout(new FlowLayout());        
        panel = new JPanel();       
        panel.setBackground(Color.RED);
        add(panel, BorderLayout.CENTER);
    }
}

2 个答案:

答案 0 :(得分:5)

JPanel的默认首选尺寸为0x0FlowLayout根据首选大小布置组件,因此组件现在的首选大小为1x1(线条边框会增加一点重量)。

您可以尝试将另一个组件添加到panel ...

panel.add(new JLabel("This is some text"));

或覆盖panel s getPreferredSize方法......

panel = new JPanel() {
    public Dimension getPreferredSize() {
        return new Dimension(100, 100);
    }
};

答案 1 :(得分:1)

试试这个:

文件Draw.java

   package com.stackovfl;

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;

    @SuppressWarnings("serial")
    class Draw extends JFrame {
    private JPanel panel;

      public Draw() {
        super("title");
        setLayout(new FlowLayout());
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(200, 300));
        panel.setBackground(Color.RED);     
        add(panel, BorderLayout.CENTER);
        /* Important to get the layout to work */
        pack();     
        /* Center the window */
        setLocationRelativeTo(null);        
        /* Important if you want to see your window :) */
        setVisible(true);
        }
    }

File Test.java(启动窗口的主要方法): 包com.stackovfl;

import javax.swing.SwingUtilities;

public class Test {
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Draw();
        }
    });
   }
}