滚动区域的例子
2008-01-05 09:50:26 来源:WEB开发网核心提示:程序代码:import javax.swing.*;import java.awt.*;import java.awt.event.*; public class ViewportTest extends JPanel implements ActionListener{PRivate JViewport viewpo
程序代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ViewportTest extends JPanel implements ActionListener
{
PRivate JViewport viewport; /* 视区类, 滚动区域是建立在可见视区滚动的基础上 */
private JPanel scrollPane; /* 滚动容器, 存放所有(包括当前不可见)构件 */
private JButton left,right; /* 左右按钮, 完成左右滚动视区的功能 */
public ViewportTest() {
viewport = new JViewport();
setLayout(new BorderLayout());
left = new JButton("<");
right = new JButton(">");
left.addActionListener(this);
right.addActionListener(this); // 设置左右按钮的事件监听
scrollPane = new JPanel(new FlowLayout());
for(int i=0; i<10; i++)
scrollPane.add(new JButton("BTn"+String.valueOf(i) )); // 假设有10个按钮, 只能看到其中几个
viewport.add(scrollPane,null);
add(left,BorderLayout.WEST);
add(right,BorderLayout.EAST);
add(viewport, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{
Rectangle curRect = viewport.getVisibleRect(); // 取得当前视区范围
if(e.getSource().equals(left))
curRect.setLocation(curRect.getLocation().x - 10, curRect.getLocation().y); // 设置范围移动
if(e.getSource().equals(right))
curRect.setLocation(curRect.getLocation().x + 10, curRect.getLocation().y);
viewport.scrollRectToVisible(curRect); // 更新视区
}
/*- TEST CODE -*/
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,60);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new ViewportTest(),BorderLayout.CENTER);
frame.show();
}
}
[]
赞助商链接