3
\$\begingroup\$

Recently I have encountered the issue of trying to add a GUI into my game using Swing. The game will randomly & infrequently flash the jButton or Swing component when I add it to my jFrame. I'm not sure if this is because Swing is not double buffered like the rest of my graphics or something is interfering with Swing (The game is in a barebone state, so I'm not sure what in the game would cause this).

I noticed that Minecraft has it's own custom GUI components, should I do a similar system, or is there an alternative to Swing?

EDIT: Figured I should add the initialization code for the component.

@Override
public void init(Main main) {
    playButton = new JButton("Test", new ImageIcon(this.getClass().getResource("gui/BlankButton.png")));
    playButton.setLocation(main.getW() / 2, main.getH() / 2);
    main.add(playButton);
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

No. Swing components wont render nicely in custom drawing. Actually the layout manager stores the coordinates of the object (component) and renders it by translating the graphics object. When in custom rendering, you do

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    // Original graphics
}

This overwrites the original rendering of the components. Instead you could translate the coordinates yourself but the rendering will be the default face, no mouse over effects and all other stuff since you will be calling repaint several times.

This has another backdrop also i.e improper functioning since you may be in another thread (i.e the game thread). You may do this with synchronization, but it so time ridden.

You can download and try the chapter 3 of Developing games in Java source but it didn't work for me exceeding version JDK 1.5.

You can make your own Button class if you want.

\$\endgroup\$
1
  • \$\begingroup\$ Okay I think I'll go with that then (Create your own button). \$\endgroup\$ Commented Dec 27, 2012 at 16:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .