2011-02-17 60 views
0

我在我的Gui Builder JFram類A中使用Custome jPanel,我面臨的問題是當我單擊JFrame中的按鈕時更新我的​​JPanel中的組件(Lable)。其中有Gui生成器JFrame ClassA:它會更改Jpl的顏色並刪除所有標籤但不更新新標籤。java更新Jpanel組件

private void btnShowActionPerformed(java.awt.event.ActionEvent evt) { 
    // TODO add your handling code here: 

      Random randomGenerator = new Random(); 
      for (int idx = 1; idx <= 10; ++idx) { 
       q = randomGenerator.nextInt(100); 
      } 
      jpl1.removeAll(); 
      new Jpl().printMe(ClassA.q); 
      jpl1.revalidate(); 
      jpl1.setBackground(Color.BLUE); 
      jpl1.repaint(); 
} 

這裏是用作GuiBuilder JFrame類A.

public class Jpl extends JPanel { 

public Jpl() { 
    printMe(ClassA.q); 
} 


public void printMe(int q) { 

    for (int i = 0; i <q; i++) { 
     System.out.println(i+"rinting lable"); 
     String htmlLabel = "<html><font color=\"#A01070\">" + i + " New Lable </font></html>"; 
     JLabel lbl = new JLabel(htmlLabel); 
     setLayout(new GridLayout(0, 1)); 
     add(lbl, Jpl.RIGHT_ALIGNMENT); 
     lbl.setForeground(Color.BLUE); 
     Border border = BorderFactory.createLineBorder(Color.lightGray); 
     lbl.setBorder(border); 
     lbl.add(new JSeparator(SwingConstants.HORIZONTAL)); 

     lbl.addMouseListener(new MouseAdapter() { 

      @Override 
      public void mousePressed(MouseEvent e) { 
       JLabel label = (JLabel) e.getSource(); 
       JOptionPane.showMessageDialog(null, "You Slected"); 
       System.out.println(label.getText() + "NO AKKA is Selected"); 
      } 
     }); 
    } 

} 

回答

1

您是在噴氣推進實驗室的一個新實例調用printMe()的是定製組件JPL類,嘗試:

private void btnShowActionPerformed(java.awt.event.ActionEvent evt) { 
    // TODO add your handling code here: 

      Random randomGenerator = new Random(); 
      for (int idx = 1; idx <= 10; ++idx) { 
       q = randomGenerator.nextInt(100); 
      } 
      jpl1.removeAll(); 
      jpl1.printMe(ClassA.q); // HERE - REMOVED new and using jpl1 instance 
      jpl1.setBackground(Color.BLUE); 
      jpl1.revalidate(); 
      jpl1.repaint(); 
} 

在不明白你爲什麼循環10次你的隨機數。只有最後的結果將被保留,也許你想使用q += randomGenerator.nextInt(100);。另外,ClassA.q應該被替換爲q,如果它是相同的變量。

+0

非常非常感謝你完全解決了我的問題。 – 2011-02-17 19:39:34