简体   繁体   English

绘制多边形后如何在Netbeans中清除JFrame

[英]How to clear a JFrame in Netbeans after a polygon has been drawn

I made this program that draws a polygon in a JFrame and then fills it. 我编写了一个程序,该程序在JFrame中绘制一个多边形,然后将其填充。 I have recently changed it so that I have buttons that control movement of the polygon. 我最近对其进行了更改,以便可以控制多边形的移动。 The movement works besides one issue: when I press a button to move the polygon a direction, a new polygon is created in the new spot but the original still stays visible. 该移动的工作原理除了一个问题:当我按下按钮将多边形移动一个方向时,会在新位置创建一个新的多边形,但原始多边形仍然可见。

What I need is to clear the JFrame before repaint() is called since calling repaint() itself isn't clearing the JFrame (even though I thought it was supposed to). 我需要的是在调用repaint()之前清除JFrame,因为调用repaint()本身并不会清除JFrame(即使我认为应该这样做)。

I have already tried things such as: 我已经尝试过诸如:

removeAll();
revalidate();
repaint();

But I am having no luck. 但是我没有运气。

EDIT: here is my class 编辑:这是我的课

public class Assign3 extends javax.swing.JPanel 
{

       /**
 * Creates new form Assign3
 */
public Assign3() 
{
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton7 = new javax.swing.JButton();
    jButton8 = new javax.swing.JButton();

    jButton3.setText("Up");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    jButton4.setText("Down");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });

    jButton5.setText("Left");
    jButton5.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton5ActionPerformed(evt);
        }
    });

    jButton6.setText("Right");
    jButton6.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton6ActionPerformed(evt);
        }
    });

    jButton7.setText("Zoom (+)");
    jButton7.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton7ActionPerformed(evt);
        }
    });

    jButton8.setText("Zoom (-)");
    jButton8.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton8ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(272, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(30, 30, 30)
            .addComponent(jButton3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton5)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton6)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton7)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton8)
            .addContainerGap(102, Short.MAX_VALUE))
    );
}// </editor-fold>                        

//UP PRESSED
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    //1) get the current y coordinates
    //2) move the y coordinates up

    upPressed();
}                                        

//DOWN BUTTON
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    //1) get the current y coordinates
    //2) move the y coordinates down

    downPressed();
}                                        

//LEFT BUTTON
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    //1) get the current x coordinates
    //2) move the x coordinates to the left

    leftPressed();
}                                        

//RIGHT BUTTON
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    //1) get the current x coordinates
    //2) move the x coordinates to the right

    rightPressed();
}                                        

//ZOOM IN BUTTON
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    //translate center to origin
    //caculate scaling
    //tanslate back

    zoomInPressed();
}                                        

//ZOOM OUT BUTTON
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:

    zoomOutPressed();
}                                        
//UP BUTTON
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    //1) get the current y coordinates
    //2) move the y coordinates up

    upPressed();
}                         

int left_most_edge, right_most_edge, scan = 0;
int wxl = 50, wxh = 362, wyl = 246, wyh = 62;
double[] xcoord;
double[][] table = new double[4][200];  //2d array containing: 
                                        //[0][-] -> ymax, [1][-] -> ymin, [2][-] -> dx, [3][-] -> x
double[] px = {100, 150, 250, 300, 250, 150, 100}; //contains all x coord.
double[] py = {125, 100, 200, 150, 100, 200, 200}; //contains all y coord.
int outnum;
double[] lastl = new double[2];
double[] lastr = new double[2];
double[] lastt = new double[2];
double[] lastb = new double[2];

public void initializeTable() 
{
    int i, j;

    for (i = 0; i < 4; i++) 
    {
        for (j = 0; j < 200; j++) 
        {
            table[i][j] = 0;
        }//end for
    }//end for
}//end initializeTable

public void upPressed() 
{
    for (int i = 0; i < py.length; i++) 
    {
        py[i] -= 5;
    }//end for
    repaint();
}//end upPressed

public void downPressed() 
{
    for (int i = 0; i < py.length; i++) 
    {
        py[i] += 5;
    }//end for
    repaint();
}//end upPressed

public void leftPressed() 
{
    for (int i = 0; i < px.length; i++) 
    {
        px[i] -= 5;
    }//end for
    repaint();
}//end upPressed

