我扩展了 JScrollPane 并向其添加了几个组件。当我将滚动窗格添加到 JFrame 时,不会显示任何组件。如果我的类扩展,例如 JPanel,然后我将它添加到独立的 JScrollPane,一切正常。我无法理解这种行为。谁能解释一下,为什么会这样?
以下是两种变体(一种有效,一种无效):
此变体不起作用:
public class MainScrollPanel extends JScrollPane {
private JPanel verticalPanel;
public MainScrollPanel() throws IOException, ParseException {
initGUI();
readData();
}
private void initGUI() {
verticalPanel = new JPanel();
verticalPanel.setLayout(new BoxLayout(verticalPanel, BoxLayout.Y_AXIS));
add(verticalPanel);
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
private void readData() throws IOException, ParseException {
//read data
//...
for(NewData message : messages) {
verticalPanel.add(new JLabel(message.getMessage()));
}
}
}
public class MainGUI extends JFrame {
private MainScrollPanel mainPanel;
public MainGUI() throws IOException, ParseException {
super("Scroll app");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainPanel = new MainScrollPanel();
getContentPane().add(mainPanel);
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) throws IOException, ParseException {
new MainGUI();
}
}
这个工作正常:
public class MainScrollPanel extends JPanel {
public MainScrollPanel() throws IOException, ParseException {
initGUI();
readData();
}
private void initGUI() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
private void readData() throws IOException, ParseException {
//The same as in previous example
}
}
public class MainGUI extends JFrame {
private MainScrollPanel mainPanel;
public MainGUI() throws IOException, ParseException {
//...
JScrollPane scrollPane = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(scrollPane);
//...
}
}