2016-08-28 191 views
0

我似乎無法得到一個矩形顯示在JFrame中。根據這個項目的參數,我必須讓這個類實現Icon接口。當我按原樣運行代碼時,我得到了JFrame,但沒有任何內容顯示。它應該顯示一個黑色的方塊。我假設這個問題與我如何初始化圖形實例變量有關。我沒有很多使用GUI圖形的經驗,所以我不完全清楚如何正確執行此操作。JFrame沒有顯示任何東西

是的,我知道getIconWidth和getIconHeight方法是多餘的,因爲我使用的是常量,但我必須具有這些方法才能實現接口。

public class MugDisplay extends JFrame implements Icon { 
private int width; 
private int height; 
private JPanel panel; 
private Graphics graphics; 

private static final int ICON_WIDTH = 100; 
private static final int ICON_HEIGHT = 100; 


public MugDisplay() { 
    this.configureGui(); 
    this.panel = new JPanel(); 
    this.panel.setLayout(new BorderLayout()); 
    this.add(this.panel, BorderLayout.CENTER); 
    this.graphics = this.getGraphics(); 
    int xPos = (this.panel.getWidth() - this.getIconWidth())/2; 
    int yPos = (this.panel.getHeight() - this.getIconHeight())/2; 
    this.paintIcon(this.panel, this.graphics, xPos, yPos); 
} 


@Override 
public void paintIcon(Component c, Graphics g, int x, int y) { 
    Graphics2D g2 = (Graphics2D) g; 
    g2.setColor(Color.BLACK); 
    g2.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT); 
} 


@Override 
public int getIconWidth() { 
    return ICON_WIDTH; 
} 


@Override 
public int getIconHeight() { 
    return ICON_HEIGHT; 
} 

private void configureGui() { 
    this.setPreferredSize(new Dimension(600, 600)); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.getContentPane().setLayout(new BorderLayout()); 
    this.pack(); 
    this.setVisible(true); 
} 

} 

爲了擁有MCVE,下面是調用此類的驅動程序類。

public class Main { 

public static void main(String[] args) { 
    MugDisplay md = new MugDisplay(); 
    md.setVisible(true); 
} 

} 
+0

請勿使用'this.getGraphics();'來獲取圖形,並且不要在構造函數中調用'paintIcon'。重寫框架的'paint'方法,調用'super.paint(g)',計算x&y並在那裏調用'paintIcon'(解析paint方法的圖形實例)。您可能還想考慮切換到'JPanel'並重寫'paintComponent',因爲我不明白在這種情況下重寫幀的'paint'的好處是什麼。 –

回答

3

this.graphics = this.getGraphics()是畫在Swing不是如何自定義工作。你應該做的是創建一個面板,重寫它的paintComponent方法,打電話給super,然後然後做你的畫。例如:

panel = new JPanel() { 
    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     int xPos = ... 
     paintIcon(this, g, xPos, yPos); 
    } 
} 

調用getGraphics將爲您提供一個短暫的Graphics對象,可以很快就會失效,這就是爲什麼你應該選擇覆蓋paintComponent代替,這將永遠給你一個可用的Graphics對象。見Performing Custom Painting

在另外一個註釋中,看起來您在完成向JFrame添加必要組件之前調用了setVisible(true)。爲確保您的組件顯示出來,請在將所有組件全部添加到框架中後致電setVisible(true)

+0

謝謝。這解決了我的問題。我甚至不知道你可以用這種語法來聲明一個面板。 – matt