Java Swing - Repaint()无效

时间:2013-11-04 17:52:43

标签: java swing jbutton actionlistener repaint

以下是我的代码。即使正在调用动作侦听器函数 -

,GUI也不会在鼠标单击事件上自行清除
package GUI;
import java.awt.Color;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;
import ospackage.tablefunctions;

public class GUI_new extends JPanel implements ActionListener{

 Graphics g1;
 JButton buttonNext = new JButton();
 int L=0;

public void display() {
    final JFrame f=new JFrame("Rectangle");     
    f.setContentPane(new GUI_new());
    f.setSize(1000,1000);
    f.setVisible(true);
    f.getContentPane().setBackground(Color.BLACK);

    f.setLayout(null);
    f.add(buttonNext);

    buttonNext.setBounds(900,30, 200, 200);
    buttonNext.setVisible(true);

    buttonNext.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            //printBlocks(g, 100);
            //buttonNext.revalidate();
            removeAll();
            revalidate();
            //f.repaint();
            //System.out.println("called repaint");
            repaint();

            System.out.println("called");
        }
    });

}

tablefunctions io = new tablefunctions();

public void paint(final Graphics g) {
    super.paint(g);
    printBlocks(g, 0);
}

public void printBlocks(Graphics g , int offset ) {
    int i=0,j=0,l=offset;

    for(i=20;i<620;i=i+60) {
        for(j=20;j<820;j=j+80) {
             String temp=Integer.toString(l);
              if(!io.retrieveData("FAT","address" , 2, temp).equals("free"))
                  g.setColor(Color.RED);
              else
                  g.setColor(Color.GREEN);

            g.drawRect(j, i, 60, 30);
            g.fillRect(j, i, 60, 30);
            g.drawString("Cluster" + l,j , i-5 );

            l++;
    }
}
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
//  e.getSource().equals()

}

public static void main(String[] args) {
    GUI_new gn = new GUI_new();
    gn.display();
}
}

2 个答案:

答案 0 :(得分:4)

GUI_new的两个实例存在问题。替换:

f.setContentPane(new GUI_new()); 

with:

f.setContentPane(this);

问题是actionPerformed重新绘制this实例,但JFrame内容是使用第二个实例初始化的。

请注意,使用absolute layout可能很复杂,通常可以避免。有关一些想法,请参阅A Visual Guide to Layout Managers

另外,请覆盖paintComponent()而不是paint()。见Performing Custom Painting

答案 1 :(得分:3)

试试这个:

GUI_new.this.removeAll(); 
GUI_new.this.updateUI();