java paintcomponent(),Java中的paintComponent()未被调用

I am trying to draw a simple rectangle but I think the paintComponent method is not getting called.

Here is the code for the class with main method:

package painting;

import java.awt.*;

import javax.swing.*;

public class Painting {

public static void main(String[] args) {

JFrame jf;

jf = new JFrame("JUST DRAW A RECTANGLE");

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jf.setLayout(null);

jf.setLocationRelativeTo(null);

jf.setSize(600,600);

jf.setVisible(true);

Mainting maint = new Mainting();

jf.add(maint);

}

}

and the class with paintComponent()

package painting;

import java.awt.*;

import javax.swing.*;

public class Mainting extends JPanel {

@Override

public void paintComponent(Graphics g)

{

super.paintComponent(g);

g.drawRect(0, 0 , 200, 200);

System.out.println("haha");

g.setColor(Color.red);

}

}

What is the problem here, I cannot figure out...

解决方案

While the answers already provided might have resulted in the rectangle appearing, the approach was less than optimal. This example aims to show a better approach. Read the comments in the code for details.

Note that Swing/AWT GUIs should be started on the EDT. This is left as an exercise for the reader.

import java.awt.*;

import javax.swing.*;

public class Painting {

public static void main(String[] args) {

JFrame jf = new JFrame("JUST DRAW A RECTANGLE");

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// null layouts cause more problems than they solve. DO NOT USE!

//jf.setLayout(null);

jf.setLocationRelativeTo(null);

/* if components return a sensible preferred size,

it's better to add them, then pack */

//jf.setSize(600, 600);

//jf.setVisible(true); // as mentioned, this should be last

Mainting maint = new Mainting();

jf.add(maint);

jf.pack(); // makes the GUI the size it NEEDS to be

jf.setVisible(true);

}

}

class Mainting extends JPanel {

@Override

public void paintComponent(Graphics g) {

super.paintComponent(g);

g.setColor(Color.RED);

g.drawRect(10, 10, 200, 200);

System.out.println("paintComponent called");

/* This does nothing useful, since nothing is painted

before the Graphics instance goes out of scope! */

//g.setColor(Color.red);

}

@Override

public Dimension getPreferredSize() {

// Provide hints to the layout manager!

return new Dimension(220, 220);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值