想通过java jpanel数组创建像facebook post这样的卡片视图

时间:2017-01-26 14:57:02

标签: java arrays swing user-interface awt

我想使用jpanel数组创建卡片视图,但代码如下:

这与我想在gui上创建它的网站上的facebook帖子相同

你也可以建议我使用其他技术来执行相同的操作,这将是一个很大的帮助。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;

public class test extends JFrame {

    private JPanel contentPane;

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

public test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 587, 391);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    JPanel[] pan = new JPanel[5];
    int j= 0;
    for(int i= 0;i<5;i++)
    {
        pan[i].setBounds(28, 22+j, 522, 149);
        contentPane.add(pan[i]);
        pan[i].setVisible(true);    
        j= j+160;

    }


}
}

错误

at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

1 个答案:

答案 0 :(得分:1)

您需要初始化面板

for(int i= 0;i<5;i++)
{
    pan[i] = new JPanel(); // this line missing
    pan[i].setBounds(28, 22+j, 522, 149);
    contentPane.add(pan[i]);
    pan[i].setVisible(true); // not required
    pan[i].setBorder(new LineBorder(Color.BLACK)); // to see bounds of your panels
    j= j+160;
}