好吧,我有一個名爲AppMain的類,它擴展了JFrame和一個JPanel(稱爲面板),我在其中添加各種JSwing組件(按鈕,標籤,分隔符),用戶可以按各種操作。一個這樣的動作是(在運行時)添加一個帶有各種JSpinners和TextAreas的整個JPanel。這些細節在一個名爲PlayerCharacter的類中擴展了JPanel。當你創建很多面板時,你會用完垂直空間並且不會自動創建滾動條。我的問題是如何添加滾動條。我嘗試製作一個ScrollPane,在其中放置第二個面板。向JPanel添加垂直滾動功能
代碼看起來有點像這樣:
public class AppMain extends JFrame {
public static void main(String[] args) {
new AppMain();
}
private static JPanel panel = new JPanel();
private static JPanel contentPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane(contentPanel);
JButton addPlayerButton = new JButton("Add player");
AppMain() {
super("window name");
setSize(1200, 750);
setLocation(250, 50);
panel.setLayout(null);
contentPanel.setLayout(null);
addPlayerButton.setBounds(5, 5, 150, 40);
contentPanel.setBounds(5, 10, 1100, 750);
scrollPane.setBounds(5, 10, 1100, 750);
panel.add(addPlayerButton);
panel.add(scrollPane);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
interfaceControls();
}
public void interfaceControls() {
addPlayerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 8; i++){
JLabel tmpLabel = new JLabel("text " + i);
tmpLabel.setBounds(5, (100 + (100 * i)), 100, 100);
contentPanel.add(tmpLabel);
contentPanel.revalidate();
contentPanel.repaint();
}
}
});
}
});
}
}
編輯:對於那些想知道,工程代碼:
public class AppMain extends JFrame {
public static void main(String[] args) {
new AppMain();
}
private static JPanel panel = new JPanel();
JPanel topPanel = new JPanel();
JPanel contentPanel = new JPanel();
JButton addPlayerButton = new JButton("Add player");
AppMain() {
super("window name");
setSize(1200, 750);
setLocation(250, 50);
JScrollPane scrollPanel = new JScrollPane(contentPanel);
panel.setLayout(new BorderLayout());
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
panel.add(addPlayerButton, BorderLayout.PAGE_START);
panel.add(scrollPanel, BorderLayout.CENTER);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
interfaceControls();
}
public void interfaceControls() {
addPlayerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 8; i++){
JButton dynamicButton = new JButton("text " + i);
contentPanel.add(dynamicButton);
contentPanel.revalidate();
contentPanel.repaint();
}
}
});
}
});
}
}
最好的辦法是提供一個能夠重現問題的[mcve](http://stackoverflow.com/help/mcve)。 –