【问题标题】:JPanel's border make JLabel disappearJPanel 的边框让 JLabel 消失
【发布时间】:2015-10-23 06:45:01
【问题描述】:

有一个框架。该框架中有一个带有 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));

有人可以解释为什么吗?

【问题讨论】:

  • 我认为有罪的是SpringLayout,因为我试图将FlowLayout设置为innerPanel的布局并显示Jlabel。
  • 我没有足够的时间来分析这个,但我发现了一个类似的问题(可能有类似的一段代码)。我希望它会有所帮助:oracle.developer-works.com/article/5332647/…

标签: java swing jpanel jlabel


【解决方案1】:

尝试改变

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

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

我希望这就是你的本意,它解决了你的问题 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2016-08-03
    • 2014-08-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    相关资源
    最近更新 更多