JPanel不会在BorderLayout中显示

时间:2011-10-12 21:22:02

标签: java swing layout-manager

我有一个边框布局,右边是JPanel。 JPanel有绝对的布局,它不包含任何东西,因为我用它来绘制图形(覆盖paintComponent(Graphics g))

问题是面板没有显示(它在那里,但像1像素宽)。我尝试在面板上设置尺寸..但这不起作用..

我该怎么做?

frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
JPanel panelCenter = new JPanel();
panelRight = new ActorDrawer();
frame.getContentPane().add(panelRight, BorderLayout.EAST);
panelRight.setSize(200, 400);
panelRight.setLayout(null);
frame.getContentPane().add(panelCenter, BorderLayout.CENTER);
frame.getContentPane().add(panelBottom, BorderLayout.SOUTH);
table = new JTable(new MyTableModel());
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
panelCenter.add(scrollPane);

3 个答案:

答案 0 :(得分:3)

查看JPanel.setPreferredSize()方法。另外,我认为JFrame.setBounds()调用不是你想要的。这是一个例子:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.BorderLayout;

public class Sandbox extends JFrame
{
    class MyPanel extends JPanel
    {
        public void paintComponent(Graphics g)
        {
            g.setColor(Color.RED);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
        }
    }

    public static void main(String[] args)
    {
        Sandbox s = new Sandbox();
    }

    public Sandbox()
    {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new BorderLayout());

        MyPanel panelRight = new MyPanel();
        panelRight.setPreferredSize(new Dimension(150, 300));
        this.getContentPane().add(panelRight, BorderLayout.EAST);

        JPanel panelCenter = new JPanel();
        this.getContentPane().add(panelCenter, BorderLayout.CENTER);

        JScrollPane scrollPane = new JScrollPane(new JTable());
        panelCenter.add(scrollPane);

        JPanel panelBottom = new JPanel();
        this.getContentPane().add(panelBottom, BorderLayout.SOUTH);

        this.setSize(400, 400);
        this.setVisible(true);
    }
}

答案 1 :(得分:1)

BorderLayout表示东部组件的首选大小,并在必要时拉伸其高度。您是否尝试过设置面板的首选大小(或覆盖getPreferredSize方法以返回您喜欢的大小)?

答案 2 :(得分:0)

这里有解决方案!我正在做同样的事情。

JPanel panel = new JPanel();          
JLabel strech_label = new JLabel("As long as you need ,  Dummy Text");
strech_label.setPreferredSize( new Dimension( 111, 0 ) );

panel.setLayout(new BorderLayout());

panel.add(new MyDraw(), BorderLayout.CENTER);
panel.add(strech_label, BorderLayout.SOUTH);

    frame1.setLayout(new BorderLayout());
    frame1.add(panel,BorderLayout.WEST);

所以基本上JLabel位于南方或北方,它将有力地拉伸MyDraw。