java中scrollpane的意思_Java中的JScrollPane

bd96500e110b49cbb3cd949968f18be7.png

I wrote a little code to see how the scroll Pane functions but my code never worked.

here's the code,

public Fenetre(){

this.setTitle("Data Simulator");

this.setSize(300, 300);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setLocationRelativeTo(null);

String hello = "hello";

int number = 69;

JPanel content = new JPanel();

content.setBackground(Color.LIGHT_GRAY);

//Box imad = Box.createHorizontalBox();

JTextArea textArea = new JTextArea(10, 10);

JLabel imad = new JLabel();

imad.setText(hello + " your favorite number is " + number + "\nRight?");

JScrollPane scrollPane = new JScrollPane();

setPreferredSize(new Dimension(450, 110));

scrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_ALWAYS);

scrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);

scrollPane.setEnabled(true);

scrollPane.setWheelScrollingEnabled(true);

scrollPane.setViewportView(textArea);

scrollPane.setViewportView(imad);

add(scrollPane, BorderLayout.CENTER);

//---------------------------------------------

//On ajoute le conteneur

scrollPane.add(textArea);

scrollPane.add(imad);

content.add(textArea);

content.add(imad);

content.add(scrollPane);

this.setContentPane(content);

this.setVisible(true);

this.setResizable(false);

}

When I run it, I get a little window with the textArea and next to the text area a very little white square, which is the scrollpane i suppose because when I remove it from the code, this square disappears. When I write in the text area and exceed the window's dimension, I can't scroll vertically using the mouse wheel, and not horizontally at all. I saw many examples on internet and I can't understand why my code doesn't work??

Any help explaining how scrollpane works?

解决方案scrollPane.setViewportView(textArea);

scrollPane.setViewportView(imad);

Only one component can be added to the viewport of the scroll pane, so the label replaces the text area.

content.add(textArea);

content.add(imad);

A component can only have a single parent. The above code removes the label from the scrollpane, so nothing is now in the scrollpane.

Try something like:

JScrollPane = new JScrollPane( textArea );

JPanel content = new JPanel( new BorderLayout() );

content.add(scrollPane, BorderLayout.CENTER);

content.add(imad, BorderLayout.PAGE_END);

setContentPane( content );

For a better solution, start with the working example found in the Swing tutorial on How to Use Text Areas and then modify the code. This way you will start with a better structured program that follows Swing standards.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值