简体   繁体   中英

How to make a graphic line into JFrame?

I use Eclipse, and I want make a graphic line into JFrame by following code:

public void Makeline () {
    Graphics g=new Graphics(); // has error
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(new Line2D.Double(0, 0, 20, 20));
}

but give followin error:

Cannot instantiate the type Graphics

The solution is to overwrite the paintComponent method, but the JFrame isn't a JComponent, so instead of JFrame, use JPanel and then add the JPanel to the JFrame.

paintComponent(Graphics g) {
    super.paintComponent(g)

    //here goes your code
    Graphics2D g2 = (Graphics2D) g;
    ...
}

Graphics is an abstract class, defining the requirements of the overall API.

Painting in Swing is done within the context of the paint chain. This is typically performed within the paintComponent method of components that extend from JComponent

Take a look at Perfoming Custom Painting for more details

You can also use a BufferdImage to generate a Graphics context, but you still need somewhere to draw the image, so it comes down what your are trying to achieve.

Graphics is an abstract class. You can't instantiate following way.

 Graphics g=new Graphics(); 

To access Graphics2D , first you need to override paint(Graphics) method.

@Override
public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM