【发布时间】:2014-05-12 18:24:51
【问题描述】:
我一直在寻找一种将垂直滚动条添加到JPanel 的方法,该滚动条又添加到CardLayout 面板中。我查看了所有与实现可滚动JPanel 相关的帖子,但我不知道如何使用这个特定的CardLayout 来实现它。 Oracle 也没有给出我可以使用的示例。
也许我没有为JWindow 或我使用的任何其他组件使用正确的配置。
我已将我的程序的精简版本放在我想为其实现垂直滚动条的下方。
我的问题是如何在代码底部实现JPanelScrollable类,使其可以滚动?
import javax.swing.*;
import java.awt.*;
import java.net.URL ;
public class Program2 extends JFrame
{
public Program2()
{
super("Flash CC");
Container2 container = new Container2();
setSize(700, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setFocusable( true ) ;
add(container);
setVisible(true) ;
}
public static void main(String[] args)
{
Program2 prog = new Program2();
}
}
class Container2 extends JPanel
{
private CardLayout cardLayout = new CardLayout() ;
private JPanel1 jPanelFirst = new JPanel1() ;
private JPanel2 jPanelSecond = new JPanel2() ;
private JPanelScrollable jPanelThird = new JPanelScrollable() ;
//Constructor
Container2()
{
this.setLayout( cardLayout ) ;
this.setFocusable( true ) ;
JScrollPane scrollFrame = new JScrollPane(jPanelThird);
this.add( jPanelFirst, "first card" ) ;
this.add( jPanelSecond, "second card" ) ;
this.add( scrollFrame , "third card" ) ;
cardLayout.show( this, "third card" ) ;
}
}
class JPanel1 extends JPanel
{
}
class JPanel2 extends JPanel
{
}
class JPanelScrollable extends JPanel
{
// here many, many, many elemnts will go
// and a vertical scroll barr is needed to view'm all.
JPanelScrollable()
{
this.setOpaque( true ) ;
this.setLayout( null ) ;
for(int i=0; i<30; i++)
{
JButton b = new JButton("Button" + i) ;
b.setBounds(0, (i * 100), 100, 50) ;
this.add(b) ;
}
}
}
【问题讨论】:
标签: java swing user-interface layout cardlayout