如何使它在JScrollPane中放入可动态调整大小的JPanel时工作



所以我制作了一个程序,通过单击按钮动态更新JPanel的大小,并将更新后的面板添加到JScrollPane中。但我不太清楚这段代码中的错误。单击按钮后面板将消失,而不是调整大小并放入滚动窗格中。非常感谢您的帮助,因为我是Swing的新手。

代码(希望我做得对(:-


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Frame extends JFrame implements ActionListener{
int scrollBarSize;
JButton button;
JPanel buttonPanel;
JPanel panel = new JPanel();
JScrollPane pane = new JScrollPane( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JTextField text;

int bigPanelPos = 495, bigPanelSize = 55 , smallPanelPos;
Frame(){
this.setSize(700,700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLayout(null);
scrollBarSize = ((Integer)UIManager.get("ScrollBar.width")) + 1;
pane.setBounds(0,0,700,550);

panel.setBackground(Color.yellow);
panel.setBounds(0,495,700,55);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setAlignmentY(Component.CENTER_ALIGNMENT);
button = new JButton("Click me!");
button.setPreferredSize(new Dimension(50,15));
button.setFont(new Font("Didot",Font.BOLD, 15));
button.addActionListener(this);

buttonPanel = new JPanel();
//      buttonPanel.setPreferredSize(new Dimension(700, 150));
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.setAlignmentY(Component.CENTER_ALIGNMENT);
buttonPanel.setBorder(BorderFactory.createTitledBorder("ButtonPanel"));
buttonPanel.setBounds(0, 550, 700, 150 );
buttonPanel.add(button);

this.add(panel);
this.add(buttonPanel);
this.setVisible(true);

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == button) {

bigPanelPos -= 55;
bigPanelSize +=55;

int n = scrollBarSize;
panel.setPreferredSize(new Dimension(700 - n,bigPanelSize));
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setAlignmentY(Component.CENTER_ALIGNMENT);
panel.revalidate();
pane.add(panel);
pane.revalidate();
this.add(pane);
//          this.add(panel);
System.out.println(pane.getBounds());
System.out.println(panel.getBounds());

}

}

}

不要使用null布局

布局管理员的工作是确定组件的大小/位置。只有当面板的首选大小大于滚动窗格的大小时,滚动窗格的滚动条才会出现。

不要将面板添加到框架

该面板是滚动窗格的子组件。面板必须添加到滚动窗格的视图中,滚动窗格必须添加到框架中。

您可以使用以下任一项将面板添加到视口:

JScrollPane pane = new JScrollPane(panel,  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

panel.setViewportView( panel );

阅读Swing教程中的Swing基础知识。有关于";布局管理器";以及";如何使用滚动窗格";提供更多信息和示例。

最新更新