我正试图改变我的玻璃窗中的布尔值:
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?
}
感谢任何帮助。
尝试创建一个public void setShow(Boolean x){show = x};在MyGlassPane类中,但无法使其工作。如何更改实例化JPanel的布尔值的值,以便绘制我的矩形(当我点击添加到“otherClass”的按钮时,就会发生这种情况)。
答案 0 :(得分:1)
您必须在MyGlassPane对象上存储引用(如果它是单例,它可以是静态的):
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);
//..
}
最后在你的主要:
public static void main(St ring[] args) {
Frame f = new Frame();
MyGlassPane mgp = new MyGlassPane();
//..
Store s = new Store(mgp);
//..
}
当然,这不是一个非常优雅的解决方案,但它应该有效......