[英]JButtons in JPanel don't display properly until repainted through resize or action
我已經有這個問題了一段時間,搜索了很多論壇和網站(包括這個),仍然沒有找到我的問題的答案。
這是我的問題:我正在構建一個可視日歷。 我有一個父面板,里面有多個面板。 我重新繪制父面板,並使3覆蓋不透明(假)。 直到我調整框架的大小 (或使用覆蓋3中的一個的按鈕,但是在本示例中省略了這些按鈕,因為它使代碼更長) ,父面板的顏色不會顯示
無論如何,這里是代碼,我把它簡化為問題部分:
public class Calendar extends JPanel{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(1600,150);
frame.add(new Calendar());
frame.setVisible(true);
}
public Calendar(){
setLayout(new GridBagLayout());
GridBagConstraints cc = new GridBagConstraints();
cc.weightx = 1;
cc.weighty = 1;
cc.gridx = 0;
cc.fill = GridBagConstraints.BOTH;
//Initiate Panels
JPanel yearpanel = new JPanel();
JPanel monthpanel = new JPanel();
JPanel daypanel = new JPanel();
yearpanel.setLayout(new GridBagLayout());
monthpanel.setLayout(new GridBagLayout());
daypanel.setLayout(new GridBagLayout());
// Set sizes
int width = (int) this.getPreferredSize().getWidth();
int height = (int) (this.getPreferredSize().getHeight() / 3);
yearpanel.setSize(width,height);
daypanel.setSize(width,height);
monthpanel.setSize(width,height);
//make transparent
yearpanel.setOpaque(false);
monthpanel.setOpaque(false);
daypanel.setOpaque(false);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Image image = Toolkit.getDefaultToolkit().getImage("Images/CalendarBackground.jpg");
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
我不知道它為什么這樣做+我無法在網上找到答案,只有那些有同樣問題的人被遺棄的問題:/
誰能幫我?
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Image image = Toolkit.getDefaultToolkit().getImage("Images/CalendarBackground.jpg");
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
}
image
。 相反,它應該聲明為類屬性並預加載。 Toolkit
方法是異步的,因此將組件用作ImageObserver
更為重要。
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
這是一個有效的SSCCE ,就像你似乎正在嘗試的那樣。
檢查Graphics.drawImage()
的返回值。 我打賭它會返回false,這意味着你正在繪制的圖像還沒有完全加載和縮放。 嘗試將圖像加載到paintComponent
方法以外的其他位置,就像Calendar
構造函數一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.