【问题标题】:How to clear a JFrame in Netbeans after a polygon has been drawn绘制多边形后如何在 Netbeans 中清除 JFrame
【发布时间】:2015-02-13 01:56:39
【问题描述】:

我制作了这个程序,它在 JFrame 中绘制一个多边形,然后填充它。我最近对其进行了更改,以便拥有控制多边形移动的按钮。除了一个问题之外,该移动还有效:当我按下按钮将多边形移动一个方向时,会在新位置创建一个新多边形,但原始多边形仍然可见。

我需要在调用 repaint() 之前清除 JFrame,因为调用 repaint() 本身并不会清除 JFrame(尽管我认为它应该这样做)。

我已经尝试过诸如:

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

但我没有运气。

编辑:这是我的课

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            
}

【问题讨论】:

  • 1) 您不应该直接在 JFrame 上绘图,而应该在它所拥有的 JPanel 上绘图(正如教程将向您展示的那样)。 2) 你的绘图代码可能是一切的关键,所以你应该展示它。
  • @HovercrafFullOfEels 那么当我调用paint() 时,Netbeans 会自动设置一个JPanel 来绘制吗?因为我的班级只扩展了 JFrame,而我没有做任何事情来设置 JPanel。
  • @HovercraftFullOfEels 我已按要求添加了代码。

标签: java netbeans jframe polygon repaint


【解决方案1】:

是否不赞成使用 JFrame 绘图...这并不重要,因为这只是为了学习经验,我知道我应该改为使用 JPanel 绘图。我通过添加 super.paint(g); 解决了这种测试的问题。在我对 paint() 方法的调用中调用。

【讨论】:

    【解决方案2】:

    JFrame 是一个没有实际显示的对象。它只是一个包含其他 GUI 对象(例如 JPanel)的容器,而 JPanel 又包含 JButton 等。

    话虽如此,您所有的实际绘画都应该发生在面板内,而不是框架内。另外,您是否拥有用于绘制多边形的其余代码?那里也可能发生一些事情。

    【讨论】:

    • 我已经添加了代码来查看是否是绘图问题。
    【解决方案3】:

    根据您提供的当前信息,很难说有什么问题,所以我所能做的就是提供一般性建议:

    • 首先,正如我在评论中提到的,不要直接在 JFrame 内绘制。 JFrame 是复杂的容器,包含并显示许多组件,包括根窗格、玻璃窗格、菜单栏和内容窗格(GUI 的中心主要部分),如果你弄乱了它们的绘图和显示,你就有可能弄乱它们的所有渲染他们的组件。
    • 而是创建一个扩展 JPanel 的类(如果您允许,NetBeans 可以这样做),并在该类的 paintComponent(...) 方法内绘制。
    • 如果需要,然后在 JFrame(或 JDialog、JApplet、另一个 JPanel...)中显示您的 JPanel。
    • 始终在您的 JPanel 的 paintComponent 覆盖中调用 super 的 paintComponent 方法。这将删除旧图像。
    • 阅读 Swing 图形教程了解详细信息。
    • 如果您需要更多帮助,请显示更多代码。

    【讨论】:

    • 我已将其全部更改为 JPanel,但现在即使构建良好,我也没有 GUI。
    • @saboehnke:你的主要方法在哪里?您在哪里创建 JFrame 并将 JPanel 添加到其中?
    • 我创建了一个新项目,现在我有一个包含 JPanel 的 JFrame,该 JPanel 然后包含我的所有绘图,并且我使用的是paintComponent() 方法而不是paint()。我现在的问题是突然填充多边形不起作用。基本上,我在 JPanel 中所做的一切现在都会在每次 repaint() 调用时清除屏幕,但现在我没有像以前那样填充我的多边形。
    • 我已经把它缩小到我的填充不再出现的唯一时间是当我在 JPanel 上绘画时调用 super.paintComponent() 或者我调用 super.paint()当我只使用 JFrame 时使用paint() 方法。知道这是为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 2020-04-25
    • 1970-01-01
    • 2021-10-20
    • 2011-12-30
    • 1970-01-01
    相关资源
    最近更新 更多