所以我制作了一個程式,通過單擊按鈕動態更新 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());
}
}
}
uj5u.com熱心網友回復:
不要使用空布局。
布局管理器的作業是確定組件的大小/位置。只有當面板的首選大小大于滾動窗格的大小時,滾動窗格的滾動條才會出現。
不要將面板添加到框架中
面板是滾動窗格的子組件。面板必須添加到滾動窗格的視窗中,并且滾動窗格必須添加到框架中。
您可以使用以下任一方法將面板添加到視口:
JScrollPane pane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
或者
panel.setViewportView( panel );
閱讀Swing 教程以了解 Swing 基礎知識。有關于“布局管理器”和“如何使用滾動窗格”的部分,其中包含更多資訊和示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374388.html
標籤:爪哇 摇摆 框架 面板 jscrollpane
上一篇:當我嘗試在JPanel的背景上添加影像時出現<<errorjavax.imageio.IIOException:Can'treadinputfile!>>
下一篇:我可以使用多個網格嗎?
