您的位置:首页 > 编程语言 > Java开发

JavaSE项目中怎样让JPanel和JScrollPane结合出现自动滚动条,并运用到自己的项目中出现不能正常显示出滚动条的原因

2014-05-07 14:22 459 查看
创建一个java 项目测试,这个是ok的 :

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

public class InvokeTest extends JFrame {

public InvokeTest() {

super("TestJScrollPane");

this.setLayout(null);

this.setBounds(200, 200, 300, 300);

JPanel panel = new JPanel();

panel.setPreferredSize(new Dimension(300,100));//主要是这句代码,设置panel的首选大小,同时保证宽高大于JScrollPane的宽高,这样下面的JScrollPane才会出现滚动条

JButton button1 = new JButton("1");

panel.add(button1);

JButton button2 = new JButton("2");

panel.add(button2);

JButton button3 = new JButton("3");

panel.add(button3);

JButton button4 = new JButton("4");

panel.add(button4);

JButton button5 = new JButton("5");

panel.add(button5);

JButton button6 = new JButton("6");

panel.add(button6);

JButton button7 = new JButton("7");

panel.add(button7);

JScrollPane scrollPane = new JScrollPane(panel);

scrollPane.setBounds(10, 10, 175, 70);

this.getContentPane().add(scrollPane);

this.setVisible(true);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) {

new InvokeTest();

}

};

将上面的思路运用到自己项目中,来滚动显示自己的图片

比如我自定义一个绘图Panel继承JPanel ,起名DrawPanel 或IMagePanel :public class DrawPanel extends JPanel implements MouseMotionListener, MouseListener{

///////各种方法如绘制图片,我就不详细列出了!

};

然后定义一个继承JFrame的类public class MapEdit extends JFrame {

//比如这个地图编辑器

private JScrollPane getMainPanel() {

private JScrollPane mainPanel = null;

private JScrollPane scrollPane= null;

private JPanel getJContentPane() { //布局

if (jContentPane == null) {

jContentPane = new JPanel();

jContentPane.setLayout(new BorderLayout());

jContentPane.add(getJPanel(), BorderLayout.NORTH);

jContentPane.add(getMainPanel(), BorderLayout.CENTER);

}

return jContentPane;

}

if (mainPanel == null) {

this.setLayout(null);

JPanel panel = new DrawPanel(this,Res.tileWidth*Res.tilex, Res.tileHeight*Res.tiley );

panel.setPreferredSize(new Dimension(Res.tileWidth*Res.tilex, Res.tileHeight*Res.tiley));//主要是这句代码,设置panel的首选大小,

scrollPane = new JScrollPane(panel);

scrollPane.setBounds(0,0, 300, 300);

this.getContentPane().add(scrollPane);

this.setVisible(true);

mainPanel =scrollPane;//注意这就是你没有显示出滚动条原因:你返回的应该是你创建的滚动条并应用到布局中,而不是返回绘图的Jpanel,应该是包含了这个绘图的

// 绘图的滚动条:注意 如果返回 mainPanel =panel 就不能正常显示出滚动条了

}

return mainPanel;

}

}

注意:jpanel和jscrollpanel 滚动条在窗口人为拉小或在 DrawPanel中增加一个图片元素后窗口拉小,滚动条消失原因:你可能在DrawPanel中鼠标事件设置了小面这行

public void mouseClicked(MouseEvent arg0) {

this.setPreferredSize(new Dimension(100,300)); -----这不是是缩小了viewPort吗,怎么能显示完全呢,亲??

}

的事件注释或去掉下面这句

// this.setPreferredSize(new Dimension(100,300));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