JPanel in JScrollPane in JTabbedPane: setPreferredSize not working
I have a class MyPanel which extends JPanel and calls setPreferredSize
within the paintComponent method. It is placed in a JScrollPane which is placed
in a JTabbedPane.
When I click on a Button, I change the width of the panel through the variable "width".
After revalidate on the panel nothing happens (no scrollbars do appear).
At the same time I change the width of another MyPanel placed in a JScrollPane but not
in a JTabbedPane. After revalidate on this panel the srollbars do appear.
Why in the first case the scrollbars do not appear ?
/*
* Test_1.java
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclass Test_1extends JFrame{
public Test_1(){
super("Test_1");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400,300);
setLocationRelativeTo(null);
jToolBar1 =new JToolBar();
jButton1 =new JButton("Set width 1000");
jTabbedPane1 =new JTabbedPane();
jScrollPane1 =new JScrollPane();
jScrollPane2 =new JScrollPane();
p1 =new MyPanel();
p2 =new MyPanel();
jToolBar1.add(jButton1);
getContentPane().add(jToolBar1, BorderLayout.NORTH);
jScrollPane1.setViewportView(p1);
jTabbedPane1.addTab("tab1", jScrollPane1);
getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
jScrollPane2.setPreferredSize(new Dimension(100, 100));
jScrollPane2.setViewportView(p2);
getContentPane().add(jScrollPane2, BorderLayout.SOUTH);
jButton1.addActionListener(new ActionListener(){
publicvoid actionPerformed(ActionEvent evt){
jButton1ActionPerformed(evt);
}
});
}
privatevoid jButton1ActionPerformed(ActionEvent evt){
p1.width=1000;
p1.revalidate();
p2.width=1000;
p2.revalidate();
}
publicstaticvoid main(String args[]){new Test_1().setVisible(true);}
private MyPanel p1, p2 ;
private JButton jButton1;
private JScrollPane jScrollPane1, jScrollPane2;
private JTabbedPane jTabbedPane1;
private JToolBar jToolBar1;
class MyPanelextends JPanel{
publicvoid paintComponent(Graphics g){
super.paintComponent(g);
setPreferredSize(new Dimension(width,100));
System.out.println(width);
}
publicint width = 100;
}
}

