简体   繁体   中英

Dynamically resizing grid of buttons with Swing WYSIWYG editor?

I'm trying to code my first GUI-based game in Java and I chose the minesweeper. I'm quite a newbie in Java (though I can manage to program the logic part of the game so not "newbie" in the "I don't know what are classes" sense) and a complete freshman in Swing so I'd love if I could use the WYSIWYG editor (like the NetBeans one) for the graphics part rather than writing the layout by hand.

However, after playing with the editor, for my current understanding, I can only set a constant amounts of different containers with the Netbeans editor - I mean, I'd have to know in advance what dimensions do the board have to have. However, I'd like the board to resize dynamically so that when user may play on a 9x9 grid with 31 bombs just as well as on the 100x105 grid with 3 bombs. Can you create such dynamically resizing (of course not on-the-fly - I mean that user can decide what grid he wants to play on when he starts the game) grid of buttons with the WYSIWYG editor as well or such thing requires coding all of this by yourself from scratch?

  • write the layout by hand, this is job exactly for GridLayout

  • use JButton , better will be to use JToggleButton with Icon

  • Use proper setXxxIcon methods for JButton / JToggleButton

uh - please do not do it with the GUI Editor. You will probably create way too much variable featured components.

Please code at least parts of that yourself - the buttons you probably use on the minesweeper field should easily be created in a loop. The button has a data field, which you can use for the status of the field (bomb, no bomb, hidden, marked, empty). So when you create the ONE Actionlistener for the buttons, you should be able to react on that there.

Your real question: Yes, it depends much on the Layout you use. Avoid sizing and when you need to set Button Size, always refer to a base of 100%:

setButtonSize(){
  int iWindowWidth = 437; // example, can be any value. Stands for 100%
  button1.setWidth((int)(iWindowWidth * 0.2)); // 20%
  button1.setWidth((int)(iWindowWidth * 0.3)); // 30%
  button1.setWidth((int)(iWindowWidth * 0.05));//  5%
  button1.setWidth((int)(iWindowWidth * 0.45));// 45%
}

That is also how I create tables with dynamic width defining the column width.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM