2016-07-01 8 views
-1

矩形の色を変更するにはどうすればいいですか?私はそれを黄色に変えたい。 の中にg.setColor(Color.YELLOW);を追加しましたが、矩形の色は変わりません。誰かが間違ったことを私に教えてもらえますか?四角形の色を変更する方法Java GUIで矩形の色を変更する

public class SelectSeat { 

    static JFrame frame; 

    public JPanel createContentPane() throws IOException 
    { 

     JPanel totalGUI = new JPanel(); 
     RectDraw rect= new RectDraw(); 
     rect.setPreferredSize(new Dimension(330,35)); //for size 
     totalGUI.setLayout(null); 
     totalGUI.setBackground(Color.WHITE); 
     totalGUI.add(rect); 
     Dimension d = rect.getPreferredSize(); 
     rect.setBounds(100, 20, d.width, d.height); // for location 
     return totalGUI; 
    } 

     void setVisible(boolean b) { 
     // TODO Auto-generated method stub 

    } 

    static void createAndShowGUI() throws IOException 
    { 

     JFrame.setDefaultLookAndFeelDecorated(true); 
     frame = new JFrame("Seat Selection"); 
     //Create and set up the content pane. 
     SelectSeat demo = new SelectSeat(); 
     frame.setContentPane(demo.createContentPane()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(535, 520); 
     frame.setLocation(500,220); 
     frame.setVisible(true); 
    } 

    private static class RectDraw extends JPanel 
    { 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.setColor(Color.BLUE); 
      g.drawString("Movie Sceen", 130, 20); 
      } 


    } 

} 

enter image description here

+0

'g.setColor(Color.YELLOW);を追加しました。 '投稿コードにその呼び出しが表示されません。コール後に長方形を塗りつぶしますか? – copeg

答えて

2

?私はそれを黄色に変えたい。

色を黄色に設定し、続いてコンポーネントの矩形を塗りつぶす必要があります。

protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.setColor(Color.YELLOW); 
    g.fillRect(0,0,getWidth(), getHeight()); 
    g.setColor(Color.BLUE); 
    g.drawString("Movie Sceen", 130, 20); 
} 

とその価値は何のために:私がnullレイアウトを使用しないことをお勧めします

totalGUI.setLayout(null); 

。タスクに適切なLayoutManagerを使用し、コンポーネント階層内にレイアウトをネストできることを覚えておいてください。

+0

ありがとう、それは動作します:) –

+0

nullレイアウトの代わりにLayoutManagerを使用しますか? –

+0

はい。ヌルレイアウトから離れたい理由を説明するには、[このレスポンス](http://stackoverflow.com/questions/17122338/swing-gridbaglayout-component-resizing/17122843#17122843)を参照してください。 – copeg

関連する問題