A
A
Alex_F1522020-12-10 09:31:17
Java
Alex_F152, 2020-12-10 09:31:17

Java swing. how to override paintComponent() multiple times, depending on the button pressed?

I create a graphic element of the program. Of course, there is practically no experience in this. On a BufferedImage placed on a JLabel I'm trying to create a graphic that will change when different JButtons are clicked . For this I use paintComponent() overriding. (If there are better options, please don’t be shy and tell me, I just don’t have anything else in mind =) ) I tried to create several Consumers with override options, but I didn’t think of what exactly to set in the condition of the switch itself. As a result, my "perversion" at the moment looks something like this

@Override
    protected void  paintComponent(Graphics g) {
        super.paintComponent(g);
      if(button16.isSelected()) {
        cons.accept(g);
      }
    }
    Consumer cons = (g) -> {
        Graphics g2d = (Graphics2D) g.create();
        g2d.fillOval(getWidth()-230, getHeight()-170, 16,16);
        g2d.dispose();

    };

I tried to create a tag when the button is pressed, and then just read it in the paintComponent() condition. As a result, a complete rubbish came out ... I won’t even spread it .... The main essence of the question is: how in this case to synchronize the button press and the redefinition of paintComponent ()? (additional: how to implement a condition in a switch(condition) for this case?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Odissey Nemo, 2020-12-17
@odissey_nemo

I haven’t done Swing for a long time, but I will soon)) So far there is only a suggestion - since there is one BufferedImage, which makes it difficult to replace it with another directly by reference without redrawing the existing one (by creating and uploading the necessary one from a resource or from disk), and then call paintComponent (repaint?) immediately after replacement?
And wouldn't it be easier to use Icon files rather than BufferedImage, which is fairly low-level? But this, of course, is only for the case when the icons are static, not dynamically drawn.
Or even assign a different status for all buttons and then call repaint in the click handlers, in which, according to the status switch, draw the graphics corresponding to it (the identifier of the last pressed button, practically).
I forgot the mechanisms themselves, I write only general considerations. Later I will find examples of my own and remember))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question