Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9252853
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T11:03:44+00:00 2026-06-18T11:03:44+00:00

I’m drawing lines on a JPanel using a paint component and graphics 2D, but

  • 0

I’m drawing lines on a JPanel using a paint component and graphics 2D, but the background of the JPanel is set to a grid which is drawn when the user enters some dimensions. How do I clear the lines drawn on the JPanel when a button is clicked but regenerate a fresh panel again with the grid lines drawn? With the action event method for the clear button, I’ve tried using repaint(), removeAll() and creating a new instance of the JPanel but none of that seems to work.

Here is the code for the class with the main Panel and button functions:

package floorplan;

/**
*
* @author xodkx
*/


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;


public class FloorPlan extends JFrame 
{

private JPanel backPanel = new JPanel();
private JPanel toolsPanel = new JPanel();
private JFrame chooseFurniture;
private JFrame chooseFixture;
private JFrame chooseFramework;
private JButton furnitureButton = new JButton();
private JButton fixturesButton = new JButton();
private JButton frameworkButton = new JButton();
private JButton deleteButton = new JButton();
private JButton saveButton = new JButton();
private JButton clearButton = new JButton();
private JButton closeButton = new JButton();
private JRadioButton wall = new JRadioButton("Wall");
private JRadioButton door = new JRadioButton("Door");
private JRadioButton window = new JRadioButton("Window");


Floor floor = new Floor();

public FloorPlan()
{
     super("Floor Plan Generator");  
     createWindow();
     buttonFunctions();
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     pack();
     setVisible(true);
}

private void createWindow()
{
  backPanel.setLayout(new BorderLayout());
  backPanel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
  GridLayout panelLayout = new GridLayout();
  frameworkButton.setText("Framework");
  fixturesButton.setText("Fixtures");
  furnitureButton.setText("Furniture");
  deleteButton.setText("Delete");
  saveButton.setText("Save");
  clearButton.setText("Clear");

  add(backPanel, BorderLayout.CENTER);
  backPanel.add(toolsPanel, BorderLayout.NORTH);
  backPanel.add(floor, BorderLayout.CENTER);
  backPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  toolsPanel.add(frameworkButton);
  toolsPanel.add(fixturesButton);
  toolsPanel.add(furnitureButton);
  toolsPanel.add(deleteButton);
  toolsPanel.add(saveButton);
  toolsPanel.add(clearButton);
  add(backPanel); 
}


private void buttonFunctions()
{
    frameworkButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(final ActionEvent e)
        {
           chooseFramework = new JFrame("Pick A Framework");
           chooseFramework.setSize(250,250);
           chooseFramework.setLayout(new GridLayout(4,1));
           chooseFramework.add(wall);
           chooseFramework.add(door);
           chooseFramework.add(window);
           chooseFramework.add(closeButton);
           closeButton.setText("Close");


           wall.addActionListener(new ActionListener() 
          {
                @Override
                public void actionPerformed(ActionEvent e) 
          {

               floor.setFramework(Framework.WALL);



        }});

            door.addActionListener(new ActionListener() 
          {
                @Override
                public void actionPerformed(ActionEvent e) 
          {

               floor.setColor(Color.RED);
               floor.setFramework(Framework.DOOR);


        }});

            window.addActionListener(new ActionListener() 
          {
                @Override
                public void actionPerformed(ActionEvent e) 
          {
               floor.setColor(Color.BLUE);
               floor.setFramework(Framework.WALL);


        }});

           closeButton.addActionListener(new ActionListener() 
           {
                @Override
            public void actionPerformed(ActionEvent e) 
            {
               chooseFramework.setVisible(false);

            }
           });

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            chooseFramework.setVisible(true);
        }
    });

    furnitureButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(final ActionEvent e)
        {
           chooseFurniture = new JFrame("Pick Furniture to add");
           chooseFurniture.setSize(250,250);
           chooseFurniture.setLayout(new GridLayout(4,1));
           chooseFurniture.add(closeButton);
           closeButton.setText("Close");

           closeButton.addActionListener(new ActionListener() 
           {
                @Override
            public void actionPerformed(ActionEvent e) 
            {
               chooseFurniture.setVisible(false);
            }
           });

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            chooseFurniture.setVisible(true);
        }
    });

    fixturesButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(final ActionEvent e)
        {
           chooseFixture = new JFrame("Pick Furniture to add");
           chooseFixture.setSize(250,250);
           chooseFixture.setLayout(new GridLayout(4,1));
           chooseFixture.add(closeButton);
           closeButton.setText("Close");

           closeButton.addActionListener(new ActionListener() 
           {
                @Override
            public void actionPerformed(ActionEvent e) 
            {
               chooseFixture.setVisible(false);
            }
           });

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            chooseFixture.setVisible(true);
        }
    });

      **clearButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(final ActionEvent e)
        {  
          **//THIS IS WHERE I WANT TO CLEAR THE JPANEL WHEN THIS BUTTON IS CLICKED**  
        }
   });**
}    
public static void main(String[] args) 
{
    SwingUtilities.invokeLater(new Runnable()
     {

        @Override
          public void run()
          {
            FloorPlan floorPlan = new FloorPlan();
          }

     });
}
}

Here is the class that does all the graphics stuff and draws onto the JPanel

package floorplan;

