Search code examples
javaswingjbuttonjtextarea

Java - Draw a circle ON JButton and JTextArea


So I'm trying to draw a sort of oval on a button and textarea. Yes, there is a reason why I can't just use a Panel or Frame.

So the button and textarea already has text on it and needs to stay as a button and textarea for the reason of the program.

So far, I only got one button to have this circle, but none of the other buttons show up with the circles. And the textareas aren't showing any circles at all.

My Code so Far for the buttons:

for (int i = 0; i < (label.length) / 2; i++) {
        butt = new JButton(label[i]); // label contains the text on button
        butt.setPreferredSize(new Dimension(83, 100));
        butt.add(smallPit); //smallpit is the circle graphics
        game.add(butt); // game is a panel
        // butt.setLayout(null);
    }
    for (int i = 6; i < label.length; i++) {
        butt = new JButton(label[i]);
        butt.setPreferredSize(new Dimension(83, 100));
        butt.add(smallPit);
        game.add(butt);
    }

Code for textarea

score2.setBounds(0, 50, 100, 210);
score1.setBounds(700, 50, 100, 210);
score2.add(scorePit);
score1.add(scorePit);

The outcome so far:

enter image description here


Solution

  • My guess is that this butt.add(smallPit); is causing your issues.

    My guess is that smallPit extends from something like JComponent (something that extends from JComponent), the problem is a component can only reside within a single container, so each time you call butt.add(smallPit);, smallPit is removed from it's previous container before been added to the new one.

    Instead, create an instance of smallPit (or what ever it is) and add it to each button which needs it.

    Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

    You should also have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?