Ok, I am trying to do something in Java. I have a JPanel. This JPanel dynamically adds components to it, so it's size can change at any time. Now, I have a JFrame. This JFrame holds this JPanel. What I want is for when the JPanel gets resized (by adding a component to it), the JFrame will be resized as well. I am trying to use a ComponentListener in the JFrame, which listenes to the JPanel, and resizes the JFrame when the JPanel gets resized. However, for some reason, this Component listener doesn't work. When the JPanel is resized it doesn't run the componentResized function. It also doesn't call any other of the component functions when it should for the JPanel (like componentShown, etc...).
Example of code:
Code:
public class MyPanel extends JPanel {
public MyPanel() {
JButton b = new JButton("!!!");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
add(new JButton("..."));
setSize(getPreferredSize().width, getPreferredSize().height);
}
}
add(b);
}
public static void main(String args[]) {
JFrame j = new JFrame("");
MyPanel m = new MyPanel();
m.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
System.out.println("AHH!!!\n");
}
});
j.getContentPane().add(new Asn5());
j.pack();
j.setVisible(true);
}
}
This doesn't print out "AHH!!!" when it is resized (and the getPreferredSize DOES change, so it should be working). What am I doing wrong. Is there a way to force the JPanel to notify it's component listeners of a change?