/**
*
* @author xodkx
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.awt.event.MouseListener;

public class Floor extends JPanel implements MouseListener, MouseMotionListener
{


private static final int WIDTH = Integer.parseInt(JOptionPane.showInputDialog("Please    
                                                   enter the width of your room"));
private static final int LENGTH = Integer.parseInt(JOptionPane.showInputDialog("Please 
                                                 enter the width of your room"));
private static final Color BACKGROUND = Color.WHITE;
private static final Color INITIAL_COLOUR = Color.BLACK;
private static final Framework INITIAL_FRAMEWORK = Framework.WALL;

private MouseState state = MouseState.IDLE;
private Framework frameworkType = INITIAL_FRAMEWORK;
private Color colour = INITIAL_COLOUR;


private Point start = null;
private Point end = null;
private Point startpt = null;
private Point endpt = null;

private BufferedImage bufImage = null;


public Floor()
{
    setPreferredSize(new Dimension(LENGTH,WIDTH));
    setBackground(Color.white);
    setBorder(BorderFactory.createLineBorder (Color.black, 5));

    this.addMouseListener(this);
    this.addMouseMotionListener(this);

}

public void setColor(Color color)
{
    colour = color;

}

public void setFramework(Framework framework)
{
    frameworkType = framework;
}

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON);

    if(bufImage == null)
    {
        int h = this.getHeight();
        int w = this.getWidth();
        bufImage = (BufferedImage)this.createImage(h,w);
        Graphics2D gc = bufImage.createGraphics();
        gc.setColor(BACKGROUND);
        gc.fillRect(0, 0, w, h);
    }


    g2.drawImage(bufImage,null,0,0);

    drawGrid(g2);

    if(state == MouseState.DRAGGING)
    {
        createComponent(g2);
    }
}

public void drawGrid(Graphics g2)
{
    int gridDivisions = 20;
    int divisionSize = WIDTH/gridDivisions;
    int grid = WIDTH*LENGTH;

    g2.setColor(Color.lightGray);

    for(int i=1; i<grid; i++)
    {
        int x = i * divisionSize;
        g2.drawLine(x,0,x,getSize().height);
    }

    for(int i=1; i<grid; i++)
    {
        int y = i*divisionSize;
        g2.drawLine(0,y,getSize().width,y);
    }
}


public void createComponent(Graphics2D g2)
{
    g2.setColor(colour);

    switch (frameworkType)
    {
        case WALL:
            g2.setStroke(new BasicStroke(5));
            g2.drawLine(start.x, start.y, end.x,end.y);
            break;

        case DOOR:
            g2.setStroke(new BasicStroke(5));
            g2.drawLine(start.x, start.y, end.x,end.y);
            break;

        case WINDOW:
            g2.setStroke(new BasicStroke(5));
            g2.drawLine(start.x, start.y, end.x,end.y);
            break;


        default:
            g2.drawString("test", 10, 20);
            break;
    }
}


@Override
public void mousePressed(MouseEvent e)
{
    state = MouseState.DRAGGING;
    start = e.getPoint();
    end = start;
}

@Override

public void mouseDragged(MouseEvent e)
{

    state = MouseState.DRAGGING;
    end = e.getPoint();
    this.repaint();

}

@Override
public void mouseReleased(MouseEvent e)
{
    end = e.getPoint();
    if(state == MouseState.DRAGGING)
    {
        state = MouseState.IDLE;
        createComponent(bufImage.createGraphics());
        this.repaint();
    }
}



@Override
public void mouseClicked(MouseEvent e)
{

}

@Override
public void mouseEntered(MouseEvent e)
{

}

@Override
public void mouseExited(MouseEvent e)
{

}



@Override
public void mouseMoved(MouseEvent e)
{

}

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T11:03:45+00:00Added an answer on June 18, 2026 at 11:03 am

    It is not clear exactly how do you want to incorporate the logic of displaying the grid. Here is an example how to toggle it just to give you the idea. In Floor class add boolean flag that controls whether the grid is displayed or not. Then in Floor.paintComponent() draw grid based on the value of this boolean flag. Changing the flag’s value should trigger a repaint. Then, change the value of this flag from FloorPlan class, in response to an action or some other program logic. Here is a simple implementation that toggles grid when clear button is clicked :

    Floor class:

    private boolean displayGrid = true;
    
    public boolean isDisplayGrid() {
        return displayGrid;
    }
    public void setDisplayGrid(boolean displayGrid) {
        this.displayGrid = displayGrid;
        repaint();
    }
    
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        ...
        if (displayGrid)
            drawGrid(g2);
    }
    

    FloorPlan class:

    clearButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            floor.setDisplayGrid(!floor.isDisplayGrid());
        }
    });
    

    EDIT:

    Seems that I totally misinterpreted your question. If I understand correctly you want to clear the drawings upon a button click. Looks like all the drawings are done on the bufImage in the Floor class. Simply reset this image, ie:

    Floor class:

    public void clear() {
        bufImage.flush();
        bufImage = null;
        repaint();
    }
    

    FloorPlan class:

    clearButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            floor.clear();
        }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to clean up various Word 'smart' characters in user input, including but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I am using JSon response to parse title,date content and thumbnail images and place
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
this is what i have right now Drawing an RSS feed into the php,
I am using the SimpleRSS gem to parse a WordPress RSS feed. The only
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.