当前位置: 首页 > 知识库问答 >
问题:

如何清除Jpanel但保留网格线?

符学
2023-03-14

下面是具有主面板和按钮函数的类的代码:

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();
          }

     });
}
}

下面是一个完成所有图形工作并绘制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个答案

单于帅
2023-03-14

不清楚您希望如何合并显示网格的逻辑。这里有一个如何切换它的例子,只是为了给你一个想法。在楼层类中添加布尔标志,该标志控制网格是否显示。然后在floor.PaintComponent()中,根据这个Boolean标志的值绘制网格。更改标志的值应该会触发重新绘制。然后,更改floorplan类中此标志的值,以响应操作或其他程序逻辑。下面是一个简单的实现,它在单击clear按钮时切换网格:

楼层等级:

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);
}

平面图等级:

clearButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(final ActionEvent e) {
        floor.setDisplayGrid(!floor.isDisplayGrid());
    }
});
public void clear() {
    bufImage.flush();
    bufImage = null;
    repaint();
}
clearButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(final ActionEvent e) {
        floor.clear();
    }
});
 类似资料:
  • 问题内容: 对于字符串,我需要它成为。 使用此正则表达式str.replaceAll(“(\ s | \ n)”,“”); 我可以得到“ abc123xyz”,但是如何在两者之间获得空格。 问题答案: 您不必使用正则表达式;您可以使用和代替。 这将为您提供您要查找的字符串。

  • 我正在创建一个简单的程序,在那里我画一个黑色的椭圆形,在那里我用鼠标点击。然而,我希望一个新的椭圆形出现,旧的消失。我该怎么做?我把removeAll()方法插入到我的mousePressed方法中,但它对我不起作用。removeAll()方法是否适用于此?还是我应该用别的?很抱歉,如果答案很明显,但我仍然是新手,并试图学习。任何建议都将不胜感激。谢谢

  • 问题内容: 我花了很长时间弄清楚我不应该将clear()用作Javascript中的函数名称: 这是Array.js: 症状:单击“添加”和“检查”按钮可得到预期的结果,但是单击“清除”按钮则无济于事。 如果我将 clear() 重命名为 clearxyz() ,它可以正常工作。 我的问题: “清除”是保留字吗?我没有在列表中看到它: 我是否应该使用调试技巧来解决此类问题?我花了很长时间(我是菜鸟

  • 问题内容: 我在网上找到的大多数示例都显示了如何删除空格-但就我而言,我需要保留它。 我希望保留空白(“ html”变量包含pre标记的内容),但是似乎用一个空格代替了多个空格。 如何保存/获取给定beautifulsoup解析器的原始内容? 问题答案: 如果您要解析的内容在 保留空白。

  • 问题内容: 如何在逗号处分割字符串,以便保留所有空格。例: 需要将其分隔成数组,使其看起来像这样: 连接它们之后: 尝试使用split这样的方法:但是后来我将其分离而没有空格… 任何想法如何做到这一点? 问题答案:

  • 问题内容: 问题是这样的:我有一个像这样的XML片段: 为了得到结果,我想删除所有-和-Tags,但保留它们的(文本)内容和子节点不变。另外,-Element应该保持不变。结果应该这样 目前,我将回到一个非常肮脏的把戏:我将etree.tostring这个片段,通过正则表达式删除有问题的标签,并用etree.fromstring结果替换原始片段(不是真正的代码,但是应该这样): 我知道我可能可以使