2012-03-23 16 views
2

10個の数字の配列を挿入ソートでソートし、長方形(棒グラフ)で表示する必要があります。ユーザーが「次へ」を押すたびに、配列内の次の位置がソートされます。コンソールは自分のアルゴリズムが動作していることを確認し、長方形は大きくなりますが、他の四角形の上に上書きされます。新しい矩形を描画する前にパネルは消去されません。これをどうすれば解決できますか?ここに私のコードの重要な部分です:JPanelの長方形の上書き。

public class graphTest extends JFrame { 

    int[] numbers = {31, 19, 76, 24, 94, 99, 21, 74, 40, 73}; 
    private JButton action = new JButton("Next"); 

    public graphTest(){ 
     final ImagePanel p1 = new ImagePanel(); 
     add(action, BorderLayout.SOUTH); 
     p1.add(new ImagePanel(), BorderLayout.CENTER); 
     add(p1,BorderLayout.CENTER); 
     action.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       //Code for insertion sort 
       p1.repaint(); 
       //System.out.println testing array 
      } 
     }); 
    } 

    class ImagePanel extends JPanel{ 
     public void paintComponent (Graphics g){ 
      super.paintComponents(g); 
      g.setColor(Color.black); 
      for(int i = 0; i < 10; i++) 
       g.drawRect(10*i+10,200-numbers[i],7,numbers[i]); 
     } 
    } 

    public static void main(String[] args) { 
     JFrame frame = new graphTest(); 
     frame.setTitle("Hi"); 
     frame.setSize(300, 300); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
     } 

} 

私は普通の四角形を描画する前に、大きなfillRectを描画することで迅速な回避策を作ったが、私はまだ適切にJPanelを再描画する方法を学びたいです。 ImagePanel.paintComponent(Graphics g)

答えて

3

あなたが本当にしたいことは、私は(最後には「S」)super.paintComponentsuper.paintComponentsを変更していないし、正常に動作するようですsuper.paintComponent(g)

+0

ありがとうございます!私が思っていたよりずっと簡単だった – user1287523

2

あるときにsuper.paintComponents(g)を呼び出します。