问题
I've been battling a bit (or a lot) with Java's Graphics, I've been going through the documentation and tutorials for drawing Java Graphics.
Every example I've found seems to have a main class that extends a JPanel and then calls itself which executes the paint function somehow.
Is it possible to draw graphics without using extends at all? I have a basic program
import javax.swing.*;
import awt.Graphics;
public class basicWindow {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Basic Window");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
frame.setVisible(true);
}
public void paint(Graphics g) {
g.fillRect(5, 15, 50, 75);
}
}
This opens a window but doesn't draw anything which I was I expect because I don't know how to execute the paint function.
If I try
Graphics graphic = new Graphics();
paint(graphic);
It doesn't work because it's complaining about the class being abstract.
回答1:
Is it possible to draw graphics without using extends at all?
Yes, it sure is possible. As mentioned by @HovercraftFullOfEels in a comment:
You can draw on a
BufferedImage
..
If you display that image in a JLabel
(lets call it label
) then to get the screen to update after the image has changed, simply call:
label.repaint();
回答2:
You will want to read the tutorials and follow them. Java Swing uses passive graphics, and your code needs to respect this.
- As per the tutorials, have your drawing class extend JPanel.
- Draw within the paintComponent method override
- Don't forget the
@Override
annotation.
Regarding,
Is it possible to draw graphics without using extends at all?
- You can draw on a BufferedImage and display that within the paintComponent method. This still requires that you extend the component.
- You can draw with a Graphics object obtained by calling
getGraphics()
on a component, however if you do this, the image will not be stable, and you risk throwing a NPE, and so this is not recommended.
来源:https://stackoverflow.com/questions/35484267/java-graphics-not-executing-paint-function-without-extends