문제

I've been trying to get the Graphics2d object to work without success. I've searched for an answer on both the Oracle tutorial site and Stackoverflow without finding an answer.

The problem I have is that when I call the methods lineTo, fill, and drawRect, I get a blank grey square in my window, instead of the shapes that I want.

package main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class GraphicsTesting extends JPanel {

private static final long serialVersionUID = 6096199371167913312L;

static BufferedImage buffImag = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);

static Graphics2D graff = buffImag.createGraphics();

Point2D.Double point = new Point2D.Double(10, 10);

static Graphics gra = buffImag.createGraphics();

public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    GeneralPath gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 4);

    gp.moveTo(30, 55);
    gp.lineTo(168, 384);
    gp.lineTo(462, 81);
    gp.lineTo(321, 423);
    gp.lineTo(269, 243);

    g2.setColor(new Color(112, 150, 134));

    g2.fill(gp);

    g2.setColor(new Color(56, 112, 232));

    g2.draw(gp);

    g2.setColor(new Color(152, 1, 210));

    g2.drawRect(25, 152, 380, 405);
    g2.drawImage(buffImag, 0, 0, 500, 0, 0, 500, 500, 500, null);
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,500);
    frame.setVisible(true);
    GraphicsTesting gT = new GraphicsTesting();

    frame.setContentPane(gT);
    gT.paint(gra);
}

}

도움이 되었습니까?

해결책 2

There are several issues with your code, but the main one causing your problem is that you are making the frame visible before adding the panel to it.

Move your setVisible(true) line to here:

frame.setContentPane(gT);
frame.setVisible(true);
gT.paint(gra);

다른 팁

Your code seems fine and I tried to run it on my machine. It produces what you can see on the following screen shot. I think this is what you expect to get, right? Your problem might be coming from a faulty Java installation or an os-related issue. Which virtual machine are you using and on which operating system?

As a side note, your code is not complete though, as the following import is missing

import java.awt.geom.Point2D;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top