gpt4 book ai didi

java - JPanel 不显示在 BorderLayout 中

转载 作者:行者123 更新时间:2023-11-29 03:53:17 25 4
gpt4 key购买 nike

我有一个边框布局,右边有一个 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);

最佳答案

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

关于java - JPanel 不显示在 BorderLayout 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7746754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com