重新绘制内容窗格

时间:2016-07-17 07:02:07

标签: java swing scroll jpanel jscrollpane

我有一个JScrollPane,其中包含JPanel,其中显示的内容类似于时间表。此时间表面板可以缩放和可滚动。我在这个时间表面板中有很多条目,每个条目都是一个自己的面板,并且有一个开始时间和一个长度。

当我现在点击此时间表中的条目时,我想放大这个条目,当然,转移到它。

例如:实际缩放显示从1月到3月的3个月。现在我在3月1日到3月3日有一个参赛作品。此条目现在例如是10像素长。 Wren我点击此条目,缩放系数以这种方式改变,时间表仅显示3天并从3月1日开始,因此条目宽度超过完整的滚动窗格视图端口。

为此,我计算时间表面板的新缩放系数和新的“开始X位置”,并调用面板的重新绘制。

这适用于缩放,但由于时间表面板此时没有新的宽度,因此滚动窗格滚动条没有新的大小。所以我无法在此代码点设置新的滚动条位置。

那么,如何在完成滚动窗格的重绘并且滚动条具有新尺寸后,如何设置正确的滚动条位置

这里有一些用于mor理解的伪代码(抱歉格式化但我没有设法粘贴代码以便缩进正确):

public class MyRootPanel extends JPanel
{
TimeSheetPanel tsPanel = new TimeSheetPanel(this);
tsPanel.setLayout(null);

scrollPanel=new JScrollPane(tsPanel,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.add(scrollPanel);

public setScrollPos(int xPos)
{
    scrollPanel.getHorizontalScrollBar().setValue(xPos);
}
}

public class TimeSheetPanel extends JPanel
{
MyRootPanel rootPanel;

public int pixelPerHour = 5; // Zoom factor
public int rowHeight = 30; // height of one row on table

public TimeSheetPanel(MyRootPanel root)
{
    rootPanel = root;

    this.setLayout(null);
    setBounds(0,0, maxDays * pixelPerHour *24, maxrows * rowHeight);

    for(Entry e : entryList)
    {
        EntryPanel entryPanel = new EntryPanel(this, entry);
        this.add(entryPanel);
    }
}

public void zoomToEntry(Entry entry)
{
    // calc new zoom factor here.
    pixelPerHour = ......
    newXPos = .....
    // and set it to the panel
    setBounds(0,0, maxDays * pixelPerHour *24, maxrows * rowHeight);
    // call repaint
    repaint();
    // THIS WILL NOT WORK
    rootPanel.setScrollPos(newXPos);
}

}

public class EntryPanel extends JPanel
{
TimeSheetPanel parentPanel;
Entry entry;

public EntryPanel(TimeSheetPanel parent, Entry e)
{
    parentPanel = parent;
    Entry = e;

    this.setLayout(null);

    int left = entry.start * parentPanel.pixelPreHour;
    int width = entry.length * parentPanel.pixelPerHour;
    int top = entry.row * parentPanel.rowHeight;
    int height = parentPanel.rowHeight;

    setBounds(left, top, width, height);

    addMouseListener(this);

}

@Override
public void mouseClicked(MouseEvent e)
{
    if (e.getClickCount() == 2)  
    {
        parentPanel.zoomToEntry(entry);
    }
}
}

1 个答案:

答案 0 :(得分:0)

对于搜索答案的人,我使用invokeLater解决了我的问题

    repaint();
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run() 
        {
            valuePanelScrollPane.getHorizontalScrollBar().setValue(xpos);
            valuePanelScrollPane.getVerticalScrollBar().setValue(ypos);
        }
    });