public void rightPressed() 
{
    for (int i = 0; i < px.length; i++) 
    {
        px[i] += 5;
    }//end for
    repaint();
}//end upPressed

public void zoomInPressed() 
{

}//end zoomInPressed

public void zoomOutPressed() 
{

}//end zoomOutPressed

public void clipPolygon(Graphics g, int number_entered_edges) 
{
    lastl[0] = px[number_entered_edges - 1];
    lastl[1] = py[number_entered_edges - 1];

    lastr[0] = wxl;
    lastb[0] = wxl;
    lastt[0] = wxl;
    lastr[1] = wyl;
    lastb[1] = wyl;
    lastt[1] = wyl;

    outnum = 0;

    for (int i = 0; i < number_entered_edges - 1; i++) 
    {
        clipL(px[i], py[i]);
    }//end for

    outnum = 0;

    for (int i = 0; i < number_entered_edges - 1; i++) 
    {
        clipL(px[i], py[i]);
    }//end for
}//end clipPolygon

public void clipL(double x, double y) 
{
    if ((lastl[0] < wxl && wxl <= x) || (x <= wxl && wxl < lastl[0])) 
        clipR(wxl, (((y - lastl[1]) * (wxl - x)) / x - lastl[0]) + y);

    lastl[0] = x;
    lastl[1] = y;

    if (wxl < x)
        clipR(x, y);
}//end clipL

public void clipR(double x, double y) 
{
    if ((x <= wxh && wxh < lastr[0]) || (lastr[0] < wxh && wxh <= x)) 
        clipB(wxh, (((y - lastr[1]) * (wxh - x)) / x - lastr[0]) + y);

    lastr[0] = x;
    lastr[1] = y;

    if (x < wxh)
        clipB(x, y);
}//end clipR

public void clipB(double x, double y) 
{
    if ((lastb[1] < wyl && wyl <= y) || y <= wyl && wyl < lastb[1]) 
        clipT((((x - lastb[0]) * (wyl - y)) / y - lastb[1]) + x, wyl);
    lastb[0] = x;
    lastb[1] = y;

    if (wyl < y)
        clipT(x, y);
}//end clipB

public void clipT(double x, double y) 
{
    if ((lastt[1] > wyh && wyh >= y) || y >= wyh && wyh > lastt[1])
        store((((x - lastt[0]) * (wyh - y)) / y - lastt[1]) + x, wyh);

    lastt[0] = x;
    lastt[1] = y;

    if (wyh > y)
        store(x, y);
}//end clipT

public void store(double x, double y) 
{
    outnum++;
    px[outnum] = x;
    py[outnum] = y;
}//end store

public double max(double x, double y)
{ //determines the greater of two values
    double max;
    if (x > y) 
        max = x;
    else 
        max = y;
    return max;
}//end max

public void edgeInsert(double xStart, double yStart, double xEnd, double yEnd, int number_entered_edges) 
{ //inserting edges into the edge table
    int j = number_entered_edges; //removing the - 1 removes line on left side
    double x;

    if (yStart > yEnd) 
    {
        table[0][j] = yStart;
        table[1][j] = yEnd;
    }//end if
    else 
    {
        table[0][j] = yEnd;
        table[1][j] = yStart;
    }//end else

    if (table[1][j] == xStart)
        x = xStart;
    else 
        x = xEnd;

    if (table[0][j] == yStart)
        table[2][j] = -(-(xEnd - xStart) / (yEnd - yStart));
    else
        table[2][j] = -(xEnd - xStart) / (yEnd - yStart);

    table[3][j] = x + table[2][j] / 2;

    help(j);
}//end edgeInsert

public void loadTable(int number_vertices, int number_entered_edges,
        double[] px, double[] py) 
{ //take the x and y coordinates and build an edge table based off of them
    int k;
    double xStart, yStart, xEnd, yEnd;

    xStart = px[number_vertices - 1];
    yStart = trunc(py[number_vertices - 1]) + 0.5;

    //start off with no edges in edge table
    number_entered_edges = 0;
    for (k = 0; k < number_vertices; k++) 
    {
        xEnd = px[k];
        yEnd = trunc(py[k]) + 0.5;

        if (yStart == yEnd) 
        {
            xStart = xEnd;
        }//end if
        else 
        {
            //add edge to edge table
            number_entered_edges++;
            edgeInsert(xStart, yStart, xEnd, yEnd, number_entered_edges);

            yStart = yEnd;
            xStart = xEnd;
        }//end else
    }//end for
    scan = (int) trunc(table[1][0]); //start at the top of the polygon
}//end loadTable

