如何在Java中使JPanel可滚动?

时间:2017-01-03 11:59:07

标签: java jpanel scrollable

我有一个扩展JPanel的类,我已经覆盖了paintComponent(Graphics g)方法。但是,我无法看到我绘制的矩形或滚动条。

在main函数中,我有以下代码:

    MyClass mainPanel = new MyClass();
    mainPanel.setPreferredSize(new Dimension(1000, 1000));
    mainPanel.setLayout(new BorderLayout());

    JPanel scrollPanel = new JPanel();
    scrollPanel.setSize(new Dimension(2000, 2000));       
    JScrollPane scrollPane = new JScrollPane(scrollPanel,  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  //Let all scrollPanel has scroll bars
    scrollPane.setViewportView(scrollPanel);
    scrollPane.setOpaque(true);

    scrollPanel.revalidate();
    mainPanel.add(scrollPane);


    JFrame frame = new JFrame("Scrollable Panel");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(mainPanel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);  

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。 MyClass扩展了JPanel。我已经覆盖了paintComponent(Graphics g)方法,我通过Graphics绘制矩形。

  A        B             c
1 Name     Surname       Weight
2 Pete     Smith         91
3 Pete     Johnson       81
相关问题