我有一个扩展 JFrame
的 Main
类,以及一个扩展 JPanel
的 DrawingPanel
类。
DrawingPanel
在其 paintComponent()
方法中填充一个正方形。 Main
是一个简单的 JFrame
。
Main
将 DrawingPanel
的实例添加到 JFrame
。
问题是:
如果我没有为 Main
设置布局,DrawingPanel
中的正方形将正确显示。
如果我确实为 Main
设置了布局,假设使用 FlowLayout()
,则正方形不会显示,但我知道 paintComponent()
DrawingPanel
中的方法确实运行,因为我从该方法内部将一些内容打印到控制台进行检查。此外,面板的黑色边框也会出现。
代码:
绘图面板类:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DrawingPanel extends JPanel {
Rectangle rect = new Rectangle(50,50,50,50);
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fill(rect);
}
}
主类:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Main extends JFrame {
JPanel panel;
public Main(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());//If I delete this line, the square gets
//displayed correctly. Otherwise, the panel
//and it's black border are displayed without
//a black square inside of them.
panel = new DrawingPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(panel);
}
public static void main(String[] args) {
Main m = new Main();
}
}
感谢您的帮助:)
最佳答案
If I don't set a layout for Main, square displays correctly. If I do set a layout for Main, suppose FlowLayout(), the square doesn't get displayed.
- 始终使用 LayoutManager:当您使用
FlowLayout
时 - 将组件的首选大小设置为
FlowLayout
遵循要添加到容器中的组件的首选大小。扩展组件并覆盖getPreferredSize(Dimenstion)
更适合提供大小提示,因为它允许根据其内容调整组件的大小。 - 不要使用 JFrame 的
setSize(Dimension)
。而是调用pack()
当您添加完用例中的所有组件后。 pack 方法调整框架大小,以便其所有内容都等于或大于其首选大小。 -
setVisible(true)
在添加所有组件之后以及调用pack()
之后应该调用onframe上JFrame
. - 并且不要忘记将 GUI 渲染任务放在 EDT 中。甚至是
JFrame.setVisible(true)
应在 EDT 内执行。利用SwingUtilities.invokeLater(Runnable)
对于本例。 - 正如 @camickr 所建议的,不要忘记查看 Performing Custom Painting Steps查看上述所有建议的实际效果。
查看官方教程页面:
关于java - 带有绘制正方形的 JPanel 无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20787540/