将Jpanel添加滚动条,无法动态使JPanel变大
这段程序本意是想点击按钮,让panel变大,然后出现滚动条Java code
public class MyFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JButton button;
public MyFrame()
{
setSize(new Dimension(400,300));
setLayout(new BorderLayout());
panel=new JPanel();
JScrollPane js=new JScrollPane(panel);
panel.setBackground(Color.RED);
getContentPane().add(js,BorderLayout.NORTH);
button=new JButton("点击变大");
button.setSize(100, 50);
add(button,BorderLayout.SOUTH);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
int x=MyFrame.this.getPanel().getWidth();
int y=MyFrame.this.getPanel().getHeight()+20;
MyFrame.this.getPanel().setSize(x, y);
MyFrame.this.repaint();
}
});
getContentPane().add(button,BorderLayout.SOUTH);
setVisible(true);
}
public JPanel getPanel()
{
return this.panel;
}
public static void main(String[] args)
{
new MyFrame();
}
}
------解决方案--------------------加个JScrollPane,把JPanel放进去
------解决方案--------------------用setPreferredSize(Dimension preferredSize)
------解决方案--------------------
试试这个,应该好了:
public class MyFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JButton button;
public MyFrame()
{
setSize(new Dimension(400,300));
setLayout(new BorderLayout());
panel=new JPanel();
JScrollPane js=new JScrollPane(panel);
panel.setBackground(Color.RED);
// js.setPreferredSize(new Dimension(100,80));
getContentPane().add(js,BorderLayout.CENTER);
button=new JButton("Zoom in");
add(button,BorderLayout.SOUTH);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
int x=MyFrame.this.getPanel().getWidth();
int y=MyFrame.this.getPanel().getHeight()+20;
getPanel().setPreferredSize(new Dimension(x, y));
getPanel().setSize(getPanel().getPreferredSize());
//MyFrame.this.repaint();
}
});
getContentPane().add(button,BorderLayout.SOUTH);
setVisible(true);
}
public JPanel getPanel()
{
return this.panel;
}
public static void main(String[] args)
{
new MyFrame();
}
}
------解决方案--------------------还有,记的区别setSize和setPreferredSize。
这里要使用setPreferredSize。 不多说了,请自己去看一下源代码。这些细节的区别文档给出的不多。