称为面板的 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);
}
}
JPanel
的默认首选大小为 0x0
。 FlowLayout
根据组件的首选大小对组件进行布局,因此组件现在具有首选大小 1x1
(线条边框增加了一点权重)。
您可以尝试添加另一个组件来panel
...
panel.add(new JLabel("This is some text"));
或者覆盖panel
getPreferredSize
方法...
panel = new JPanel() {
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
试试这个:
文件绘制.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);
}
}
文件测试.java(启动窗口的主要方法):Package 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();
}
});
}
}