I have class extended from JPanel. This class contains several other JComponents and a lot of painting. What I did and I know it isn't correct is, I overrided the paintComponent for the paintings, so far so good.
But I also set the location and the size for all subcomponents in this method, because they depend on the getWidth and getHeight from the JPanel. I know this isn't the place for the components, but where do I do this kind of stuff. At constructor time the sizes aren't set. So how do it correct? Because as long as I have the location and size method in the paintComponent method, the CPU never stops calculating something.
Edit: what i did looked like this;
public class abc extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
/** all the painting stuff */
textfield.setLocation(
this.getWidth() * someValue,
this.getHeight() * someotherValue);
// also depends on getHeight() and getWidth()
textfield.setSize(new Dimension(getHeight(), getWidth());
}
}
Everything worked fine, except that I always had a CPU usage around 10%. If commeted both lines out, the CPU usage dropped to 0%. So now I used a Layoutmanager like you recommended. And still everything lookes fine, but the CPU load didn't change it still stayed by around 10%. The code, how it looks now:
public class abc extends JPanel {
public abc() {
GridBagLayout gblayout = new GridBagLayout();
this.setLayout(gblayout);
textfield = new JTextField();
textfield.setHorizontalAlignment(JTextField.CENTER);
textfield.setBackground(new Color(0, 0, 0, 0));
textfield.setBorder(null);
textfield.setText("0");
gblayout.setConstraints(textfield, new GridBagConstraints(
0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(4, 4, 4, 4), 1, 1));
this.add(textfield);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
/** still the same paintings */ }
}