public void include(int number_entered_edges) 
{ //pushing the right most edge
    while ((right_most_edge + 1 < number_entered_edges) && (table[1][right_most_edge + 1] < scan)) 
    {
        right_most_edge++;
    }//end while
}//end include

public void exclude() 
{ //excluding edges that we no longer care about
    for (int i = left_most_edge; i <= right_most_edge; i++) 
    {
        if (table[0][i] < scan) 
        {
            left_most_edge++;
            for (int j = i; j >= left_most_edge; j--) 
            {
                table[0][j] = table[0][j - 1];
                table[2][j] = table[2][j - 1];
                table[3][j] = table[3][j - 1];
            }//end for
        }//end if
    }//end for
}//end exclude

public void help(int i) 
{
    double helpX, helpDX, helpYMax, helpYMin;
    for (int j = i - 1; j >= 0; j--) 
    {
        if ((table[1][j] == table[1][j + 1] && table[3][j] > table[3][j + 1]) || table[1][j] > table[1][j + 1]) 
        {
            helpYMax = table[0][j];
            table[0][j] = table[0][j + 1];
            table[0][j + 1] = helpYMax;

            helpYMin = table[1][j];
            table[1][j] = table[1][j + 1];
            table[1][j + 1] = helpYMin;

            helpDX = table[2][j];
            table[2][j] = table[2][j + 1];
            table[2][j + 1] = helpDX;

            helpX = table[3][j];
            table[3][j] = table[3][j + 1];
            table[3][j + 1] = helpX;
        }//end if
    }//end for
}//end help

public void updateX() 
{ //increment x based on dx
    for (int i = left_most_edge; i <= right_most_edge; i++) 
    {
        table[3][i] += table[2][i];
    }//end for
}//end updateX

public void sortOnX() 
{ //sorting x values from least to greatest in edge table
    int l = 0;
    double t;
    xcoord = new double[right_most_edge - left_most_edge + 1];

    for (int i = left_most_edge; i <= right_most_edge; i++) 
    {
        xcoord[l] = table[3][i];
        for (int j = l - 1; j >= 0; j--) 
        {
            if (xcoord[j] > xcoord[j + 1]) 
            {
                t = xcoord[j];
                xcoord[j] = xcoord[j + 1];
                xcoord[j + 1] = t;
            }//end if
        }//end for

        l++;
    }//end for
}//end sortOnX

public void fillScan(Graphics g) 
{ //determines the line to be drawn for filling
    for (int i = 0; i < xcoord.length; i += 2) 
    {
        drawMyHorizontalLine(g, (int) Math.round(xcoord[i]), scan, (int) Math.round(xcoord[i + 1]));
    }//end for
}//end fillScan

public double trunc(double num) 
{ //trucates the number passed in to remove any decimal
    double rem;
    if ((num % 2) == 0)
        return num;
    else
    {
        rem = num % 2;
        return num - rem;
    }//end else
}//end trunc

public void drawMyPolygon(Graphics g) 
{ //draws the polygon
    g.setColor(Color.RED);
    g.drawLine((int) px[0], (int) py[0], (int) px[1], (int) py[1]);
    g.drawLine((int) px[1], (int) py[1], (int) px[2], (int) py[2]);
    g.drawLine((int) px[2], (int) py[2], (int) px[3], (int) py[3]);
    g.drawLine((int) px[3], (int) py[3], (int) px[4], (int) py[4]);
    g.drawLine((int) px[4], (int) py[4], (int) px[5], (int) py[5]);
    g.drawLine((int) px[5], (int) py[5], (int) px[6], (int) py[6]);
    g.drawLine((int) px[6], (int) py[6], (int) px[0], (int) py[0]);
}//end drawMyPolygon

public void drawMyHorizontalLine(Graphics g, int x1, int y, int x2) 
{ //draws the line for filling
    g.setColor(Color.GREEN);
    g.drawLine(x1, y, x2, y);
}//end drawMyHorizontalLine

