将自定义JLabel添加到JScrollpane

时间:2017-02-03 08:34:04

标签: java swing jlabel jscrollpane

我正在创建一个允许用户创建自定义类型的攻击树的应用程序。将节点添加到树中时,它们将绘制在标签上。只要在树的同一级别上存在一定量的节点,它们就不再适合标签。我将标签添加到滚动窗格中,并假设一旦我尝试在标签边缘之外绘制某些东西,滚动条就会出现,唉没有。我怎样才能做到这一点?

以下是我实例化框架的方法:

    public ApplicationFrame() {
    super("Attack Tree GUI");

    tree = new AttackTree();
    rootNode = tree.getRoot();

    PageView label1 = new PageView(rootNode, tree);
    this.view = label1;

    JPanel contentPane = new JPanel(new BorderLayout());
    JScrollPane scrollPane = new JScrollPane(label1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    scrollPane.setViewportView(label1);

    contentPane.add(BorderLayout.NORTH, getToolBar());
    contentPane.add(BorderLayout.CENTER, scrollPane);
    contentPane.setPreferredSize(new Dimension(1100, 900));

    setContentPane(contentPane);

    pack();
}

以下是PageView类的代码:

public class PageView extends JLabel implements AttackTreeListener{

protected AttackTreeNode rootNode;
protected AttackTree tree;

public PageView(AttackTreeNode rootNode, AttackTree tree){
    this.rootNode = rootNode;
    this.tree = tree;
    rootNode.addListener(this);
    tree.addListener(this);
}

public void paintComponent(Graphics g) {

    Graphics2D g2d = (Graphics2D)g; 

    // paints the page background
    g2d.setColor(Color.white);
    g2d.fillRect(0, 0, getWidth(), getHeight());
    // paints the page frame
    g2d.setColor(Color.black);
    g2d.drawRect(0, 0, getWidth(), getHeight());

    // Paint Nodes
    for(AttackTreeNode atn : tree.getNodes()) {
        paintTreeNode(atn, g2d);
    }

    // Paint Connections
    for(AttackTreeNode atn : tree.getNodes()) {
        if (!(atn.getChildren().isEmpty())){
            paintConnection(atn, g2d);
        }
    }
}

0 个答案:

没有答案