Trying to change a JPanel's backcolor...
I'm using Eclipse.
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.border.BevelBorder;
public class mainForm extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainForm frame = new mainForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainForm() {
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
panel.setBackground(Color.black);
}
});
panel.setBounds(112, 62, 91, 72);
contentPane.add(panel);
}
}
On the line: "panel.setBackground(Color.black)", I'm getting the error: "Cannot refer to a non-final variable panel inside an inner class defined in a different method."
Re: Trying to change a JPanel's backcolor...
That error is correct: you cannot refer to a non-final local variable from within your anonymous MouseListener inner class. The reasons for this is due to the inner class making a local copy of the variable before using it, and if the variable is non-final then logic errors might occur. The simple solution: declare the panel JPanel variable final.
Re: Trying to change a JPanel's backcolor...
How do I get all panels on the contentPane?
Current code is something like this:
Code:
for(int i=0;i<=contentPane.getComponentCount()-1;i++)
{
contentPane.getComponent(i).addMouseListener(ma);
}
How do I check the type of the Component? I only want the MouseListener to be added to JPanels.
Re: Trying to change a JPanel's backcolor...
Use instanceof to determine the type