Reputation: 577
Im trying to represent a given math function inside of a JPanel,
for now I just have the axis, but the axis isnt painting and I dont know why, by the way if I call new Axis()
inside the frame it does paint.
Main class
public class MyClass{
final static int HEIGHT = 400;
final static int WIDTH = 400;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(WIDTH,HEIGHT);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPanel(frame);
frame.setVisible(true);
}
static void setPanel(JFrame frame) {
JPanel panel = new JPanel();
panel.setBackground(Color.GRAY);
panel.add(new Axis());
frame.add(panel);
}
}
Axis Class
@SuppressWarnings("serial")
public class Axis extends JComponent{
static final int LONG_AXIS = 150;
public void paintComponent(Graphics g) {
int CenterX = getWidth()/2;
int CenterY = getHeight()/2;
g.setColor(Color.BLACK);
//x axis line
g.drawLine(CenterX - LONG_AXIS, CenterY, CenterX + LONG_AXIS, CenterY);
//y axis line
g.drawLine(CenterX, CenterY - LONG_AXIS, CenterX, CenterY + LONG_AXIS);
}
}
Another question: Is it possible to have multiple paint methods?
Upvotes: 0
Views: 283
Reputation: 285430
When running, check the size of your Axis object, and you'll likely find that it is [0, 0] or [1, 1] in size since you're adding it to a JPanel that uses FlowLayout by default, and so will not cause Axis to expand, and Axis's default preferred size is [0, 0].
Consider overriding the Axis component's getPreferredSize()
method to return a reasonable dimension, or have its containing JPanel use BorderLayout and add it BorderLayout.CENTER, or do both.
Also, don't forget to call the super's paintComponent method in your override.
Regarding,
Ok, I mean if its a good practice, for example one paint method for the axis, and another paint method to do the draw math function
Consider creating methods that paintComponent(...)
calls for each of these steps. If complex, you could delegate it to non-component objects that your drawing component holds and that again paintComponent calls.
Also, static parts of your image, i.e., the x and y axis's are best drawn to a BufferedImage that is then drawn in paintComponent via g.drawImage(....)
Upvotes: 2