Drawing graphics in java - NetBeans IDE
I created a new JApplet form in NetBeans:
public clas开发者_运维问答s UI extends javax.swing.JApplet {
//generated code...
}
And a JPanel in design mode named panou
:
// Variables declaration - do not modify
private javax.swing.JPanel panou;
How do I get to draw a line on panou
? I've been searching for this for 5 hours now so a code snippet and where to place it would be great. Using Graphics2D preferably.
- Go to design mode
- Right Click on the panel "panou"
- Click "Costumize code"
- In the dialog select in the first combobox "costum creation"
- add after
= new javax.swing.JPanel()
this, so you see this:
panou = new javax.swing.JPanel(){
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g); // Do the original draw
g.drawLine(10, 10, 60, 60); // Write here your coordinates
}
};
Make sure you import java.awt.Graphics
.
The line that you will see is always one pixel thick. You can make it more "line" by doing the following:
Create this method:
public static final void setAntiAliasing(Graphics g, boolean yesno)
{
Object obj = yesno ? RenderingHints.VALUE_ANTIALIAS_ON
: RenderingHints.VALUE_ANTIALIAS_OFF;
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, obj);
}
And add after super.paintComponent(g);
(in your costum creation) this:
setAntiAlias(g, true);
Edit:
What you are doing wrong is: you paint the line once (by creating the frame).
When you paint the line the frame is also invisible. The first draw is happening when the frame becomes visible. The frame will be Repainted, so everything from the previous paint will disappear.
Always you resize the frame, everything will be repainted. So you have to make sure each time the panel is painted, the line also is painted.
To do custom painting in a JPanel
, one would need to make a subclass of a JPanel
, and then overload the paintComponent
method:
class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
// Perform custom painting here.
}
}
In the example above, the MyPanel
class is a subclass of JPanel
, which will perform whatever custom painting is written in the paintComponent
method.
For more information on how to do custom painting in Swing components, Lesson: Performing Custom Painting from The Java Tutorials have some examples.
If one wants to do painting with Java2D (i.e. using Graphics2D
) then one could do some painting on a BufferedImage
first, then draw the contents of the BufferedImage
onto the JPanel
:
class MyPanel extends JPanel {
BufferedImage image;
public MyPanel() {
Graphics2D g = image.createGraphics();
// Do Java2D painting onto the BufferedImage.
}
public void paintComponent(Graphics g) {
// Draw the contents of the BufferedImage onto the panel.
g.drawImage(image, 0, 0, null);
}
}
Further reading:
- Painting in AWT and Swing
- Trail: 2D Graphics
精彩评论