如何在JPanel中绘制?(Swing/graphics Java)
2022-08-31 21:02:48
我正在做一个项目,我试图制作一个油漆程序。到目前为止,我已经使用 Netbeans 创建了一个 GUI 并设置了程序。
截至目前,我能够调用所有必要的协调来绘制它,但我对如何在内部实际绘画感到非常困惑。
在我的代码末尾,我试图在面板内部绘制失败。
任何人都可以解释/展示如何在这样的示例中使用图形吗?
我发现的所有示例都创建了一个类并对其进行扩展,但我不知道我是否可以做到这一点,因为它是在netbeans中生成的。JPanel
我需要在JPanel
中绘制,在我的JFrame
中。我不知道在哪里放置图形类。
JavaPaintUI 类
package javapaint;
import java.awt.*;
import javax.swing.*;
public class JavaPaintUI extends javax.swing.JFrame {
public JavaPaintUI() {
initComponents();
}
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jPanel2MousePressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
jPanel2MouseReleased(evt);
}
});
jPanel2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
jPanel2MouseDragged(evt);
}
});
pack();
}// </editor-fold>
int currentX, currentY, oldX, oldY;
private void jPanel2MouseDragged(java.awt.event.MouseEvent evt) {
if (tool == 1) {
currentX = evt.getX();
currentY = evt.getY();
oldX = currentX;
oldY = currentY;
System.out.println(currentX + " " + currentY);
System.out.println("PEN!!!!");
}
}
private void jPanel2MousePressed(java.awt.event.MouseEvent evt) {
oldX = evt.getX();
oldY = evt.getY();
System.out.println(oldX + " " + oldY);
}
//mouse released//
private void jPanel2MouseReleased(java.awt.event.MouseEvent evt) {
if (tool == 2) {
currentX = evt.getX();
currentY = evt.getY();
System.out.println("line!!!! from" + oldX + "to" + currentX);
}
}
//set ui visible//
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JavaPaintUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel2;
// End of variables declaration
class jPanel2 extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("BLAH", 20, 20);
g.drawRect(200, 200, 200, 200);
}
}
}
屏幕截图
整个事情是一个,中间的白色部分是我想画的。JFrame
jPanel2