2014-07-14 38 views
0

我有與矩形網格,我將填補其值。但是,根據輸入的格子可能會很大,所以我想爲圖像添加一個滾動條選項。下面的代碼似乎沒有做我想要的東西?任何幫助表示讚賞。添加滾動條的JFrame電網

class Cube extends JComponent 
    { 
public void paint(Graphics g) 
{ 

    for (int i = 0; i < 10; i++) 
    { 
     for (int j = 0; j < 10; j++) 
     { 
      g.setColor(Color.GRAY); 
      g.fillRect(i*40, j*40, 40, 40); 
     } 
    } 

    for (int i = 0; i < 50; i++) 
    { 
     for (int j = 0; j < 50; j++) 
     { 
      g.setColor(Color.BLACK); 
      g.drawRect(i*40, j*40, 40, 40); 
     } 
    } 

} 
public static void main(String[] a) 
{ 
    // CREATE SCROLLBAR 
    JScrollPane scroller = new JScrollPane(); 
    JFrame window = new JFrame(); 
    window.setSize(200,200); 
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    window.getContentPane().add(new Cube()); 
    //ADD THE SCROLLBAR 
    window.getContentPane().add(scroller, BorderLayout.CENTER); 
    window.setVisible(true); 
} 

}

回答

2

一些提示:

  1. 您需要添加立方體滾動窗格。您可能會發現this tutorial about scrollpane有幫助。
  2. You should use event dispatcher thread when using swing.

我下面重寫程序。

class Cube extends JComponent 
{ 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     for (int i = 0; i < 10; i++) 
     { 
      for (int j = 0; j < 10; j++) 
      { 
       g.setColor(Color.GRAY); 
       g.fillRect(i*40, j*40, 40, 40); 
      } 
     } 

     for (int i = 0; i < 50; i++) 
     { 
      for (int j = 0; j < 50; j++) 
      { 
       g.setColor(Color.BLACK); 
       g.drawRect(i*40, j*40, 40, 40); 
      } 
     } 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(1000, 1000); 
    } 

    public static void main(String[] a){ 
     // use event dispatcher thread 
     EventQueue.invokeLater(
      new Runnable() { 
       public void run() { 
        Cube cube = new Cube(); 
        JScrollPane scroller = new JScrollPane(cube); 
        JFrame window = new JFrame(); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        // set the content pane 
        window.setContentPane(scroller); 
        window.pack(); 
        window.setVisible(true); 
       } 
     }); 
    } 
} 
+2

JComponent中具有的paintComponent,第一代碼線應super.paintComponent方法,前覆蓋的getPreferredSize類立方體的內部,然後除去cube.setPreferredSize(新尺寸(1000,1000)),和調用JFrame.pack() window.setVisible(真); – mKorbel

+0

是的,你是對的@mKorbel。我編輯了我的答案。謝謝。 – ThomasEdwin