[英]Shapes not drawing in Java
誰能幫助我,告訴我為什么矩形不會出現? 框架運行良好,但未顯示任何形狀。 我嘗試了幾種不同的方法,包括使用兩個單獨的類,但是我得到的只是一個空框架。
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Surface extends JPanel
{
public void paintComponent(Graphics2D g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(100, 100, 30, 40);
}
public static void main(String[] args)
{
Surface s = new Surface();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(600, 400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(s);
s.repaint();
}
}
如果要覆蓋方法,請正確注釋它:
@Override
public void paintComponent(Graphics2D g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(100, 100, 30, 40);
}
那么您的IDE應該告訴您,由於參數類型Graphics2D
錯誤,因此您沒有正確覆蓋paintComponent
方法。
這是JComponent
原始/父方法的簽名:
protected void paintComponent(Graphics g)
如您所見,它使用Graphics
而不是Graphics2D
。 您當前正在重載 paintCompoent
而不是覆蓋它。 因此,將您的參數類型更改為Graphics
(並導入java.awt.Graphics
),它將起作用:
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(100, 100, 30, 40);
}
順便說一句,您要先設置jf
的可見性,然后再向其內容窗格中添加一些內容。 在某些情況下,這可能會引起麻煩,並且在重新繪制框架之前(或執行其他操作導致框架重新繪制自身,例如調用pack()
),添加的組件才可見。 因此,最好在main
方法中切換這些方法調用的順序:
Surface s = new Surface();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(600, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(s);
//s.repaint(); // not needed anymore, because "jf" will repaint everything during the 'setVisible' call
jf.setVisible(true); // should almost always be the last thing you do
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.