如何在JFrame / JPanel中显示列表并在按钮点击后刷新它?

时间:2016-12-28 21:27:46

标签: java arraylist jframe jpanel jbutton

我不知道如何在JFrame中逐个显示我的对象列表(无论参数如何)。我想用循环来做它。我想在点击按钮等后显示前10个元素和接下来的10个元素。任何想法?

1 个答案:

答案 0 :(得分:0)

我认为这对我不起作用...我已经在JList中添加了一个列表到JPanel,按钮点击后它会刷新,但是当我点击实际显示JList元素时它们会回到第一个一些 - 到开头...(repaint()命令被注释,因为有了它我没有看到我的JList的任何变化)。当remove()和revalidate()命令也被注释时,我有这些相同的效果......所以我不知道问题出在哪里......

public Window()
{
    setTitle("Window");
    setSize(600,600);
    setResizable(false);
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    JList<?> list = new JList<Object>(tmp_list.toArray());
    listPanel = new JPanel();
    listPanel.setLayout(new BorderLayout());
    listPanel.add(new JScrollPane(list));
    add(listPanel, BorderLayout.CENTER);

    nextButton = new JButton("Next");
    buttonsPanel = new JPanel();
    buttonsPanel.setLayout(new FlowLayout());
    buttonsPanel.add(nextButton);
    add(buttonsPanel, BorderLayout.SOUTH);
    nextButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{   
    Object source = e.getSource();

    if(source == nextButton)
    {
        if(current_page < last_page)
        {
            current_page++;
            refreshListPanel();
        }
    }
}

private void refreshListPanel()
{
    listPanel.removeAll();
    tmp_list = showCurrentPage(N, cars1);
    JList<?> list = new JList<Object>(tmp_list.toArray());
    listPanel.add(new JScrollPane(list));
    listPanel.revalidate();
    listPanel.repaint();
}

private List<Car> showCurrentPage(int n, List<Car> main_list)
{
    List<Car> list = new ArrayList<Car>();
    int counter = n*(current_page);
    int size;
    if(current_page == last_page && C%N != 0)
        size = main_list.size()%n;
    else
        size = n;

    for(int i = 0; i < size; i++)
    {
        list.add(main_list.get(counter + i));
    }
    return list;
}