简体   繁体   中英

How to increase line width (Java Applet)

I've been trying to increase the width of line using the setStroke method in Java but the only output I seem to be getting is an error message saying "Cannot find method setStroke".

public void paint(Graphics g){
    g.setColor(Color.orange);
    g.setStroke(new BasicStroke(4));
    g.drawLine(5, 5, 480, 5);
 }

I've imported

import java.applet.Applet;
import java.awt.*;          
import java.awt.event.*;    
import javax.swing.*;
import java.awt.Graphics2D;

Try with Graphics2D#setStroke()

Simply downcast it to Graphics2D and use it.

For example

Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(4));

NOTE: Never forget to call super.paint(g) in overridden method.

You need to change what type you're inputting into your method.

public void paint(Graphics2D g){
    g.setColor(Color.orange);
    g.setStroke(new BasicStroke(4));
    g.drawLine(5, 5, 480, 5);
 }

as Graphics2D instead of Graphics .

EDIT:

This will also work (casting it):

public void paint(Graphics2D g){
    Graphics2D twoD = (Graphics2D) g;
    twoD.setColor(Color.orange);
    twoD.setStroke(new BasicStroke(4));
    twoD.drawLine(5, 5, 480, 5);
 }

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