JPanel的JScrollPane下拉后也不能完全显示新增的控件
我的一个JPanel(布局是BoxLayout, Y_AXIS)添加进JScrollPane。在JPanel中有一个按钮JButton1,点击会在该panel上添加一个新的按钮,当添加的按钮已经超出panel的显示范围时,JScrollPane没有显示出竖直方向的滚动条。为什么呢?原代码如下:
import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
import javax.swing.WindowConstants;
public class NewJPanel extends javax.swing.JPanel {
private JButton jButton1;
private JPanel thisPanel=this;
int i=0;
public static void main(String[] args) {
JFrame frame = new JFrame();
NewJPanel p=new NewJPanel();
JScrollPane js=new JScrollPane(p,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.getContentPane().add(js);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public NewJPanel() {
super();
initGUI();
jButton1.addActionListener(new listener());
}
private void initGUI() {
try {
BoxLayout thisLayout = new BoxLayout(
this,
javax.swing.BoxLayout.Y_AXIS);
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(193, 300));
{
jButton1 = new JButton();
this.add(jButton1);
jButton1.setText("jButton1");
}
} catch (Exception e) {
e.printStackTrace();
}
}
class listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==jButton1)
{
JButton jb=new JButton(""+i);
jb.addActionListener(new relistener());
thisPanel.add(jb);
thisPanel.updateUI();
i++;
}
}
}
class relistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
thisPanel.remove((JButton)e.getSource());
thisPanel.updateUI();
}
}
}