天天看點

java jpanel 繪圖,Java JPanel繪圖形狀

java jpanel 繪圖,Java JPanel繪圖形狀

I am for the first time working with JPanel and drawing basic shapes on the JPanel.

I have written code for the shape like this:

public class Shape extends JPanel{

int x,y;

public Shape(int x, int y){

this.x = x;

this.y = y;

}

public void paint(Graphics g){

super.paint(g);

g.setColor(Color.black);

g.drawRect(x, y, 20, 20);

}

}

I have another class where I will be using this shape. It extends JFrame and implements MouseListener. On this JFrame I have put the JPanel it is called simply "panel".

I have the method, which reads the mouse position, and draws the shape on the "panel".

public void mouseClicked(MouseEvent e){

Shape shape = new Shape(e.getX(),e.getY());

panel.add(shape);

panel.revalidate();

panel.repaint();

}

The problem is that it doesn't draw the shape on the coordinate where my mouse is. It just draws on panel at the upper-side and draws, them in a line.

Thank you for you answers.

解決方案

public class ShapesPanel extends JPanel {

private java.util.List shapesList ;

public ShapesPanel() {

shapesList = new java.util.ArrayList() ;

this.addMouseListener(new MouseClickListener()) ;

}

private Shape createShape( Rectangle bounds ) {

Shape shape = new Ellipse2D.Double(bounds.x, bounds.y, bounds.width, bounds.height );

return shape ;

}

private class MouseClickListener extends MouseAdapter {

@Override

public void mouseClicked(MouseEvent e) {

Point pt = e.getPoint();

Dimension size = new Dimension(100, 100 );

Rectangle bounds = new Rectangle(pt.x, pt.y, size.width, size.height );

Shape shape = createShape(bounds);

shapesList.add( shape );

repaint();

}

}

protected void paintComponent(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

Rectangle bounds = new Rectangle(0,0,getWidth(), getHeight() );

g2.setPaint( Color.white );

g2.fill( bounds );

for (Iterator iterator = shapesList.iterator(); iterator.hasNext(); ) {

Shape shape = (Shape) iterator.next();

g2.setPaint( Color.cyan );

g2.fill( shape );

g2.setPaint( Color.black );

g2.draw( shape );

}

}

public static void main(String[] args) {

JFrame frame = new JFrame("Draw Shapes") ;

frame.getContentPane().add( new ShapesPanel() );

frame.setSize(600, 600);

frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);

frame.setVisible( true );

}

}

Hope this helps to draw java shapes in a panel.