Page 1 of 2 12 LastLast
Results 1 to 20 of 22

Thread: MouseEvent

  1. #1
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default MouseEvent

    Hey,
    How can I add: MouseEvent to Graphics
    for example I have :
    Java Code:
        public void paint(Graphics g){
    
            super.paint(g);
    
            int mouseX1 = 0;
            int mouseY1 = 0;
    
            String mouseX = Integer.toString(mouseX1);
            String mouseY = Integer.toString(mouseY1);
            g.drawString("X: " + mouseX + " Y: " + mouseY, 0, 10);
            g.setColor(Color.green);
            g.drawOval(100, 20, 50, 50);
            g.drawLine(10, 40, 100, 40);
        }
    and I want it to be:
    Java Code:
        public void paint(Graphics g, MouseEvent e){
    
            super.paint(g);
    
            mouseX1 = e.getX();
            mouseY1 = e.getY();
    
            String mouseX = Integer.toString(mouseX1);
            String mouseY = Integer.toString(mouseY1);
            g.drawString("X: " + mouseX + " Y: " + mouseY, 0, 10);
            g.setColor(Color.green);
            g.drawOval(100, 20, 50, 50);
            g.drawLine(10, 40, 100, 40);
        }
    but if I will do it nothing comes up on my applet.
    Last edited by PhQ; 03-20-2010 at 08:44 PM.

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

    Default

    Is this Swing or AWT (an Applet or a JApplet)?

    Either way, you don't add a MouseListener in this way but rather add a MouseListener to the component (a JPanel if this is Swing or a Canvas or the Applet itself if this is AWT -- I think), and have the MouseListener change the state of the program, perhaps by adding data to an ArrayList. Then the paintComponent method (if Swing) or paint method (if AWT) uses this data to change the painting of the GUI. If you give us more details of your app, we can perhaps give you more details about solutions.

    Best of luck!

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

    Default

    By the way, when you override paint or paintComponent to draw on a GUI, you cannot change the method signature because if you do, this method is not a true override and will not be called by the GUI librarie's graphics system. Thus this is not kosher:
    Java Code:
    public void paint(Graphics g, MouseEvent e){
    since the two parameters don't match the parameters of the super class's method signature.

  4. #4
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    Quote Originally Posted by Fubarable View Post
    Is this Swing or AWT (an Applet or a JApplet)?

    Either way, you don't add a MouseListener in this way but rather add a MouseListener to the component (a JPanel if this is Swing or a Canvas or the Applet itself if this is AWT -- I think), and have the MouseListener change the state of the program, perhaps by adding data to an ArrayList. Then the paintComponent method (if Swing) or paint method (if AWT) uses this data to change the painting of the GUI. If you give us more details of your app, we can perhaps give you more details about solutions.

    Best of luck!
    Well, I am trying to learn about applets.
    This is my code:
    Java Code:
        /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class applet extends JApplet {
    
        /**
         * Initialization method that will be called after the applet is loaded
         * into the browser.
         */
        public void init() {
            // TODO start asynchronous download of heavy resources
        }
    
        public void start(){
    
        }
    
        public void stop(){
    
        }
    
        public void destroy(){
    
        }
    
    
    
        public void paint(Graphics g){
    
    
            super.paint(g);
            g.setColor(Color.green);
            g.drawOval(20, 20, 50, 50);
            g.drawLine(45, 70, 45, 100);
            g.drawLine(45, 70, 80, 100);
            g.drawLine(45, 70, 10, 100);
        }
    
    }
    At the moment I am trying to draw a stick man :) .
    And at the top I want it to say the mouse position, to make it easier for myself,
    to let you know, I am not an expert on JAVA, I started learning it like 6 months ago, and I find it awesome. :)

    Can I add a new method?
    For example:
    Java Code:
    public void mouse(MouseEvent e){
    blah blah blah
    }
    and for example do: mouse(getX);
    but I am not sure how to do that. :(
    Last edited by PhQ; 03-20-2010 at 09:19 PM.

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

    Default

    First of all, you don't want to paint directly on the JApplet but rather paint in a JPanel that the JApplet holds. This way you can override paintComponent and not paint and get all of the benefits of Swing graphics over AWT graphics, including double buffering.

    Next of all, if all you want to do is to display the position of the mouse, then for my money, I'd use a JLabel. Something like so:
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.*;
    
    public class MousePositionApp extends JApplet {
      public void init() {
        try {
          javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
              createGUI();
            }
          });
        } catch (Exception e) {
          System.err.println("createGUI didn't successfully complete");
        }
      }
    
      private void createGUI() {
        getContentPane().add(new GraphicsPanel());
      }
    }
    
    class GraphicsPanel extends JPanel {
      private static final String MOUSE_POS = "Mouse Position: ";
      JLabel mousePositionLabel = new JLabel(MOUSE_POS);
      
      public GraphicsPanel() {
        setLayout(new BorderLayout());
        add(mousePositionLabel, BorderLayout.SOUTH);
        addMouseMotionListener(new MouseAdapter() {
          public void mouseMoved(MouseEvent e) {
            String labelTxt = MOUSE_POS + String.format("[%d, %d]", e.getPoint().x, e.getPoint().y);
            mousePositionLabel.setText(labelTxt);
          }
        });
      }
      
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.green);
        g.drawOval(20, 20, 50, 50);
        g.drawLine(45, 70, 45, 100);
        g.drawLine(45, 70, 80, 100);
        g.drawLine(45, 70, 10, 100);
      }
    }
    Much luck!

  6. #6
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    Quote Originally Posted by Fubarable View Post
    First of all, you don't want to paint directly on the JApplet but rather paint in a JPanel that the JApplet holds. This way you can override paintComponent and not paint and get all of the benefits of Swing graphics over AWT graphics, including double buffering.

    Next of all, if all you want to do is to display the position of the mouse, then for my money, I'd use a JLabel. Something like so:
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.*;
    
    public class MousePositionApp extends JApplet {
      public void init() {
        try {
          javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
              createGUI();
            }
          });
        } catch (Exception e) {
          System.err.println("createGUI didn't successfully complete");
        }
      }
    
      private void createGUI() {
        getContentPane().add(new GraphicsPanel());
      }
    }
    
    class GraphicsPanel extends JPanel {
      private static final String MOUSE_POS = "Mouse Position: ";
      JLabel mousePositionLabel = new JLabel(MOUSE_POS);
      
      public GraphicsPanel() {
        setLayout(new BorderLayout());
        add(mousePositionLabel, BorderLayout.SOUTH);
        addMouseMotionListener(new MouseAdapter() {
          public void mouseMoved(MouseEvent e) {
            String labelTxt = MOUSE_POS + String.format("[%d, %d]", e.getPoint().x, e.getPoint().y);
            mousePositionLabel.setText(labelTxt);
          }
        });
      }
      
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.green);
        g.drawOval(20, 20, 50, 50);
        g.drawLine(45, 70, 45, 100);
        g.drawLine(45, 70, 80, 100);
        g.drawLine(45, 70, 10, 100);
      }
    }
    Much luck!
    Thank you very very very much.

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

    Default

    Quote Originally Posted by PhQ View Post
    Thank you very very very much.
    You're quite welcome. If later you want to do some actual drawing with the mouse, then you may wish to search this and other fora (for instance the Java2D section of the Sun fora) for examples. Some are descent, others so-so.

    Much luck!

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

    Default

    Myself, I generally try to avoid using GridBagLayout since it is quite complex and easy to mess up. I'm not saying I never use it, but in general I try to use other simpler layouts first if possible. Often we nest JPanels several inside of another each using their own simple layout to more easily achieve a complex layout without the hassle of GridBagLayout. If you decide to go this route though and have JPanels sitting on top of another that displays an image, just make sure that the overlying JPanels have their opaque property set to false so that they will allow the image to show through.

    If you need more layout help, you may wish to post your latest code attempt and perhaps an image of the layout you are trying to achieve.

    Much luck.

  9. #9
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    I am trying to make a game like Mafia Wars or Street Racing on facebook, but I am not sure what is the best layout to use.

    This is what I have so far.

    Java Code:
      class GraphicsPanel extends JPanel {
    
      public GraphicsPanel() {
        
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        JLabel label1 = new JLabel("test1");
        c.gridx = 0;
        c.gridy = 0;
        add(label1, c);
        JLabel label2 = new JLabel("test2");
        c.gridx = 0;
        c.gridy = 1;
        add(label2, c);
        JLabel label3 = new JLabel("test3");
        c.gridx = 0;
        c.gridy = 2;
        add(label3, c);
        JLabel label4 = new JLabel("test4");
        c.gridx = 0;
        c.gridy = 3;
        add(label4, c);
        JLabel label5 = new JLabel("test5");
        c.gridx = 0;
        c.gridy = 4;
        add(label5, c);
        
      }
    
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.green);
        g.drawOval(20, 20, 50, 50);
      }
    }
    When I run it every label is in the middle,
    how can I make it so it will be at the start of the window?

    Or maybe I could use a different layout?
    Last edited by PhQ; 03-21-2010 at 06:04 PM.

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

    Default

    If I wanted the labels all at the top, I'd add them to a JPanel, I'll call it "topPanel", that uses GridLayout set up so that it lays out components in a single row. I'd set the opaque property of this JPanel to false so that any underlying image will show through, and I'd set the overall layout of the GraphicsPanel to BorderLayout and add the topPanel to the main panel in the BorderLayout.NORTH position. For example:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class GraphicsPanel2 extends JPanel {
      
      private static final Color COLOR_1 = Color.red;
      private static final Color COLOR_2 = Color.blue;
      private static final Font LABEL_FONT =  new Font(Font.DIALOG, Font.BOLD, 16);
    
      public GraphicsPanel2() {
        JPanel topPanel = new JPanel(new GridLayout(1, 0, 5, 5));
        topPanel.setOpaque(false);
        for (int i = 0; i < 5; i++) {
          JLabel label = new JLabel("Test " + (i + 1), SwingConstants.CENTER);
          label.setFont(LABEL_FONT);
          label.setForeground(Color.white);
          topPanel.add(label);
        }
        
        setPreferredSize(new Dimension(500, 300));
        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.NORTH);
      }
      
      
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(new GradientPaint(0, 0, COLOR_1, 
            100, 100, COLOR_2, true));
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, 0, w, h);
      }
      
      private static void createAndShowUI() {
        JFrame frame = new JFrame("GraphicsPanel");
        frame.getContentPane().add(new GraphicsPanel2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
          }
        });
      }
    }
    I strongly recommend that you read the Sun Swing tutorials Laying out Components in a Container section.

  11. #11
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    This is a very cool thing to be honest.
    Now people can play the game on their internet browser or they can download it. ;)
    Thanks for helping me!!!
    Another question, do you know any good anti-decompiler programs?

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

    Default

    You're welcome. No, I don't know of these, but if you Google Java obfuscator (sp?), you may find what you want.

  13. #13
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    This might sound stupid, but how can I add a loading thing, for example, when you start a game it loads? How can I add it ? :D
    Last edited by PhQ; 03-23-2010 at 08:49 PM.

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

    Default

    Your question is not clear to me. You may wish to supply some details, such as what exactly is meant by "loading thing".

  15. #15
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    Do you know when you start a game and it loads?
    I would like to make that.

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

    Default

    Quote Originally Posted by PhQ View Post
    Do you know when you start a game and it loads?
    I would like to make that.
    You're still very anemic in your descriptions. A splash screen? A progress monitor? Come on, you can do better than your description above. Best of luck with whatever it is though.

  17. #17
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    A progress monitor

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

    Default

    Then you will want to look up the Sun tutorial on JProgressBar.

    Also, this site may help you with asking questions that get answered quicker. I know because it has helped me: Smart Questions

  19. #19
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    How come that this
    Java Code:
    add(mousePositionLabel, BorderLayout.SOUTH);
            addMouseMotionListener(new MouseAdapter() {
    
                public void mouseMoved(MouseEvent e) {
                    String labelTxt = MOUSE_POS + String.format("[%d, %d]", e.getPoint().x, e.getPoint().y);
                    mousePositionLabel.setText(labelTxt);
                }
            });
    doesn't work in JTabbedPane?

  20. #20
    PhQ's Avatar
    PhQ
    PhQ is offline Senior Member
    Join Date
    Mar 2010
    Location
    Lithuania
    Posts
    358
    Rep Power
    5

    Default

    By the way..
    Java Code:
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.image.ImageObserver;
    import java.text.AttributedCharacterIterator;
    
    import javax.swing.*;
    
    public class startGUI extends JApplet {
    
        private static final String MOUSE_POS = "Mouse Position: ";
        JLabel mousePositionLabel = new JLabel(MOUSE_POS);
    
        public void init() {
    
            
    
            setSize(955, 605);
            JMenuBar menubar = new JMenuBar();
            JMenu menuFile = new JMenu("File");
            JMenuItem loginItem = new JMenuItem("Login");
            menuFile.add(loginItem);
            JMenuItem registerItem = new JMenuItem("Register");
            menuFile.add(registerItem);
            menubar.add(menuFile);
            JMenu menuHelp = new JMenu("Help");
            JMenuItem aboutItem = new JMenuItem("About");
            menuHelp.add(aboutItem);
            menubar.add(menuHelp);
            setJMenuBar(menubar);
    
          
    
    
            add(mousePositionLabel, BorderLayout.SOUTH);
            addMouseMotionListener(new MouseAdapter() {
    
                public void mouseMoved(MouseEvent e) {
                    String labelTxt = MOUSE_POS + String.format("[%d, %d]", e.getPoint().x, e.getPoint().y);
                    mousePositionLabel.setText(labelTxt);
                }
            });
    
    
    
            JPanel panel2 = new JPanel();
            panel2.setLayout(null);
            panel2.setOpaque(false);
            JLabel label = new JLabel("Hello!");
            Insets insets = panel2.getInsets();
            Dimension size = label.getPreferredSize();
            label.setBounds(25 + insets.left, 5 + insets.top,
                    size.width, size.height);
    
            add(panel2);
            panel2.add(label);
    
                JPanel main = new JPanel(new BorderLayout()) {
          ImageIcon background = new ImageIcon(getClass().getResource("background.jpg"));
          protected void paintComponent(Graphics g) {
              g.drawImage(background.getImage(),0,0,this.getPreferredSize().width,this.getPreferredSize().height,null);
          }
        };
        JTabbedPane tab = new JTabbedPane();
        tab.setUI(new javax.swing.plaf.basic.BasicTabbedPaneUI(){
          protected void paintTabBackground(Graphics g,int tabPlacement,int tabIndex,int x,int y,int w,int h,boolean isSelected){}
          protected void paintContentBorder(Graphics g,int tabPlacement,int selectedIndex){}
        });
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setOpaque(false);
        panel.setPreferredSize(new Dimension(955,605));
        panel.add(new JLabel("Hello World"),new GridBagConstraints());
        tab.addTab("Panel", panel);
        main.add(tab);
        add(main);
      }
    
    
    
    }
    This is my class.
    And could you please help me with that logging thing (if I do System.out.println("Hello") it will print out Hello in a JTextArea or something)?

Page 1 of 2 12 LastLast

Posting Permissions

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