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