我有三个类,Main,DrawingPanel和ToolboxPanel。 ToolboxPanel包含我的所有按钮,包括撤消按钮。 DrawingPanel是我绘制对象的地方。我希望撤消按钮在屏幕上绘制对象时启用,并在屏幕上没有剩余对象时禁用。 Main创建DrawingPanel和ToolboxPanel的实例。如果我使用静态方法并调用Main.setUndoStatus(false),我可以让我的undo按钮正常工作;来自drawingPanel。然后setUndoStatus在toolboxPanel中调用setter。但是,我一直在阅读观察者模式和听众,并认为我可能没有以最佳实践方式进行。
我应该如何正确地使用观察者模式和/或鼠标监听器来解决这个问题? (或任何"更好的"这样做的方式)。
这里的一些代码与我正在做的有些相似。
public class Main
{
DrawingPanel drawingPanel;
ToolboxPanel toolboxPanel;
public Main()
{
drawingPanel = new DrawingPanel();
toolboxPanel = new ToolboxPanel(drawingPanel);
}
}
//A static method here to setUndoStatus, but I feel like I shouldn't have it
public static void setUndoStatus(boolean b)
{
{
toolboxPanel.setUndoStatus(b);
}
}
public class ToolboxPanel
{
JButton undoButton;
public ToolboxPanel(DrawingPanel drawingPanel)
{
undoButton = new JButton("Undo");
undoButton.setEnabled(false);
undoButton.addActionListener
(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
drawingPanel.undo();
undoButton.setEnabled(drawingPanel.getUndoStatus());
}
}
);
}
public void setUndoStatus(boolean status)
{
undoButton.setEnabled(status);
}
}
public class DrawingPanel
{
public DrawingPanel()
{
addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
//Some code here that's unrelated
if(objectsExist == true) //If something gets drawn, whatever
{
Main.setUndoStatus(true); //Don't like this
}
}
});
}
}