2011-07-28 119 views
0

我在JScrollPane中有一個帶有GridBagLayout的JPanel。我還在JPanel中有一個'add'按鈕,單擊它時將從JPanel中刪除,向JPanel添加一個單獨組件的新實例,然後將其自身添加回JPanel。這種類型的組件越來越多,隨後是「添加」按鈕。JScrollPane中的GridBagLayout沒有正確調整大小

添加新組件可以正常工作,JPanel伸展以適應新組件,並且JScrollPane的行爲與預期相同,允許您滾動瀏覽JPanel的整個長度。

這是附加的工作原理:

jPanel.remove(addButton); 
GridBagConstraints c = new GridBagConstraints(); 
c.gridx = 0; 
c.gridy = GridBagConstraints.RELATIVE; 
jPanel.add(new MyComponent(), c); 
jPanel.add(addButton, c); 
jPanel.validate(); 
jPanel.repaint();` 

拆除工程通過單擊添加的組件本身內部的按鈕。他們將自己從JPanel中刪除就好了。但是,JPanel保持它的伸展大小,重新定位組件列表。

這是去除如何工作的:

Container parent = myComponent.getParent(); 
parent.remove(myComponent); 
parent.validate(); 
parent.repaint();` 

的問題是,爲什麼我的GridBagLayout的JPanel添加組件時刪除組件時調整,但不是?

+1

如果你打電話重新驗證並重新繪製由JScrollPane中舉行的JViewport會發生什麼? –

+1

如果您將您的[SSCCE](http://sscce.org)與您的問題一起顯示問題,您通常會更快得到更好的答案。 – camickr

+0

感謝氣墊船,它做到了。錯過'重新驗證'。 – naugler

回答

1

你必須重新驗證並重新繪製JScrollPane的,這裏有一個例子:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class SwingTest { 

    public static void main(String[] args) { 
     final JPanel panel = new JPanel(new GridBagLayout()); 

     for (int i = 0; i < 25; i++) { 
      JTextField field = new JTextField("Field " + i, 20); 

      GridBagConstraints constraints = new GridBagConstraints(); 
      constraints.gridy = i; 

      panel.add(field, constraints); 
     } 

     final JScrollPane scrollPane = new JScrollPane(panel); 

     JButton removeButton = new JButton("Remove Field"); 
     removeButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       if (panel.getComponentCount() >= 1) { 
        panel.remove(panel.getComponentCount() - 1); 
        scrollPane.revalidate(); 
        scrollPane.repaint(); 
       } 
      } 
     }); 


     JFrame frame = new JFrame("Swing Test"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.setSize(640, 480); 
     frame.setLocation(200, 200); 
     frame.getContentPane().add(scrollPane); 
     frame.getContentPane().add(removeButton, BorderLayout.SOUTH); 

     frame.setVisible(true); 
    } 
} 
+0

謝謝!我錯過了'重新驗證'的方法,並使用'驗證'。 – naugler