面板覆盖了JScrollPane中的自身

时间:2017-02-12 17:41:58

标签: java swing

我的问题很难解释。首先,我有:

  • JPanel(leftPanel)
  • 一个JScrollPane(lBar),用于滚动leftPanel( - > new JScrollPane(leftPanel))
  • 每次点击时在左侧面板中添加新面板的按钮

结果如下: https://www.youtube.com/watch?v=VFXwh_vofQI

有两个问题:

  • 点击4或5次,面板自我覆盖(奇怪) (次级)
  • 我希望按钮+面板看起来更好(相反 一个大中心按钮)

我使用的代码:

ActionsPanel panel = new ActionsPanel();
JScrollPane lBar = new JScrollPane(leftPanel);
lBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

ActionsPanel类:

public class ActionsPanel extends JPanel
{
    private JButton newAction;

    public ActionsPanel(final Editor editor)
    {
        this.newAction = new JButton("New");
        this.newAction.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                getActions().add(new Action());
                refresh();
            }
        });

        setLayout(new GridLayout(0, 1));
        refresh();
    }

    public void refresh()
    {
        removeAll();
        add(newAction);

        for (Action action : getActions())
        {
            ActionPanel panel = new ActionPanel(action);
            panel.revalidate();
            panel.repaint();
            add(panel);
        }

        revalidate();
    }
}

ActionPanel类:

public class ActionPanel extends JPanel
{
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D graphics = (Graphics2D) g;

        setSize(getWidth(), 100);
        setLayout(new GridLayout(2, 1));

        graphics.setColor(Color.GRAY);
        graphics.drawRect(0, 0, getWidth(), getHeight());
        graphics.setColor(Color.BLACK);
        graphics.setStroke(new BasicStroke(2));
        graphics.drawRect(0, 0, getWidth(), getHeight());
        graphics.drawString("Ordinal : " + getOrdinal(), 5, 15);
    }
}

0 个答案:

没有答案