任何人都可以帮助我并告诉我为什么矩形不会出现?框架运行良好,但没有形状出现。我尝试过几种不同的方式,包括两个单独的类,但我得到的只是一个空框架。
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();
}
}
答案 0 :(得分:2)
如果要覆盖方法,请正确注释:
@Override
public void paintComponent(Graphics2D g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(100, 100, 30, 40);
}
然后您的IDE会告诉您,您 正确覆盖paintComponent
方法,因为参数类型Graphics2D
错误。
这是JComponent
中original/parent method的签名:
protected void paintComponent(Graphics g)
正如您所看到的,它使用Graphics
代替Graphics2D
。您目前overloading paintCompoent
而不是overriding。因此,请将参数类型更改为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