代码:

import java.awt.BorderLayout;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class PaintWindow {

private JFrame frame;
private aJPanel panel;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                PaintWindow window = new PaintWindow();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public PaintWindow() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new aJPanel();
    frame.getContentPane().add(panel, BorderLayout.CENTER);

    JButton btnNewButton = new JButton("New button");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            panel.stam();
        }
    });
    frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);

    frame.setBounds(100, 100, 450, 300);
    frame.setVisible(true);
}

public class aJPanel extends JPanel {
    private static final long serialVersionUID = 8874943072526915834L;
    private Graphics g;

    public aJPanel() {
        super();
        System.out.println("Constructor");
    }

    public void paint(Graphics g) {
        super.paint(g);
        System.out.println("paint");
        g.fillRect(10, 10, 10, 10);
        this.g = g;

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("paintComponent");
        g.fillRect(20, 20, 20, 20);
        this.g = g;
    }

    public void stam() {
        System.out.println("stam");
        this.g.fillRect(40, 40, 40, 40);
        this.repaint();
    }
}
}


我想要做的是在用户单击按钮或触发鼠标事件后绘制自定义形状(线条,矩形等)。但是调用aJPanel.stam()并不会显示该矩形。我对JPanel相当陌生。有什么建议么?

最佳答案

首先:


班级名称应以大写字母开头
类名应具有描述性。


“ aJPanel”不符合以上任何一个条件。


  但是调用aJPanel.stam()不会显示该矩形


有关动态绘画的两种常见方法,请参见Custom Painting Apporoaches


将对象添加到列表并迭代列表以绘制所有对象
直接绘制到BufferedImage,然后绘制BufferedImage


这些示例通过拖动鼠标来添加矩形,但是单击按钮时只需调用addRectangle(...)方法就可以轻松添加矩形。

09-28 12:09