2017-01-03 3 views
-2

JPanelを拡張するクラスがあります。ここではpaintComponent(Graphics g)メソッドをオーバーライドしています。しかし、私が描いた長方形やスクロールバーは見えません。私はこの問題を解決したJPanelをJavaでスクロール可能にするには?

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); 
+0

あなた – AxelH

+2

は 'scrollPanel.setPreferredSize(新しい次元(2000、2000を試してみてください[公式ガイド](https://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html)を読みました)); '。現在あなたの 'scrollPanel'は何も縮小していないので、' scrollPane'はスクロールバーを表示する必要はありません。 – khelwood

+1

@ NimrodArgov、彼のコードを読んで、彼は1つ持っています。 – AxelH

答えて

0

:私は下に次のコードを持っている主な機能には

。 MyClassはJPanelを拡張します。そして、GraphicsComponent(Graphics g)メソッドを上書きして、Graphicsを介して長方形を描画します。

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

JScrollPane scrollPane = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); //Let all scrollPanel has scroll bars 
scrollPane.setPreferredSize(new Dimension(1000, 900)); 


JFrame frame = new JFrame("Scrollable JPanel"); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.add(scrollPane); 
frame.setSize(1000, 900); 
frame.pack(); 
frame.setLocationRelativeTo(null); 
frame.setVisible(true); 
関連する問題