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);
}
}
答案 0 :(得分:5)
JPanel
的默认首选尺寸为0x0
。 FlowLayout
根据首选大小布置组件,因此组件现在的首选大小为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();
}
});
}
}