JPanel的数组未添加到JScrollPane

时间:2016-03-05 09:53:36

标签: java swing

在我的buildBar(....)方法中,我有一个Panel,我在其中添加了一个JScrollPane(scroll_pane)。在JScollPane内部,我添加了一个JPanel数组,但没有显示任何面板

class MyFrame extends JFrame {

    private JPanel contentPane;
    JPanel panel;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
           public void run() {
                try {
                    MyFrame frame = new MyFrame();
                    frame.setVisible(true);
               } catch (Exception e) {
                    e.printStackTrace();
                }
            }
       });
    }

    public MyFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        panel = new JPanel();
        panel.setBounds(42, 41, 319, 161);
        contentPane.add(panel);
        panel.setLayout(null);

        buildBar(3,124,85,100,100);
    }

    JPanel[] myPanel;
    private void buildBar(int no_of_bars, int prev_x, int prev_y, int width,            int height){
        JScrollPane scroll_pane = new JScrollPane();
        scroll_pane.setBounds(124, 85, 2, 2);
        myPanel = new JPanel[no_of_bars];
        for(int i=0; i<no_of_bars; i++){
            myPanel[i] = new JPanel();
            myPanel[i].setBounds(prev_x,prev_y,width,height);
            myPanel[i].setBackground(new Color(255,0,0));
            prev_x = prev_x + width + 10;
            scroll_pane.add(myPanel[i]);
        }
        panel.setLayout(new BorderLayout());
        panel.add(scroll_pane,BorderLayout.CENTER);
        panel.revalidate();
        panel.repaint();
    }

}

当我运行上面的代码时,我得到的是面板底部和右侧边缘的红色线条

0 个答案:

没有答案