Results 1 to 11 of 11
  1. #1
    javstudent is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default Drawing a square with a button

    Hi,

    I'm using NetBeans IDE 6.9.1 and I am trying to draw square once a button is pressed.

    I have 3 classes.

    Graphic class:

    import java.awt.Color;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    /**
    *
    * @author
    */
    public class Graphic extends JPanel
    {

    @Override
    public void paintComponent(Graphics g)
    {
    super.paintComponent(g);
    g.setColor(Color.BLUE);
    g.fillRect(5, 5, 20, 20);
    }

    }
    The code for the button in my NewJFrame class generated by NetBeans IDE

    private void button2ActionPerformed(java.awt.event.ActionEvent evt) {
    Graphic graphic = new Graphic();
    jPanel2.add(graphic);// TODO add your handling code here:
    }
    My Main class:

    package javaapplication9;

    /**
    *
    * @author */
    public class Main
    {
    public static void main(String args[])
    {
    java.awt.EventQueue.invokeLater(new Runnable()
    {
    public void run() {
    new NewJFrame().setVisible(true);
    }
    });
    }
    }
    When I press my button, the square does not display. Is it possible to add a component to another JPanel ( which is also a component )?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

  3. #3
    javstudent is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default

    You mean repaint and revalidate jPanel2?

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by javstudent View Post
    You mean repaint and revalidate jPanel2?
    Yes, if this is the container that holds the Graphic JPanel. Also you sometimes have to repack your top-level window (JFrame?) so as to allow components to shift and allow room for the new component. Layout managers of course are key for this too.

  5. #5
    javstudent is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default

    I made another application just to test out the button and I used the repaint() method and it still does not work. So what I have is this:

    My Square class

    package javaapplication10;
    import java.awt.Color;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    /**
    *
    * @author
    */
    public class Square extends JPanel
    {
    @Override
    public void paintComponent(Graphics g)
    {
    super.paintComponent(g);
    g.setColor(Color.BLUE);
    g.fillRect(5, 5, 20, 20);
    }

    }
    My Drawing Class

    package javaapplication10;
    import javax.swing.JFrame;

    /**
    *
    * @author
    */
    public class Drawing extends JFrame
    {
    /** Creates new form Drawing */
    public Drawing()
    {
    initComponents();
    }


    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

    jButton1.setText("jButton1");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    jButton1MouseClicked(evt);
    }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
    .addContainerGap(277, Short.MAX_VALUE)
    .addComponent(jButton1)
    .addGap(50, 50, 50))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
    .addContainerGap(266, Short.MAX_VALUE)
    .addComponent(jButton1)
    .addContainerGap())
    );

    pack();
    }// </editor-fold>

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
    Square k = new Square();
    add(k);
    repaint();
    // TODO add your handling code here:
    }

    /**
    * @param args the command line arguments
    */
    My Main class

    package javaapplication10;

    /**
    *
    * @author
    */
    public class Main
    {


    public static void main(String[] args)
    {
    java.awt.EventQueue.invokeLater(new Runnable()
    {
    public void run()
    {
    new Drawing().setVisible(true);
    }
    });
    }// TODO code application logic here
    }
    I am telling the container, in this case the class Drawing, to repaint once the panel component is added. Don't know where to go from here....

  6. #6
    javstudent is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default

    Any takers? I also tried the revalidate method as well and it still did not work.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Your problem is likely with layouts, and I'll bet that after you create your Square object and add it to your gui, if you check it's size it's 0 x 0. Do not use NetBeans to generate your code, read the tutorials on how to use layout managers, and add your new JPanel to a container that uses a layout manager that will allow the square to be seen. Also, when posting code here, please don't use "quote" tags, but rather use "code" tags else your code will not be readable.

  8. #8
    javstudent is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default

    Thank you!

    I will check the size and try to figure out how to edit the code (Netbeans doesn't allow the code to be edited by default) so that I can use layout managers.

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by javstudent View Post
    Thank you!

    I will check the size and try to figure out how to edit the code (Netbeans doesn't allow the code to be edited by default) so that I can use layout managers.
    You can use different layout managers in NetBeans-generated code, but again, I'm advising you to not use NetBeans-generated code. Create the Swing program by hand as it will be easier to do what you want and you'll have more control over your program and a greater understanding as to what it's doing and why.

  10. #10
    javstudent is offline Member
    Join Date
    Apr 2011
    Posts
    6
    Rep Power
    0

    Default

    I have been reading about layout managers and I seem to not want to use them for certain instances. I can add panels to frames and add panel within panels without problem using just pure code and not IDE. However, when I try to paint an oval within a panel, it either removes the background color of the panel and adds the oval or it retains the color of the panel but the blue oval is not showing.

    This is the code that I have for my

    Main class

    Java Code:
    package javaapplication13;
    
    /**
     *
     * @author
     */
    public class Main
    {
    
        public static void main(String[] args)
        {
            Frame f = new Frame();
    
        }
    
    }
    My Frame class

    Java Code:
    package javaapplication13;
    import javax.swing.JFrame;
    import java.awt.Color;
    import javax.swing.JPanel;
    import javax.swing.BoxLayout;
    
    /**
     *
     * @author 
     */
    public class Frame extends JFrame
    {
        public Frame()
        {
            initComponents();
        }
    
        private void initComponents()
        {
           //Tcell2 t =  new Tcell2();
           getContentPane().setBackground(Color.GREEN);
           setSize(800, 600);
           setResizable(true);
           setVisible(true);
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           setLayout(null);
    
           JPanel j =  new JPanel();
           j.setSize(200,200);
           j.setBackground(Color.RED);
           j.setLocation(100, 200);
    
           //JPanel j2 =  new JPanel();
           //j2.setSize(20,20);
           //j2.setBackground(Color.BLUE);
           //j2.setLocation(4, 5);
    
           Tcell2 t =  new Tcell2();
           
           BoxLayout box = new BoxLayout(j,BoxLayout.LINE_AXIS);
           j.setLayout(box);
    
           add(j);
           j.add(t);
           System.out.println(t.isShowing());
           System.out.println(j.isShowing());
           j.validate();
           j.repaint();
    
     
        }
    
    }
    and my Tcell2 class which draws the blue oval.

    Java Code:
    package javaapplication13;
    import java.awt.Color;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    /**
     *
     * @author 
     */
    public class Tcell2 extends JPanel
    {
        public Tcell2()
        {
    
        }
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.setColor(Color.BLUE);
            g.fillOval(5, 5, 30, 30);
        }
    
    }
    In my Frame class, I have it showing that my components j and t are showing because they give a readout of true. However, I am still puzzled on why my background for the jpanel essentially dissappears? Any takers?

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    The red background-containing JPanel is there, but is covered by the other JPanel that was added. To see what I mean, please make the other panel not opaque:

    Java Code:
    class Tcell2 extends JPanel {
       public Tcell2() {
          setOpaque(false); 
       }
    The BoxLayout tutorial and api will tell you why the second panel completely covers the first. Also, and again, you'll want to avoid using null layouts. Just because it's easier to use at this stage doesn't make them better to use as you'll find out when you get into more complex layouts.

Similar Threads

  1. Replies: 4
    Last Post: 09-25-2010, 10:03 AM
  2. Button click for drawing geometry shape
    By nnur in forum AWT / Swing
    Replies: 5
    Last Post: 05-15-2010, 08:48 PM
  3. moving square
    By blindfolded in forum New To Java
    Replies: 5
    Last Post: 01-22-2010, 06:58 PM
  4. How can I square(^2) the pic in the grid
    By racewithferrari in forum New To Java
    Replies: 2
    Last Post: 11-03-2009, 06:27 PM
  5. How can I square(^2) the pic in the grid
    By racewithferrari in forum New To Java
    Replies: 1
    Last Post: 11-01-2009, 11:16 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •