2016-01-28 5 views
0

Мне поручено рисовать массивList форм в java.Как рисовать фигуры из массиваList в JPanel?

Я чувствую, у меня есть большая часть этого прямо, однако

Последний метод в ShapeChooserPanel я не могу узнать, как напечатать Shapes в массиве, он должен нарисовать текущую форму на месте мыши была нажата.

Мой код ниже

Основной класс:

import javax.swing.JFrame; 

public class Lab2 { 

    public static void main (String[] args) { 


     JFrame myFrame = new JFrame("Lab 2"); 

     myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     myFrame.add(new ShapeChooserPanel()); 
     myFrame.pack(); 
     myFrame.setVisible(true); 


    } 
} 

ShapeChooserPanel

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.util.ArrayList; 

public class ShapeChooserPanel extends JPanel { 

private int currentX; 
private int currentY; 
private Color currentColor; 
private int currentShape; 
private JButton clearBtn; 
private JRadioButton circle, square, triangle, box; 
private DrawingPanel drawingPanel; 
private JPanel controlsPanel; 
//constants representing shape choice 
private final int CIRCLE = 0; 
private final int SQUARE = 1; 
private final int TRIANGLE = 2; 
private final int BOX = 3; 
//constant delta used for setting distance between points 
private final int DELTA = 25; 
private int[] Xs; 
private int[] Ys; 
//store all the shapes to be painted UNCOMMENT when you have Shape.java defined 
ArrayList<Shape> shapes; 

public ShapeChooserPanel(){ 
    //provide some default values paints a circle at (10,10) in blue 
    currentX = 10; 
    currentY = 10; 
    Xs = new int[4];//we will use all 4 points for the square, but only the first 3 for the triangle 
    Ys = new int[4]; 
    setPoints(currentX,currentY); 
    currentShape = CIRCLE; 
    currentColor = Color.red; 
    shapes = new ArrayList<Shape>(); 
    //instantiate the controls panel and set its layout to display everything in a single column 
    controlsPanel = new JPanel(); 
    controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.Y_AXIS)); 


    //TODO: add clear button * 
    // TODO: define radio buttons * 

    clearBtn = new JButton("Clear"); 
    clearBtn.addActionListener(new ClearListener()); 

    circle = new JRadioButton("Red Circle"); 
    circle.addActionListener(new ShapeListener()); 

    square = new JRadioButton("Cyan Square"); 
    square.addActionListener(new ShapeListener()); 

    triangle = new JRadioButton("Green Triangle"); 
    triangle.addActionListener(new ShapeListener()); 

    box = new JRadioButton("Blue Box"); 
    box.addActionListener(new ShapeListener()); 

    ButtonGroup group = new ButtonGroup(); 
    group.add(clearBtn); 
    group.add(circle); 
    group.add(square); 
    group.add(triangle); 
    group.add(box); 

    controlsPanel.add(clearBtn); 
    controlsPanel.add(circle); 
    controlsPanel.add(square); 
    controlsPanel.add(triangle); 
    controlsPanel.add(box); 



    //TODO: add radio buttons to group * 
    //TODO add listeners to radio buttons * 
    //TODO: add radio buttons to controls panel * 

    drawingPanel = new DrawingPanel(); 

    drawingPanel.setBorder(BorderFactory.createLineBorder(Color.black)); 
    //TODO: set a border around the drawing panel * 
    drawingPanel.setPreferredSize(new Dimension(200,200)); 
    drawingPanel.addMouseListener(new PanelListener()); 

    add(drawingPanel); 
    add(controlsPanel); 
    setPreferredSize(new Dimension (300,400)); 
}//end constructor 

public void setPoints(int x, int y) { 
    //TODO: set Xs and Ys * 

    for(int i = 0; i < 4; i++) { 
     Xs[i] = x; 
     Ys[i] = y; 
    } 

} 

private class ClearListener implements ActionListener{ 
    public void actionPerformed(ActionEvent ae){ 
     shapes.removeAll(shapes); 
     drawingPanel.repaint(); 
    } 
} 
private class PanelListener implements MouseListener { 
    public void mouseClicked(MouseEvent me) { 

     currentX = me.getX(); 
     currentY = me.getY(); 
     //TODO: find coordinates of this mouse click * 

     //TODO: add a new shape to the shapes list* 

     shapes.add(new Shape(currentX, currentY, SQUARE,Color.cyan)); 

     setPoints(currentX, currentY); 
     //TODO: call setPoints with current x and y values * 
     drawingPanel.repaint(); 
    } 
    public void mouseExited(MouseEvent me){} 
    public void mouseEntered(MouseEvent me){} 
    public void mouseReleased(MouseEvent me){} 
    public void mousePressed(MouseEvent me){} 
} 
//Class to listen for radio button changes 
private class ShapeListener implements ActionListener{ 
    public void actionPerformed(ActionEvent me){ 
     //TODO: determine which radio button was clicked * 

     if(me.getActionCommand().equals("Red Circle")){ 
      shapes.add(new Shape(currentX, currentY, CIRCLE, Color.red)); 

      } 

      if (me.getActionCommand().equals("Cyan Square")){ 
       shapes.add(new Shape(currentX, currentY, SQUARE, Color.cyan)); 
      } 

      if(me.getActionCommand().equals("Green Triangle")){ 
       shapes.add(new Shape(currentX, currentY, TRIANGLE, Color.green)); 

      } 

      if(me.getActionCommand().equals("Blue Box")){ 
       shapes.add(new Shape(currentX, currentY, BOX, Color.blue)); 

      } 


     //TODO: set current shape and color * 
     drawingPanel.repaint(); 
    } 
} 

private class DrawingPanel extends JPanel { 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     //TODO: paint all the shapes in our list 
    } 
} 
} 

И Shape.java

import java.awt.Color; 
import java.awt.Graphics; 

public class Shape { 

    private int x,y; 
    private int type; 
    private Color c; 

    public Shape(int x, int y, int type, Color c) { 
     this.x = x; 
     this.y = y; 
     this.type = type; 
     this.c = c; 

    } 

    public int getX() { 

     return x; 
    } 

    public int getY() { 

     return y; 
    } 

    public int getType() { 

     return type; 
    } 

    public Color getColor() { 

     return c; 
    } 



} 
+1

Можем ли мы, пожалуйста, не публиковать один и тот же вопрос, вам может потребоваться некоторое время, чтобы получить ответ, который вам нужен – MadProgrammer

ответ

2

В классе DrawingPanel вам нужен метод Li ke addShape(...), который добавит объект Shape в ArrayList. Затем в методе paintComponent(...) вы перебираете ArrayList для рисования каждой фигуры в списке.

Посмотрите пример Draw On Component, найденный в Custom Painting Approaches для рабочего примера.

Пример только рисует прямоугольники, поэтому ваш код будет немного более активным, так как вам нужно будет проверить, какой тип фигуры вы хотите нарисовать.

Смежные вопросы