Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>/** * 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); } } </code></pre> <p>Now, when I actually define my buttons, I do this. By providing the one line it needs, the only thing that makes it different from others. Now I could make a new file for each one, and define a new class for each one. This is much simpler.</p> <pre><code>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); } </code></pre> <p>Now, when I handle the buttons being pressed, remember back in the definition of TopButton... there was</p> <pre><code> public void mouseClicked(MouseEvent e) { triggerEvent(); } </code></pre> <p>We know <code>triggerEvent()</code> eventually gets defined. We can define it on a per-button basis, and when the panel gets clicked, no matter what we defined <code>triggerEvent()</code> to be, it gets called.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload