Reputation: 17
I'm trying to create a method that, when called, creates a JFrame. Within the same class that creates said JFrame, I have another method called line. This method, when called, is supposed to draw a line on the JFrame based on the entered coordinates. The JFrame loads correctly, but the line method doesn't work. i.e. nothing shows up on the JFrame even when the line method has valid coordinates.
import java.awt.*;
import javax.swing.JFrame;
public class Window{
JFrame f = new JFrame("Pathway");
public Window(int width, int height){
f.setSize(width,height);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void line(int x1,int y1,int x2,int y2){
Graphics g = f.getGraphics();
g.setColor(Color.BLACK);
g.drawLine(x1,y1,x2,y2);
}
}
As I'm still a beginner, I have no idea what is going on. Any help would be greatly appreciated. Thanks!
Upvotes: 0
Views: 74
Reputation: 324118
Don't use getGraphics(). That is not how you do custom painting.
Custom painting is done by overriding the paintComponent()
method of a JPanel
and you add the panel to the frame.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.
Start with the working example from the tutorial and then customize it.
Upvotes: 1