有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jpanel Java向ScrollPane中嵌入的面板添加JLabel

JScrollPane scrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(23, 11, 603, 123);

contentPane.add(scrollPane);

JPanel panel = new JPanel();
JLabel[] labels=new JLabel[callout.getRedCount()]; //callout.getRedCount() = 8
panel.setLayout(null);
int x = 50;
int y = 50;
for (int i=0;i<callout.getRedCount();i++){ //callout.getRedCount() = 8
        labels[i]=new JLabel("Red" + i);
        labels[i].setBounds(x, y, 32, 32);
        panel.add(labels[i]);
        x += 150;
}
scrollPane.setViewportView(panel);

我试图将这些标签添加到嵌入在scrollPane中的面板中。标签显示正确,但最后几个超过面板大小时除外。scrollPane不会滚动。我尝试了各种不同的布局,但仍然没有结果。我是否遗漏了一些关于如何做到这一点的信息


共 (1) 个答案

  1. # 1 楼答案

    好的,我用GridBagLayout做了这个

    public static void main(String args[]){
    
        JFrame contentPane = new JFrame();
    
        JScrollPane scrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(23, 11, 50, 50);
    
        contentPane.add(scrollPane);
    
        JPanel panel = new JPanel();
        JLabel[] labels=new JLabel[8]; //callout.getRedCount() = 8
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(0,10,0,0);
        int x = 50;
        int y = 50;
        for (int i=0;i<8;i++){ //callout.getRedCount() = 8
                labels[i]=new JLabel("Red" + i);
                gbc.gridx = i;
                panel.add(labels[i], gbc);
        }
        scrollPane.setViewportView(panel);
        contentPane.setSize(50,50);
        contentPane.setVisible(true);
    
    }
    

    您可以改变周围的值,这是非常粗糙的。希望这有帮助