我正在学习Java,现在我已经克服了软件包混乱的局面,一切进展顺利。我可以在我正在学习的大多数事物和至少已经知道其概念的事物之间得出相似之处。但是下面的代码到底是怎么回事?它是某种形式的构造函数还是匿名对象?

Something obj = new Something()
{
  private static final int num = 3;

  public void meth()
  {
    // w/e
  }
};

最佳答案

/**
 * Notice there's only one thing in this that isn't defined:
 * It still needs public abstract void triggerEvent();
 */
public abstract static class TopButton extends JPanel implements MouseListener {
        protected ButtonPanel parent;
        private String text;
        public TopButton(ButtonPanel bp, String text) { parent = bp; this.text = text; addMouseListener(this); }
        public void mouseClicked(MouseEvent e) { triggerEvent(); }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited(MouseEvent e) { }
        public void mousePressed(MouseEvent e) { }
        public void mouseReleased(MouseEvent e) { }
        public abstract void triggerEvent();
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Color oldColor = g.getColor();
            Font oldFont = g.getFont();
                Font newFont = new Font(oldFont.getName(),oldFont.getStyle(),oldFont.getSize());
                g.setFont(newFont);
                g.setColor(Color.black);
                g.drawString(text, 20, 20);
            g.setFont(oldFont);
            g.setColor(oldColor);
        }
    }


现在,当我实际定义按钮时,便会执行此操作。通过提供所需的一行,唯一使其与众不同的东西。现在,我可以为每个文件创建一个新文件,并为每个文件定义一个新的类。这要简单得多。

private static void loadButtonPanelButtons() {
    /* This button should tell the parent to bring up the save screen */
    TopButton save = new TopButton(buttonPanel,"Save") {
        public void triggerEvent() { parent.triggerSave(); }
    };
    save.setBorder(LineBorder.createBlackLineBorder());
    buttonPanel.add(save);

    /* This button should tell the parent to bring up the load screen */
    TopButton load = new TopButton(buttonPanel,"Load") {
        public void triggerEvent() { parent.triggerLoad(); }
    };
    load.setBorder(LineBorder.createBlackLineBorder());
    buttonPanel.add(load);

    TopButton addTile = new TopButton(buttonPanel,"Add Tile") {
        public void triggerEvent() { parent.triggerAddTile(); }
    };
    addTile.setBorder(LineBorder.createBlackLineBorder());
    buttonPanel.add(addTile);

    TopButton saveTiles = new TopButton(buttonPanel,"Save Tiles") {
        public void triggerEvent() { parent.triggerStyleSave(); }
    };
    saveTiles.setBorder(LineBorder.createBlackLineBorder());
    buttonPanel.add(saveTiles);
}


现在,当我处理被按下的按钮时,请回想一下TopButton的定义...

    public void mouseClicked(MouseEvent e) { triggerEvent(); }


我们知道triggerEvent()最终被定义。我们可以按按钮定义它,单击面板时,无论我们定义的triggerEvent()是什么,它都会被调用。

07-24 18:12