I have a MyFrame class which extends JFrame . I added components(Controls i.e buttons) to this frame using the design options in NET BEANS. I have a MyCanvas class which extends JPanel with an overridden paintComponent() method . I am trying to add this component to MyFrame class. But when i add it and make it visible the canvas(JPanel) doesn’t show itself on the JFrame.
(First I was trying to add Mycanvas class extended by Canvas. But then i read a thread here to try and change it to JPanel. I didn’t work either. And for canvas i obviously use paint not paintcomponent())
My code is here below
MyCanvas Class
public class MyCanvas extends javax.swing.JPanel{
MyCanvas()
{
super();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics2D=(Graphics2D)g;
graphics2D.drawRect(10, 10, 10, 10);
graphics2D.drawOval(0, 0, 100, 100);
}
}
MyFrame
public class Myframe extends javax.swing.JFrame {
public Myframe() {
initComponents();
@SuppressWarnings("unchecked")
+generatedcode by the designer
private void RectangleActionPerformed(java.awt.event.ActionEvent evt) {
}
private void SquareActionPerformed(java.awt.event.ActionEvent evt) {
}
private void CircleActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Myframe().setVisible(true);
}
});
}
public void run() {
new Myframe().setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton Circle;
private javax.swing.JButton Rectangle;
private javax.swing.JButton Square;
// End of variables declaration
}
My Main Program
public static void main(String[] args) {
MyCanvas c = new MyCanvas();
Myframe f= new Myframe();//Works if used JFrame instead of MyFrame
f.add(c);
f.setVisible(true);
}
Basically i want to create a GUI in which i want Buttons which can trigger events and change what is drawn on a canvas. I tried it with an empty jframe. added the canvas/panel to the JFrame . It worked. Also I changed my Panel/Canvas and refresehed the frame. That also worked fine. But i am unable to do it like this.
The is that you are mixing creating
JFramewith IDE and creatingJPanelyourself, remember the IDE adds all components toJFrameininitComponents()which is ideally where you’d want to have yourCanvasadded.either create the
JFrameandJPanelby yourself (without use of Netbeans GUI Builder)or
You can use the Palette Manager of Netbeans to add your
Componentto the palette, then you can use it in the GUI builder as you would any other class:(Simply drag the
Canvasclass from the projects tree on to theJFramein the GUI designer)To make sure your custom
Canvasfunctions:getPrefferedSize(..)and return a size which fitsReference: