Referencing coordinates of a JPanel in a JFrame
-
01-06-2021 - |
Pergunta
Hi I am having trouble with referencing the origin of a JPanel within my JFrame. My JPanel was set up like so in the constructor I want to add a line that is on the left edge of my JPanel.
table = new JPanel();
table.setBackground(Color.green);
table.setBounds(10,10, 600, 600);
table.setSize(width.getValue(), height.getValue());
add(table);
Then the paint method...
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawLine(table.getX(), table.getY(), table.getX(), (table.getY() + table.getHeight()));
g2d.drawLine(100, 100, (int)Math.round(cueBall.getPositionX()), (int)Math.round(cueBall.getPositionY()));
}
The last command in the paint method is unrelated to my problem... The code appears to be getting the origin as (10, 10) but applying it to the JFrame as a whole rather than the contentPane. I don't completely understand the contentPane but I thought that add() adds to the content pane and from then on you are referencing coordinates from the contentPane only...I just don't see why setBounds() added the JPanel where I wanted it which was (10,10) in relation to only the contentPane but when I paint() it appears to get the coordinates in relation to the contentPane but paint those coordinates in reference to the JFrame. I realize I could just add a value to move the line down but I suspect that is a poor solution.
Do I need to add a contentPane with it's own paint() method or something along those lines?
Solução
You should override and do your painting in JPanel.paintComponent()
. Checkout Painting in AWT and Swing.
Not sure what is the reason for the use of setbounds()
, are you trying to go with absolute positioning of your components? I'd recommend to get familiar with java layouts, here is a good start - A Visual Guide to Layout Managers.