Implemented "delegate" on java using the method in the interface with the signature void (string). When you try to call the JLabel.setText (String text) method in this way, the program crashes, however, if you throw another method (mesadbox / output to the console) everything works fine.

The compiler does not issue errors, the program window is "frozen."

Snake type game, playing field output via JLable. Code:

There is a class "Forms". This is a GUI. Here we create an instance of the "engine" class, throw a link to the setText method to it and output the map in JLable:

public class Form extends JFrame { private static final long serialVersionUID = 1L; private JLabel _gameLablel; public static void main(String[] args) { new Form().setVisible(true); } private Form() { super("My Game"); setSize(400, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); _gameLablel = new JLabel("sample text"); _gameLablel.setHorizontalAlignment(SwingConstants.CENTER); _gameLablel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { StartGame(); } }); add(_gameLablel); } private void StartGame() { EingeClass ec = new EingeClass(new IDelegate() { @Override public void AnMethod(String s) { _gameLablel.setText(s); } }); ec.StartShowing(); }} 

There is a class "Game Engine", which starts the generation of the map and calls to draw it at a given frequency:

 class EingeClass { Map m; IDelegate del; public EingeClass(IDelegate d) { this.m = new Map(); this.del = d; } public void StartShowing() { while (true) { try { del.AnMethod(m.ShowMap()); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }} 

And the self-made "delegate" for passing the reference to the draw method:

 interface IDelegate { void AnMethod(String s);} 

The "card" class is responsible for generating the card and returns a string with the card:

 class Map { char[][] _mapField = new char[10][10]; char _wall = '#'; char _grass = '+'; public Map() { GenerateMap(); } void GenerateMap() { for (int i = 0; i < _mapField[0].length; i++) for (int j = 0; j < _mapField[1].length; j++) if ((i > 0 && j > 0) && (i < _mapField[0].length - 1 && j < _mapField[1].length - 1)) _mapField[i][j] = _grass; else _mapField[i][j] = _wall; } String ShowMap() { String s = ""; for (int i = 0; i < _mapField[0].length; i++) { for (int j = 0; j < _mapField[1].length; j++) s += _mapField[i][j]; s += System.lineSeparator(); } return s; }} 
  • one
    Error text would be very useful - ArchDemon Nov.
  • Added info error in the post. - Jumping_With_Snake

1 answer 1

Graphics are redrawn after the event handler completes

 @Override public void mouseClicked(MouseEvent arg0) { StartGame(); } 

And your code goes into an infinite loop inside the handler, so the interface never redraws.