public void fillMyPolygon(Graphics g, int number_vertices, int number_entered_edges) 
{ //calls methods to deal with edge table and fill the polygon
    if (number_entered_edges < 3 || number_entered_edges > 200) 
    {
        System.out.println("Polygon size error");
    }//end if
    else 
    {
        loadTable(number_vertices, number_entered_edges, px, py);
        while (left_most_edge < number_entered_edges) {
            scan++; //move down the screen
            exclude();
            updateX();
            include(number_entered_edges);
            sortOnX();
            fillScan(g);
        }//end while
    }//end else
}//end fillMyPolygon

public void drawWindow(Graphics g) 
{
    g.setColor(Color.BLACK);
    g.drawLine(50, 62, 50, 246);
    g.drawLine(50, 62, 362, 62);
    g.drawLine(50, 246, 362, 246);
    g.drawLine(362, 62, 362, 246);
}//end drawWindow

public void buttons() 
{
    jButton1.setVisible(true);
    jButton2.setVisible(true);
    jButton3.setVisible(true);
    jButton4.setVisible(true);
    jButton5.setVisible(true);
    jButton6.setVisible(true);
}//end buttons

@Override
public void paintComponent(Graphics g) 
{
    super.paintComponent(g);

    //initialize the edge table to all zeroes
    initializeTable();

    clipPolygon(g, 7);

    //begin filling the polygon
    fillMyPolygon(g, 7, 7);

    //draw polygon with red outline
    drawMyPolygon(g);

    //draw viewing window
    drawWindow(g);

    //set buttons to visible
    buttons();
}//end paintComponent

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
// End of variables declaration            
}

Whether drawing to the JFrame was frowned upon or not...it does not matter as this was just for a learning experience and I know that I should draw to a JPanel instead. 不管是否对JFrame进行绘制……都没关系……这无关紧要,因为这只是为了获得学习经验,我知道我应该改为使用JPanel。 I fixed my issue for this occurrence of testing just by adding the super.paint(g); 我通过添加super.paint(g)解决了这种测试问题。 call inside my call to the paint() method. 调用我对paint()方法的调用。

JFrame is an object that has no actual display. JFrame是没有实际显示的对象。 It is simply a container that holds other GUI objects such as JPanel, which in turn holds JButtons etc. 它只是一个容纳其他GUI对象(例如JPanel)的容器,而JPanel又包含JButtons等。

That being said, all of your actual painting should occur within the Panel, not the Frame. 话虽如此,您所有的实际绘画都应该在面板中进行,而不是在框架中进行。 Also, do you have the rest of the code you used to draw and paint your polygon? 此外,您是否拥有用于绘制和绘制多边形的其余代码? There could be something going on there as well. 那里可能还会发生一些事情。

It's hard to say what could be wrong based on the current information that you've provided, so about all I can do is give general advice: 根据您所提供的当前信息很难说出什么地方出了问题,所以我所能做的就是提供一般建议:

  • First and foremost as mentioned in my comment, don't draw directly inside of a JFrame. 首先,正如我在评论中提到的,不要直接在JFrame内部绘制。 JFrame's are complex containers that hold and display many components including root panes, glass panes, menu bars, and content panes (the central main portion of your GUI), and if you mess with their drawing and display you risk messing up their rendering of all their components. JFrame是复杂的容器,可容纳并显示许多组件,包括根窗格,玻璃窗格,菜单栏和内容窗格(GUI的中央主要部分),如果您弄乱了它们的图形并进行显示,则可能会弄乱它们的所有渲染它们的组成部分。
  • Instead create a class that extends JPanel (NetBeans can do this if you let it), and draw inside of the paintComponent(...) method of this class. 而是创建一个扩展JPanel的类(如果允许,NetBeans可以这样做),并在该类的paintComponent(...)方法内部进行绘制。
  • Then display your JPanel in a JFrame (or JDialog, JApplet, another JPanel...) if desired. 然后根据需要在JFrame(或JDialog,JApplet,另一个JPanel ...)中显示您的JPanel。
  • Always call the super's paintComponent method in your JPanel's paintComponent override. 始终在JPanel的paintComponent覆盖中调用上级的paintComponent方法。 This will erase old images. 这将删除旧图像。
  • Read the Swing graphics tutorials for the details. 阅读Swing图形教程以获取详细信息。
  • Show more code if you need more help. 如果需要更多帮助,请显示更多代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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