I would like progressively modify a java JFrame design structure, as in the this simple example. In a loop I'am increasing de preferredWidth of a JPanel and using the method pack(). But apparently the pack method is ignored. If I put the pack out of the loop, using it only one time, it's work. Anyone know the reason and a possible solution?
public class Calculadora extends JFrame {
private JPanel pnl = new JPanel();
private boolean flag;
public Calculadora() {
JPanel pnlPrincipal = new JPanel();
pnlPrincipal.setPreferredSize(new Dimension(300, 300));
pnlPrincipal.setBackground(Color.BLACK);
JButton btnAnexo = new JButton("Anexo");
btnAnexo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (flag) {
closeAnexo();
flag = false;
} else {
openAnexo();
flag = true;
}
}
});
pnlPrincipal.add(btnAnexo);
this.pnl.setBackground(Color.WHITE);
this.pnl.setPreferredSize(new Dimension(0, 300));
this.add(pnl, BorderLayout.EAST);
this.add(pnlPrincipal, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
}
private void openAnexo() {
new Thread () {
@Override
public void run() {
for (int i = pnl.getWidth(); i <= 200; i++) {
pnl.setPreferredSize(new Dimension(i, 300));
pack();
}
}
}.start();
}
private void closeAnexo() {
new Thread () {
@Override
public void run() {
for (int i = pnl.getWidth(); i >= 0; i--) {
pnl.setPreferredSize(new Dimension(i, 300));
pack();
}
}
}.start();
}
public static void main(String[] args) {
new Calculadora();
}
}