2012-10-14 65 views
2

改變我有一個由兩個JPanelsJPanel的顏色從另一個

Panel1包含一個按鈕,當按鈕被點擊我要的是Panel2在顏色改變,併成爲紅色的框架,這沒」牛逼發生

因此,任何幫助,並解釋如何在面板的顏色從另一個面板中更改

public class MyForm extends JFrame { 
      public MyForm() { 
    // TODO Auto-generated constructor stub 
    super(); 
    // setLayout(new FlowLayout()); 
    Panel1 panel1 = new Panel1(); 
    add(panel1, BorderLayout.NORTH); 

    Panel2 panel2 = new Panel2(); 
    add(panel2, BorderLayout.CENTER); 
} 

class Panel1 extends JPanel { 

    public Panel1() { 
     // TODO Auto-generated constructor stub 

     JButton btn = new JButton("Change Color"); 
     add(btn); 
     btn.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       // TODO Auto-generated method stub 
       System.out.println("Sqsq"); 
       Panel2 panel2 = new Panel2(); 
       panel2.setBackground(Color.red); 
       panel2.repaint(); 

      } 
     }); 
    } 
} 

class Panel2 extends JPanel { 
    public Panel2() { 
     // TODO Auto-generated constructor stub 
     super(); 
     setBackground(Color.black); 

    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     // TODO Auto-generated method stub 
     super.paintComponent(g); 
    } 
} 

public static void main(String[] args) { 
    MyForm form = new MyForm(); 
    // form.setLocationRelativeTo(null); 
    form.setSize(500, 500); 
    form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    form.setVisible(true); 

} 
} 

回答

6

首先,在你btnactionPerformed方法,你正在創建一個Panel2這是不一樣的引用,只要一個添加到幀,因此,不會有任何變化......

您需要通過Panel1和參考你要更新的組件......

class Panel1 extends JPanel { 

    private JComponent changeMe; 

    public Panel1(JComponent changeMe) { 
     this.changeMe = changeMe; 
     // TODO Auto-generated constructor stub 

     JButton btn = new JButton("Change Color"); 
     add(btn); 
     btn.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       // TODO Auto-generated method stub 
       System.out.println("Sqsq"); 
       if (changeMe != null) { 
        changeMe.setBackground(Color.red); 
        changeMe.repaint(); 
       } 

      } 
     }); 
    } 
} 

您可能需要請求父容器而不是重新繪製,但怎麼看這個去...

+0

打我吧:) –

+0

好工作!謝謝 – HADEV

相關問題