每次添加容器时都可以增加面板长度吗?

时间:2017-05-20 02:10:39

标签: java swing panel

我目前正在设计一个GUI分配规划器。我一直遇到一些问题。对于我的程序的一部分,我有一个面板来保存仍需要完成的作业。我想要创建的是一个面板,它将向面板添加容器(保持组件以显示分配)。但是,我能想到这样做的唯一方法是每次添加容器时都要加长面板。不幸的是,据我们所知,这是不可能的,因为面板在创建时被赋予了定义的宽度和深度。理想情况下,如果可能的话,我想在每次添加容器时增加面板长度。滚动条会向下滚动面板。

这可能吗?我是以正确的方式接近这个吗?我是GUI的新手,所以我愿意接受改进和建议。如果有人希望我发布我的代码到目前为止,我会。 (当心,此刻它的形状非常粗糙)

以下是我想要做的草稿:

enter image description here

TIA

到目前为止,这是我的大部分代码。问题是,一旦我添加了一定数量的容器,它就会开始变小。我只想在每次添加容器时扩展它。大多数评论都是针对文档或提醒做某事。

import javax.swing.*;
import java.awt.*;
//import java.util.ArrayList;

public class MyWindow
{
    private final JFrame frame = new JFrame();
    private final int WINDOW_WIDTH = 500, WINDOW_DEPTH = 500;
    private JPanel panel;
    private JPanel toDoList, completed;
    //ArrayList<JFrame> frame = new ArrayList<>();

    public MyWindow()
    {
        frame.setTitle("Assignment Planner");
        this.contents();
    }

    private void contents()
    {//use an arraylist to create containers    ArrayList<JPanel> container = new ArrayList<>();
        frame.setSize(WINDOW_WIDTH, WINDOW_DEPTH);
        panel = new JPanel(new GridLayout(2, 1));

        toDoList = new JPanel();
        toDoList.setLayout(new /*GridLayout(0,1,5,5)*/BoxLayout(toDoList, BoxLayout.PAGE_AXIS));
        toDoList.setPreferredSize(new Dimension(250, 250));
        panel.add(toDoList);

        completed = new JPanel();
        //panelCompleted.setLayout(new GridLayout(0, 1)); //fix like one above

        panel.add(completed);

        JScrollPane scroll = new JScrollPane(toDoList); 
        panel.add(scroll);                                      //scroll panes for both panels
        JScrollPane scroll2 = new JScrollPane(completed);
        panel.add(scroll2);

        toDoList.add(assignment());
        toDoList.add(Box.createRigidArea(new Dimension(0,1)));
        toDoList.add(assignment());
        toDoList.add(Box.createRigidArea(new Dimension(0,1)));
        toDoList.add(assignment());
        toDoList.add(Box.createRigidArea(new Dimension(0,1)));
        beginningScrollPaneValue += 110;
        toDoList.setPreferredSize(new Dimension(250, beginningScrollPaneValue));
        toDoList.revalidate(); //scroll.revalidate();
        toDoList.repaint(); //scroll.repaint();

        frame.getContentPane().add(panel, BorderLayout.CENTER);//add the panel in the JFrame's content pane in the center
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    JPanel assignment()
    {
        JPanel container = new JPanel(new GridBagLayout());
        container.setMaximumSize(new Dimension(500,100));
        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 0.5;

        JCheckBox cb = new JCheckBox();
        c.fill = GridBagConstraints.NONE;
        c.gridx = 1;
        c.gridy = 0;
        container.add(cb, c);
        container.setBackground(Color.red);//does no fill area behind checkbox

        return container;
    }
}

0 个答案:

没有答案