我正处于尝试创建Java2d图形绘制程序的早期阶段。我使用了流布局,并且使用了三个面板。前两行是按钮,组合框等,第三行是一个大的,空白的,白色的面板,将用于绘画。前两个面板显示得很漂亮,但paint面板显示为第二个按钮面板旁边的一个小白框。任何帮助都将不胜感激。
public class DrawingApp extends JFrame
{
private final topButtonPanel topPanel = new topButtonPanel();
private final bottomButtonPanel bottomPanel = new bottomButtonPanel();
private final PaintPanel paintPanel = new PaintPanel();
public DrawingApp()
{
super("Java 2D Drawings");
setLayout(new FlowLayout());
add(topPanel);
add(bottomPanel);
add(paintPanel);
}
public static void main(String[] args)
{
DrawingApp frame = new DrawingApp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(750,500);
frame.setVisible(true);
}
}
public class topButtonPanel extends JPanel
{
private final String[] names = {"Line", "Oval", "Rectangle"};
private final JButton undo = new JButton("Undo");
private final JButton clear = new JButton("Clear");
private final JLabel shape = new JLabel("Shape:");
private final JComboBox<String> shapesComboBox = new JComboBox(names);
private final JCheckBox filled = new JCheckBox("Filled");
public topButtonPanel()
{
super();
setLayout(new FlowLayout());
add(undo);
add(clear);
add(shape);
shapesComboBox.setMaximumRowCount(3);
add(shapesComboBox);
add(filled);
}
}
public class bottomButtonPanel extends JPanel
{
private final JCheckBox useGradient = new JCheckBox("Use Gradient");
private final JButton firstColor = new JButton("1st Color");
private final JButton secondColor = new JButton("2nd Color");
private final JLabel lineWidthLabel = new JLabel("Line Width:");
private final JLabel dashLengthLabel = new JLabel("Dash Length:");
private final JTextField lineWidthField = new JTextField(2);
private final JTextField dashLengthField = new JTextField(2);
private final JCheckBox filled = new JCheckBox("Dashed");
public bottomButtonPanel()
{
super();
setLayout(new FlowLayout());
add(useGradient);
add(firstColor);
add(secondColor);
add(lineWidthLabel);
add(lineWidthField);
add(dashLengthLabel);
add(dashLengthField);
add(filled);
}
}
public class PaintPanel extends JPanel
{
public PaintPanel()
{
super();
setBackground(Color.WHITE);
setSize(700,400);
}
}发布于 2016-03-24 06:39:56
基本上,这是对Swing API工作方式的误解。
Swing (在很大程度上)依赖于布局管理API,该API用于决定组件的大小(以及放置位置)
使用setSize是没有意义的,因为布局管理器会自己决定组件的大小,并相应地进行调整。
您可以向布局管理器建议您希望组件使用getPreferred/Minimum/MaximumSize的大小,例如
public class PaintPanel extends JPanel
{
public PaintPanel()
{
super();
setBackground(Color.WHITE);
}
public Dimension getPreferredSize() {
return new Dimension(700, 400);
}
}请记住,布局管理器完全有权忽略这些值,因此您需要更好地了解这些管理器是如何工作的
有关详细信息,请参阅Laying Out Components Within a Container
https://stackoverflow.com/questions/36189948
复制相似问题