1
\$\begingroup\$

What is the best way to implement custom sliders (for volume), buttons normal, with images (icons) and with text, text boxes and other stuff with java.awt.Graphics?

Thanks,
Kerdo

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

This is easy.
First you have to capture the click and move events:

addMouseListener(new MouseListener() {
    @Override void mouseClicked(MouseEvent e) {
        mouse(e)
    }
...

And you travel through all the buttons, slides, etc.. in the mouse method, to pass the location of the mouse to them:

public void mouse(MouseEvent e) {
    allComponents.forEach(a -> a.hey(e.getX(), e.getY()));
}

And then you update the states in the hey method. For example, if it's a button, you see if the location of the mouse is inside the button. If so, you set your button's color to a darker one (just for example).

Then draw all the game objects to the screen. Override the paintComponent method, and invoke the methods of the parameter Graphics g, like drawString, drawRect, etc..

The approach described above is used in one of my personal project.

\$\endgroup\$
9
  • \$\begingroup\$ Thanks for your reply. I followed some tutorials and now got some things still to ask: I'm switching between gamestates (main menu, pause menu, etc). When switching the old menu's ui components are still accessible (clickable, executable). So I wrote a simple UI Manager to update all the components simultaneously. Now I'm creating a new UI Manager for every state and have to switch it in mousemanager. Is it better to have one and have tags on uicomponents to tell which state they belong in and update them when the corresponding menu is active? Mousemanager: (1/2) \$\endgroup\$
    – Kerdo
    Nov 28, 2017 at 17:17
  • \$\begingroup\$ Some screencaps of my code: imgur.com/XRWA1XB (MouseManager), imgur.com/a/YsHXt (Main menu UI implementation), imgur.com/a/qQDWm (UIManager). Any comments of making it better? (2/2) \$\endgroup\$
    – Kerdo
    Nov 28, 2017 at 17:19
  • \$\begingroup\$ You can g.fillRect(0, 0, width, height) before every refresh \$\endgroup\$
    – ice1000
    Nov 29, 2017 at 13:06
  • \$\begingroup\$ A suggestion: for (A a : as) { if (!a.x()) continue; a.y(); } can be replaced with for (A a : as) { if (a.x()) a.y(); } :D \$\endgroup\$
    – ice1000
    Nov 29, 2017 at 13:14
  • \$\begingroup\$ Actually I'm not familiar with the API you used so I can't be helpful with the usage of the widgets :) (BTW you have 16 rep now and you can upvote my answer :) \$\endgroup\$
    – ice1000
    Nov 29, 2017 at 13:17

You must log in to answer this question.

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