It appears that a judge in their courtroom can ask anyone any questions. A quick search shows that it is not uncommon for persons refusing to answer judges' questions to be prosecuted for contempt of court, but most of those persons (if not all) are subpoenaed witnesses.
This question is about everyone else in the courtroom apart from the witnesses (and let's exclude the defendant too to avoid being sidetracked by self-incrimination laws e.g. The Fifth Amendment): prosecutors/plaintiffs, lawyers, experts, members of the public etc.: do they break any laws if they refuse to answer a question from the judge?
So far I have found that, in the US, lawyers can be fined for that.
In New Zealand, the relevant upcoming law deals with disobeying "Certain court orders and undertakings" but it does not look like arbitrary questions asked by judges fall into that bucket.