JPanel的边界使JLabel消失

时间:2015-07-31 14:30:29

标签: java swing jpanel jlabel

有一个框架。 BoxLayout在该框架中有一个面板。在该面板中有一个ScrollPane。 ScrollPane中有另一个使用SpringLayout的面板。内部面板中有一个标签。

这是一段代码:

package test;


import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;


class MainPanel extends JPanel {    
    MainPanel() {        
        JPanel panel = new JPanel();

        BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
        panel.setLayout(boxLayout);

        panel.setBorder(BorderFactory.createLineBorder(Color.black));

        JPanel innerPanel = new JPanel();
        SpringLayout springLayout = new SpringLayout();
        innerPanel.setLayout(springLayout);

        JLabel label = new JLabel("test");            
        innerPanel.add(label);

        springLayout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, innerPanel);  
        springLayout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, innerPanel);  

        //innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
        innerPanel.setPreferredSize(new Dimension(300, 100));

        panel.add(innerPanel);    

        JScrollPane scrollPane = new JScrollPane(panel);  
        this.add(scrollPane);
    }
}


class MainFrame extends JFrame {
    MainFrame() {        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(new MainPanel());        

        this.pack();
        this.setVisible(true);   
    }
}


public class Test {
    public static void main(String[] args) {        
        SwingUtilities.invokeLater(new Runnable() {            
            @Override
            public void run() {                
                new MainFrame();                
            }
        });        
    }
}

标签“test”按预期可见。但是当我向内部面板添加边框(取消注释该线,见下文)时,标签就会消失。

//innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));

有人可以解释为什么吗?

0 个答案:

没有答案