[英]JPanel with a painted square doesn't display correctly
我有擴展JFrame
類Main
,以及擴展JPanel
類DrawingPanel
。 DrawingPanel
在其paintComponent()
方法中填充一個正方形。 Main
是一個簡單的JFrame
。
Main
將一個DrawingPanel
實例添加到JFrame
。
問題是:
如果我沒有為Main
設置布局,則DrawingPanel
的方塊會正確顯示。 如果我為Main
設置布局,假設FlowLayout()
,則不會顯示正方形,但我知道DrawingPanel
中的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();
}
}
謝謝你的幫助 :)
如果我沒有為Main設置布局,則正確顯示正方形。 如果我為Main設置布局,假設FlowLayout(),則不顯示正方形。
FlowLayout
FlowLayout
遵循要添加到Container的組件的首選大小。 擴展組件並覆蓋getPreferredSize(Dimenstion)
對於提供大小提示更為可取,因為它允許根據組件的內容調整組件大小。 setSize(Dimension)
。 而是在完成從用例中添加所有組件后調用pack()
。 包裝方法調整框架的大小,使其所有內容都達到或超過其首選尺寸。 JFrame
上調用pack()
之后調用框架上的setVisible(true)
。 JFrame.setVisible(true)
應該在EDT中執行。 在這種情況下使用SwingUtilities.invokeLater(Runnable)
。 查看官方教程頁面 :
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.