Reputation: 91
I'm trying to get my head around changing a Boolean in my glasspane:
public class Frame extends JFrame{
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Frame f = new Frame();
MyGlassPane mgp = new MyGlassPane();
f.setGlassPane(mgp);
mgp.setVisible(true);
mgp.setOpaque(false);
Store s = new Store();
f.add(s);
f.pack();
}
public class MyGlassPane extends JPanel{
Boolean show;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
if(show){
g.fillRect(50, 50, 50, 50);
}
}
public class Store extends JPanel{
public Store(){
setLayout(null);
But jb1 = new But();
add(jb1);
setBackground(Color.DARK_GRAY);
}
}
public class But extends JButton implements MouseListener, MouseMotionListener {
public But(){
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
public void mouseClicked(MouseEvent e) {
//Here I should be able to "show = true", but can't figure out how?
}
Any help is appreciated.
Tried creating a public void setShow(Boolean x){ show = x}; in the MyGlassPane class, but couldn't make it work. How can I change the value of the instanciated JPanel's boolean value, so that it draws my rectangle (this should happen when i click a button added to the "otherClass").
Upvotes: 0
Views: 122
Reputation: 5233
You have to store a reference on the MyGlassPane objet (it can be static if it's a singleton) :
public class But extends JButton implements MouseListener, MouseMotionListener {
private MyGlassPane mgp;
public But(MyGlassPane mgp){
this.mgp = mgp;
}
public void mouseClicked(MouseEvent e) {
mgp.show = true;
}
}
public Store(MyGlassPane mgp){
//..
But jb1 = new But(mgp);
//..
}
and finally in your main :
public static void main(St ring[] args) {
Frame f = new Frame();
MyGlassPane mgp = new MyGlassPane();
//..
Store s = new Store(mgp);
//..
}
Of course, not a very graceful solution, but it should work...
Upvotes: 1