简体   繁体   中英

Repainting JPanel

So i'm trying to clear my drawing Panel and I have looked at multiple examples but none of them seem to be working for me? I have a clear button that clears textfields/errors which I got to work perfectly but the Drawing panel still does not clear arraylists or "repaint". I'm playing around with changing around the size of the oval so please ignore my drawPoints method.

Here is my code:

public class Panel extends JPanel{
ArrayList<Point> pointArray = new ArrayList<>();
ArrayList<Color> colorArray = new ArrayList<>();

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g); 
    repaint();
    //Create the 2D graphics object
    Graphics2D myDrawing = (Graphics2D) g;
    for (int i = 0; i < pointArray.size(); i++) {
        myDrawing.setColor(colorArray.get(i));
        myDrawing.fillOval(pointArray.get(i).x,pointArray.get(i).y, 10, 10);
   }        
}
  public void drawPoints(int mouseX, int mouseY, int height, int width){
   Point p = new Point(mouseX,mouseY);
   pointArray.add(p);
   colorArray.add(this.getForeground());
   repaint();
}

  public void changeColor(){
 int red = (int) (Math.random() * 256);
 int green = (int) (Math.random() * 256);
 int blue = (int) (Math.random() * 256);
 this.setForeground(new Color(red,green,blue)); 
 }

 public void mousePressed(MouseEvent event) {
    pointArray.clear();
    colorArray.clear();
    repaint();
 }

}

public static void main(String[] args) {
    //set the frame
    JFrame frame = new JFrame();
    frame.setSize(600, 300);
    frame.setTitle("Multiple Panels");  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

    //create the panel for GUI
    JPanel panelGUI = new JPanel();
    panelGUI.setBackground(Color.yellow);
    //GUIs
    //create textfields
    JTextField radiusField1 = new JTextField("10", 10);
    JTextField radiusField2 = new JTextField("10", 10);
    //create buttons
    final JButton clearDrawingButton = new JButton("Clear Screen");
    final JButton changeColorButton = new JButton("Change Color");
    //labels
    final JLabel displayLabel = new JLabel("");

    //add all GUIs to the GUI panel
    panelGUI.add(radiusField1);
    panelGUI.add(radiusField2);
    panelGUI.add(changeColorButton);
    panelGUI.add(clearDrawingButton);
    panelGUI.add(displayLabel);

    //create the panel to draw
    final Panel drawingPanel = new Panel();
    drawingPanel.setBackground(Color.white);
    //create the initial color
    Color drawingColor = new Color(255,0,0);
    //set the initial drawing color of the panel
    drawingPanel.setForeground(drawingColor);

    //add the grid with two columns and two rows to add the three panels
    GridLayout grid = new GridLayout(0,2,10,20);
    //add the grid to the frame
    frame.setLayout(grid);
    //add the panels to the frame
    frame.add(panelGUI);
    frame.add(drawingPanel); 


class MouseClickListener implements MouseListener
    {  
        public void mouseClicked(MouseEvent event)
        {  
           int x = event.getX();
           int y = event.getY();
           System.out.println(x + " " + y);              

           try {
           String text1 = radiusField1.getText();
           String text2 = radiusField2.getText();
           int height = Integer.parseInt(text1);
           int width = Integer.parseInt(text2);
           drawingPanel.drawPoints(x, y, height, width);

        } catch (NumberFormatException ex) {
        displayLabel.setText("Textfields empty! Please enter number.");}
        }

        // Do­nothing methods
        public void mouseReleased(MouseEvent event) {}
        public void mousePressed(MouseEvent event) {}
        public void mouseEntered(MouseEvent event) {}
        public void mouseExited(MouseEvent event) {}
        }
    class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            if (event.getSource()== changeColorButton){
                drawingPanel.changeColor();
            }

            if(event.getSource()==clearDrawingButton){
                radiusField1.setText("10");
                radiusField2.setText("10");
                displayLabel.setText("");
            }
        } 
    } 
   MouseListener listener1 = new MouseClickListener();
   drawingPanel.addMouseListener(listener1);
   ActionListener listener = new ButtonListener();
   changeColorButton.addActionListener(listener);
   clearDrawingButton.addActionListener(listener);
   frame.setVisible(true);
}  

}

You have this mousePressed method in your main class:

 public void mousePressed(MouseEvent event) {
    pointArray.clear();
    colorArray.clear();
    repaint();
 }

But it isn't doing anything because your main class does not implement MouseListener and no one is calling this method.

The rest of your code is not very pretty looking. I assume you are doing this as part of a course or otherwise just trying to learn Java Swing in a non-work environment. If this is true, I would recommend that you start over - at least with your MouseListeners, and instead create Actions for your button responses by subclassing AbstractAction and using it with JButton.setAction(myAction); This may seem painful now, but you'll be glad you did it in the future

I have a clear button that clears textfields/errors which I got to work perfectly but the Drawing panel still does not clear arraylists or "repaint".

Well look at the code that clears the text fields:

        if(event.getSource()==clearDrawingButton){
            radiusField1.setText("10");
            radiusField2.setText("10");
            displayLabel.setText("");
        }

Where is the code that clears the ArrayLists?

Add the code to clear the ArrayLists to the ActionListener .

You can also check out Custom Painting Approaches for working code that draws "rectangles". It supports different colors and a "Clear" button.

Also, instead of using a JTextField for the oval size, you might want to consider using a JSpinner . This will allow the user to easily change the numeric value and you don't have to add any special editing to make sure the value entered is a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM