当前位置: 代码迷 >> J2SE >> 求教java中的drawString()步骤
  详细解决方案

求教java中的drawString()步骤

热度:9549   发布时间:2013-02-25 00:00:00.0
求教java中的drawString()方法
这个程序代码为什么只显示窗口,而不显示字符串呢?

import javax.swing.*;
import java.awt.*;
class DrawPanel extends JPanel
{
public void painComponent(Graphics g)
{
g.drawString("Hello,world",75,100);
}
}
class DrawFrame extends JFrame
{
public DrawFrame()
{
setTitle("Hello,world");
setSize(300,200);
DrawPanel panel=new DrawPanel();
add(panel);
}
}
public class Test
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
DrawFrame frame=new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
求教!!!
新手
------最佳解决方案--------------------------------------------------------
painComponent 
=> paintComponent 

在方法前加上 @Override 可以避免这类错误。
------其他解决方案--------------------------------------------------------
import javax.swing.*;
import java.awt.*;
class DrawPanel extends JPanel
{
         public void painComponent(Graphics g)
         {
                g.drawString("Hello,world",75,100);
         }
}
class DrawFrame extends JFrame
{
        public DrawFrame()
        {
                setTitle("Hello,world");
                setSize(300,200);
                DrawPanel panel=new DrawPanel();
                add(panel);
         }
}
public class Test
{
        public static void main(String[] args)
        {
                EventQueue.invokeLater(new Runnable()
                {
                        public void run()
                        {
                                DrawFrame frame=new DrawFrame();
                                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                frame.setVisible(true);
                         }
  相关解决方案