0

我正试图改变我的玻璃窗格中的布尔值:

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”的按钮时应该会发生这种情况)。

4

1 回答 1

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);
     //..
 }

当然,这不是一个非常优雅的解决方案,但它应该可以工作......

于 2013-06-03T18:35:47.957 回答