首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Graphics2d制作盒子

Graphics2d制作盒子
EN

Stack Overflow用户
提问于 2020-10-21 12:45:13
回答 1查看 35关注 0票数 0

我是个java新手,我想做一个在屏幕上画一个方框的程序,除了paintComponent()没有用之外,其他的都是正确的。

代码语言:javascript
复制
import java.awt.*; 
import javax.swing.*;
import java.awt.Graphics2D.*;
public class Frame extends JPanel
{
    @Override //this section creates the box
    public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
     super.paintComponent(g);
     
     Graphics2D g2d = (Graphics2D) g;
     
     g2d.drawRect(150,150,20,20);
    
    }
    public static void createWindow() //this section creates the frame
    {
        JFrame frame = new JFrame("Simple GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //set closing bebavior
        frame.setSize(400, 400);                                 //set the size of jframe
        frame.setLocationRelativeTo(null);                       //center the jframe 
        frame.setVisible(true);                                  //show the frame
    }
    //main method  
    public static void main(String[] args) 
    {
        createWindow();//launch your creaWindow method  
        paintComponent();
    }
}       
EN

回答 1

Stack Overflow用户

发布于 2020-10-21 12:58:07

您必须复习Java的基础知识。您的错误在于,您必须创建此类框架的对象,并将其添加到已创建的JFrame中。下面是正确的代码@Hh000。

代码语言:javascript
复制
import java.awt.*; 
import javax.swing.*;
import java.awt.Graphics2D.*;
public class Frame extends JPanel{

    @Override //this section creates the box
    public void paintComponent(Graphics g){
     super.paintComponent(g);
     g.setColor(Color.BLACK);
     g.drawRect(150,150,20,20);
    }
    
    //main method  
    public static void main(String[] args){ 
        JFrame frame = new JFrame("Simple GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //set closing bebavior
        Frame frameObject = new Frame();                       //Making a class object
        frame.add(frameObject);                                //Adding the object into the JFrame
        frame.setSize(400, 400);                               //set the size of jframe
        frame.setLocationRelativeTo(null);                     //center the jframe 
        frame.setVisible(true);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64456831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档