Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Post Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    I want to make a drawing move left and right when I click on the appropriate button and the save its coordinates and then load its coordinates...
    also bring it home by resetting its coordinates by pressing (clicking) aapropriate buttons

    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
    [B]// Please give IDEA!!![/B]
     
    public class MyQ3FrameTrials extends JFrame
    {
    JPanel p1, p2;
    JCheckBox Face, Head, Tail, Body;
    JButton Left, Right, Reset, Load, Save;
     
    public MyFrameTrials()
    {
    setTitle("MyTrialsForLearningButtonComma…
    setSize(600, 250);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
     
    p1 = new JPanel();
    p2 = new JPanel();
     
    Face = new JCheckBox("String");
    Head = new JCheckBox("Circle");
    Tail = new JCheckBox("Line");
    Body = new JCheckBox("Rectangle");
     
    Left = new JButton("<< Move left");
    Right = new JButton(">> Move right");
    Reset = new JButton("Reset coordinates");
    Load = new JButton("Load last saved coordinates");
    Save = new JButton("Save current coordinates");
     
    Container cp = getContentPane();
    cp.add(p1, BorderLayout.WEST);
    cp.add(p2, BorderLayout.SOUTH);
     
    p1.setLayout(new GridLayout(5, 1));
    p1.add(Face);
    p1.add(Head);
    p1.add(Tail);
    p1.add(Body);
     
    p2.setLayout(new GridLayout(2 ,3));
    p2.add(Left);
    p2.add(Right);
    p2.add(Reset);
    p2.add(Load);
    p2.add(Save);
     
    Face.addMouseListener(new ButtonWatcher());
    Head.addMouseListener(new ButtonWatcher());
    Tail.addMouseListener(new ButtonWatcher());
    Body.addMouseListener(new ButtonWatcher());
     
    Left.addMouseListener(new ButtonWatcher());
    Right.addMouseListener(new ButtonWatcher());
    Reset.addMouseListener(new ButtonWatcher());
    Load.addMouseListener(new ButtonWatcher());
    Save.addMouseListener(new ButtonWatcher());
     
    }
    public class ButtonWatcher extends MouseAdapter
    {
    public void mouseClick (MouseEvent e)
    {
    Object buttonPressed = e.getSource();
    if (buttonPressed.equals(Left))
    {
    [B]// what to code here ... Please give IDEA![/B]
    }
    if (buttonPressed.equals(Right))
    {
    [B]// what to code here ... Please give IDEA![/B]
    }
     
    }
    }
    public void paint (Graphics g)
    {
    g.drawRect(140, 40, 440, 140);
    g.setColor(Color.WHITE);
    g.fill3DRect(140, 40, 440, 140, true);
    g.setColor(Color.WHITE);
     
    if(Head.isSelected())
    {
    g.setColor(Color.RED);
    g.fillOval(250 ,85 ,40 ,25);
    }
    if(Tail.isSelected())
    {
    g.setColor(Color.RED);
    g.drawLine(200, 100, 190, 75);
    }
    if(Body.isSelected())
    {
    g.setColor(Color.RED);
    g.fillRect(200, 100, 60, 40);
    }
    if(Face.isSelected())
    {
    g.setColor(Color.BLACK);
    g.setFont(new Font(" ",Font.BOLD, 20));
    g.drawString("* --", 260, 105);
    }
    }
     
     
    public static void main (String[] args)
    {
     
    MyFrameTrials f1 = new MyFrameTrials();
    f1.paint(null);
     
    }
     
    }

    I have made another class called Pixel, for my x and y int values...

    here is the code for it
     
    import java.awt.Color;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Scanner;
     
    public class Pixel extends Point
     { 
        private Color color = Color.green; 
        public Pixel() 
        { 
            super(); 
            color = Color.red;
     
        }  
     
        public  Pixel (int newX,  int newY,  Color NEWCOLOR) 
        { 
            x = newX ; 
            y = newY ; 
            color = NEWCOLOR;
     
        }  
     
    @Override
        public void reset() 
        { 
            x = 110;
            y = 100;
            color = Color.red;
     
        } 
     
    //getter method
        public Color getColor()
        {
            return color;
     
        }
     
    //setter method
        public void setColor(Color aColor)
        {
            color = aColor;
     
        }
     
    @Override
        public boolean equals(Object o) 
          {  
            if((o instanceof Pixel) && this.x == ((Pixel)o).x && this.y == ((Pixel)o).y && this.color == ((Pixel)o).color)
              {  
                 return true;  
              }
              else
                 {
                     return false;
                 }    
     
          }
     
        @Override
        public int hashCode() 
          {
            int hash = 7;
            hash = 67 * hash + (this.color != null ? this.color.hashCode() : 0);
            return hash;
          }
     
        public void loadPos(String filename) throws IOException
          {
            try
             {
               File myFile = new File("D:/coordinates.txt");
               Scanner scn = new Scanner(myFile);
               x = Integer.parseInt(scn.nextLine());
               y = Integer.parseInt(scn.nextLine());
               scn.close();
             }
            catch(IOException exception)
             {
               System.out.println(exception);
             }
          }
     
        public void savePos(String filename) throws IOException
          {
            try
             {
                FileWriter fw = new FileWriter("D:/coordinates.txt");
                PrintWriter pw = new PrintWriter(fw);
                pw.println(x);
                pw.println(y);
                pw.close();
             }
            catch(IOException error)
             {
                System.out.println(error);
             }
          }
     
     }
    Please advise... I am a beginner and a novice rookie... can you help me by providing me with the actual code so that I might learn it... Thanks
    I will then experiment and make other things... I first need to know what to write I do not know the syntax or commands to be written.
    Can you please help me!!!
    Last edited by java_rookie; May 5th, 2012 at 02:46 PM. Reason: Extra Info


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,596
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Please Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting

    To cause a drawn image to be at a different location after a button press, you need to have class variables like x and y that the draw method uses (your code uses hardcoded values) that the button listener code can change before it calls repaint. If the x,y values are changed the next call to the paint method will call the draw methods with that new location to draw at.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Thank you for your reply Norm,
    but I was hoping that you might teach me or guide me as what to write as in java code...

    can you please help me learn...
    and thanks for the advice for putting my code as
    <YOUR CODE HERE>
    its much better now...

    Please advise... I am a beginner and a rookie... can you help me by providing me with the actual code so that I might learn it...
    I will then experiment and make other things... I first need to know what to write I do not know the syntax or commands to be written.
    Can you please help me!!!
    kindly help me learn coding in Java!

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,596
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Do you understand what the parameters are to the draw methods you are using in the paint() method?
    If you do not change them, the drawing will always be done at the same place.
    Change the parameters to the draw methods to use variables defined out side of the paint() method.
    Have the code in the button listener methods change their values to have the draw methods draw at a new location.

    You should look at the API doc for the methods to see what their parameters are:
    Java Platform SE 6

    Find the class in the lower left and click on it to get the class's API doc in the main frame.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Thank you for your reply!
    Can you please give an example .... I'd prefer if you could write a sample code or amend mines...
    cause i am confused...
    please help me understand... and learn...
    I appreciate your efforts Norm

    also, I do not understand the parameters of the paint() method... please advise...
    I looked at the javaDoc but it confused me more I do not understand it or how to use the JavaDoc to write my code... sorry!
    Last edited by java_rookie; May 5th, 2012 at 02:24 PM. Reason: more info

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,596
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Do it one step at a time.
    Change the calls to the draw method to use variables instead of hardcoded numbers. For example:
    g.drawShape(10, 30,...
    change to
    g.drawShape(x,y,...

    Define x and y as int variables outside of the paint() method:
    int x = 10;
    int y = 30;
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    dear I want to move the whole drawing together as one object...
    I only want to learn how to use the buttons i've created in my frame to be able to move my drawing which is final (fixed) to the left 5 spaces and then to the right 5 spaces
    then to save the coordinates in the coordinates.txt file
    also to be able to load my saved coordintes... and reset them to the home position
    can you help me with that dear.., Norm

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,596
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Do one thing at a time, get it to work and then try doing another.
    First get all of the draw methods to use the x,y variables.
    Change all of the draw methods to use the x,y values corrected to where each one should be.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Can you please write the code for that and correct my errors...
    cuz i'm confused...
    Thank you for your help...Norm
    Please give me a code example... cuz I $uck @ theory at the moment...I'm a beginner ;(

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,596
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    I don't do student code. I've explained what you need to do. Do it one small step at a time.
    define the x and y and use it in one of the draw methods. Compile and execute to see that is works.

    Post the errors and the code if you have problems.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    I have tried to do as you told me...
    now at least look at my new amended code...
    but it does not look pretty and I have to resize to refresh the MyFrame can you tell me how to auto refresh in java so that my output window gets updated in realtime rather than me having to maximize / minimize the window to update...

    package myTrials;
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.color.*;
    import java.awt.Graphics.*;
    import my.Pixel;
     
    public class MyFrame extends JFrame {
        // declearing variables
        private static Pixel point = new Pixel();
        private JCheckBox rec;
        private JCheckBox str;
        private JCheckBox cir;
        private JCheckBox ln;
        private JButton left;
        private JButton right;
        private JButton save;
        private JButton load;
        private JButton reset;
        private JPanel panel1;
        private JPanel panel2; 
        // constructor
        public MyFrame(){
            setTitle("myTrials");
            setSize(600 , 250);
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
        public void addPanel1(){
            panel1 = new JPanel();
            getContentPane().add(panel1 , "West");
            panel1.setLayout(new GridLayout(4 , 1));
            str = new JCheckBox("String");
            ln = new JCheckBox("Line");
            cir = new JCheckBox("Circle");
            rec = new JCheckBox("Rectangle");
            panel1.add(str);
            panel1.add(ln);
            panel1.add(cir);
            panel1.add(rec);
            str.addItemListener(new CkeckBoxWatcher());
            ln.addItemListener(new CkeckBoxWatcher());
            cir.addItemListener(new CkeckBoxWatcher());
            rec.addItemListener(new CkeckBoxWatcher());
        }
        public void addPanel2(){
            panel2 = new JPanel();
            getContentPane().add(panel2 , "South");
            panel2.setLayout(new GridLayout(2 , 3));
            left = new JButton("<<moveleft");
            right = new JButton("move Right>>");
            save = new JButton("save coordinates");
            reset = new JButton("reset coordinates");
            load = new JButton("load last  saved coordinates");
            panel2.add(left);
            panel2.add(right);
            panel2.add(reset);
            panel2.add(load);
            panel2.add(save);
            left.addActionListener(new ButtonWatcher());
            right.addActionListener(new ButtonWatcher());
            save.addActionListener(new ButtonWatcher());
            reset.addActionListener(new ButtonWatcher());
            load.addActionListener(new ButtonWatcher());
        }
        public void paint(Graphics g){
            super.paint(g);
            g.drawRect(140 , 40 , 440 , 140);
            g.setColor(Color.white);
            g.fill3DRect(140 , 40 , 440 , 140, true);
            if (rec.isSelected()){
                g.drawRect(point.x - 5 , 100,  100, 50);
                g.setColor(Color.red);
                g.fill3DRect(point.x - 5 , 100,  100, 50, true);
     
            }
            if (ln.isSelected()){
                g.drawLine(point.x, point.y , 150, 70);
                g.setColor(Color.red);
            }
            if (cir.isSelected()){
                g.drawOval(point.x + 94 , 70 , 60 , 50);
                g.fillOval(point.x + 94 , 70 , 60 , 50);
            }
            if (str.isSelected()){
                Font font = new Font("Sherif" , Font.BOLD , 14);
                g.setFont(font);
                g.setColor(Color.black);
                g.drawString("* --", point.x + 111, 100);
            }
        }
            public static void main(String[] args){
            MyFrame a = new MyFrame();
            a.addPanel1();
            a.addPanel2();
        }
            private class CkeckBoxWatcher implements ItemListener{
                public void itemStateChanged(ItemEvent i){
                    repaint();
                }
            }
            private class ButtonWatcher implements ActionListener{
                public void actionPerformed(ActionEvent e){
                    Object select = e.getSource();
                    if (select.equals(left)){
                        point.x = point.x - 5;
                        repaint();
                    }
                    if (select.equals(right)){
                        point.x = point.x + 5;
                        repaint();
                    }
                    if (select.equals(reset)){
                        point.reset();
                        repaint();
                }
                    if (select.equals(save)){
                        point.savePos("C:/coordinates.txt");
                        repaint();
            }
                    if (select.equals(load)){
                        point.loadPos("C:/coordinates.txt");
                        repaint();
                    }
    }
            }
    }
    the tail (line) remains fixed and does not move with everything...
    also when i run in NetBeans IDE 7.1
    i get the following msgs:
    ***********************
    ***********************
    run:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at MySolutions.MyFrame.paint(MyFrame.java:84)
    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:797)
    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:714)
    at javax.swing.RepaintManager.prePaintDirtyRegions(Re paintManager.java:694)
    at javax.swing.RepaintManager.access$700(RepaintManag er.java:41)
    at javax.swing.RepaintManager$ProcessingRunnable.run( RepaintManager.java:1636)
    at java.awt.event.InvocationEvent.dispatch(Invocation Event.java:209)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:646)
    at java.awt.EventQueue.access$000(EventQueue.java:84)
    at java.awt.EventQueue$1.run(EventQueue.java:607)
    at java.awt.EventQueue$1.run(EventQueue.java:605)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 616)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)
    ************************
    *************************

    please advise!
    thank you!

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,596
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: Can anyone help me in coding Java for my GUI trials for Learning Button Commands?

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at MySolutions.MyFrame.paint(MyFrame.java:84)
    There is a variable with a null value on line 84. Look at line 84 and find the variable with the null value and then backtrack in the code to find out why that variable does not have a valid non-null value.

    Use a println before line 84 to print all the variables on line 84 to see which one has the null value.

    how to auto refresh in java so that my output window gets updated
    Don't call setVisible until everything is ready to be shown.
    Last edited by Norm; May 5th, 2012 at 04:36 PM.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 2
    Last Post: February 19th, 2012, 06:36 AM
  2. need help Coding RADIO BUTTON for REMEMBER ME
    By timosoft in forum Java Theory & Questions
    Replies: 3
    Last Post: February 4th, 2011, 04:19 PM
  3. simple java console program, need help recalling commands
    By zero0000000 in forum Java Theory & Questions
    Replies: 2
    Last Post: October 22nd, 2010, 05:47 AM
  4. Executing Linux Commands with Java GUI
    By linuxrockers in forum AWT / Java Swing
    Replies: 2
    Last Post: February 15th, 2010, 09:57 PM
  5. 15, Loves ICT, learning Java coding.
    By Sergant Mitch in forum Member Introductions
    Replies: 1
    Last Post: September 20th, 2008, 09:40 AM

Tags for this Thread