Java MouseListener 🖱️

Поделиться
HTML-код
  • Опубликовано: 23 ноя 2024

Комментарии • 87

  • @BroCodez
    @BroCodez  4 года назад +50

    public class Main{
    public static void main(String[] args) {

    new MyFrame();
    }
    }
    import java.awt.Color;
    import java.awt.event.*;
    import javax.swing.*;
    public class MyFrame extends JFrame implements MouseListener{
    JLabel label;

    MyFrame(){
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(500,500);
    this.setLayout(null);

    label = new JLabel();
    label.setBounds(0, 0, 100, 100);
    label.setBackground(Color.red);
    label.setOpaque(true);
    label.addMouseListener(this);

    this.add(label);
    this.setVisible(true);
    }
    @Override
    public void mouseClicked(MouseEvent e) {
    // Invoked when the mouse button has been clicked (pressed and released) on a component
    //System.out.println("You clicked the mouse");
    }
    @Override
    public void mousePressed(MouseEvent e) {
    // Invoked when a mouse button has been pressed on a component
    System.out.println("You pressed the mouse");
    label.setBackground(Color.yellow);
    }
    @Override
    public void mouseReleased(MouseEvent e) {
    // Invoked when a mouse button has been released on a component
    System.out.println("You released the mouse");
    label.setBackground(Color.green);
    }
    @Override
    public void mouseEntered(MouseEvent e) {
    // Invoked when the mouse enters a component
    System.out.println("You entered the component");
    label.setBackground(Color.blue);
    }
    @Override
    public void mouseExited(MouseEvent e) {
    // Invoked when the mouse exits a component
    System.out.println("You exited the component");
    label.setBackground(Color.red);
    }
    }

    • @joyceasante8292
      @joyceasante8292 Год назад +1

      Practicing...
      public class Main{
      public static void main(String[]args){
      new MyFrame();
      }
      }
      ***************
      import java.awt.FlowLayout;
      import java.awt.Color;
      import java.awt.event.*;
      import javax.swing.*;
      public class MyFrame extends JFrame implements MouseListener
      {
      JLabel label;
      ImageIcon smile;
      ImageIcon frown;
      ImageIcon grimace;
      ImageIcon cool;
      MyFrame ()
      {
      this.setDefaultCloseOperation (EXIT_ON_CLOSE);
      this.setSize (250, 250);
      //this.setLayout (null);
      this.setLayout (new FlowLayout());
      label = new JLabel();
      label.addMouseListener(this);
      smile = new ImageIcon ("smile.png");
      frown = new ImageIcon ("frown.png");
      grimace = new ImageIcon("grimace.png");
      cool = new ImageIcon("cool.png");
      label.setIcon(smile);
      this.pack();
      this.setLocationRelativeTo (null);
      label = new JLabel ();
      label.setBounds (0, 0, 200, 200);
      label.setBackground (Color.yellow);
      label.setOpaque (true);
      label.addMouseListener (this);
      //this.addMouseListener(this);
      this.add (label);
      this.setVisible (true);
      }
      @Override public void mouseClicked (MouseEvent e)
      {
      //System.out.println("Mouse clicked.");
      }
      @Override public void mousePressed (MouseEvent e)
      {
      //System.out.println("Mouse pressed.");
      //label.setBackground (Color.blue);
      label.setIcon(frown);
      }
      @Override public void mouseReleased (MouseEvent e)
      {
      //System.out.println("Mouse released.");
      //label.setBackground (Color.orange);
      label.setIcon(cool);
      }
      @Override public void mouseEntered (MouseEvent e)
      {
      //System.out.println("Component entered.");
      //label.setBackground (Color.green);
      label.setIcon(grimace);
      }
      @Override public void mouseExited (MouseEvent e)
      {
      System.out.println ("Component exited.");
      //label.setBackground (Color.yellow);
      label.setIcon(smile);
      }
      }

    • @aseelalrdaini866
      @aseelalrdaini866 Год назад

      I exactly do what you did but there is a message that tell there is no main in code so what is the problem?

    • @joyceascuriousgirl
      @joyceascuriousgirl Год назад

      @@aseelalrdaini866 🤔
      I'm still learning how to code.
      Perhaps, you mistyped something or forgot to write a line.
      If you post your code here, perhaps I or someone else can help you fix the issue.

    • @joyceascuriousgirl
      @joyceascuriousgirl Год назад

      There are 2 classes.
      Main class ends before "import...".

  • @bitcoin1532
    @bitcoin1532 3 года назад +14

    With each video I watch understanding terms on the next one gets easier. I'll one day rewatch this whole playlist to master all these concepts. Thank you bro

  • @mahernurhussen2398
    @mahernurhussen2398 Год назад

    This might be the first Java program that I actually loved since learning about the countdown one.

  • @DanielRodrigues-bx6lr
    @DanielRodrigues-bx6lr 3 года назад +9

    This was fantastic! I love how you incorporated those emoticons with funny explanations! :D

  • @Shad0wAnlirome
    @Shad0wAnlirome 3 года назад +5

    Gracias que buen proyecto, entendí de la mejor manera, saludos desde colombia espero seguir aprendiendo con tu canal

  • @pavelkvasnicka6856
    @pavelkvasnicka6856 Год назад

    This is the best Java tutorial for beginners, so you can learn Java and English in one hit. Please keep going! I vote for Java advance tutorial. Thanks a lot Bro

  • @monwil3296
    @monwil3296 4 года назад +2

    Bro, keep the juice flowing 👏. Thanks

    • @BroCodez
      @BroCodez  4 года назад

      I will Mon Wil. thanks bro

  • @wolontong
    @wolontong 2 года назад +2

    how to add multiple mouselisteners to multiple labels in one sidebar?

  • @maxwong1768
    @maxwong1768 2 года назад

    Hope can make a lesson about the MouseMotionListener .

  • @zoetenuta6823
    @zoetenuta6823 2 года назад

    Dude your channel single handedly saved my computer science grade

  • @maxwong1768
    @maxwong1768 2 года назад +3

    When I saw your cover page of this lesson , I thought you are going to talk about how to make the eyes of the emoji following the cursor .
    But I was wrong , therefore I decide to make this function comes true as a challenge to myself .
    After a few days of struggling and reviewing the math knowledges , I can't believe that I achieve the goal . Now the eyeball spins to follow my cursor . I can even move the whole face around the frame .
    Here's my code . There are 3 parts as the comment gets word count limit .
    // Part 1
    package testing;
    public class Main {
    public static void main(String[] args) {
    MyFrame frame = new MyFrame() ;
    }
    }
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MyFrame extends JFrame implements MouseListener , MouseMotionListener {
    // For finding the position of two black balls .
    MyFrame blackBall ;

    // Instantialization of image icon .
    ImageIcon faceIcon = new ImageIcon("src/noEyeFace.png") ;
    ImageIcon leftWhiteBallIcon = new ImageIcon("src/whiteBall.png") ;
    ImageIcon leftBlackBallIcon = new ImageIcon("src/blackBall.png") ;
    ImageIcon rightWhiteBallIcon = new ImageIcon("src/whiteBall.png") ;
    ImageIcon rightBlackBallIcon = new ImageIcon("src/blackBall.png") ;

    // Instantialization of label .
    JLabel faceLabel = new JLabel() ;
    JLabel leftWhiteBallLabel = new JLabel() ;
    JLabel leftBlackBallLabel = new JLabel() ;
    JLabel rightWhiteBallLabel = new JLabel() ;
    JLabel rightBlackBallLabel = new JLabel() ;
    // distance between the cursor and the start point of the face .
    double cursorFaceDistanceX , cursorFaceDistanceY ;
    // distance between the cursor and the eyeball .
    double cursorLeftBlackBallDistanceX , cursorLeftBlackBallDistanceY ;
    double cursorRightBlackBallDistanceX , cursorRightBlackBallDistanceY ;
    // distance between the start point of face and the orbit center .
    final double faceLeftOrbitDistanceX = 150 , faceLeftOrbitDistanceY = 180;
    final double faceRightOrbitDistanceX = 350 , faceRightOrbitDistanceY = 180 ;

    // component parameters (frame , face , 2 white balls , 2 black balls , 2 orbits)
    final double frameWidth = 1000 , frameHeight = 1000 , titleBarHeight = 30 , screenFrameGap = 7 ;
    final double faceWidth = 500 , faceHeight = 500 ;
    final double leftWhiteBallRadius = 65 , rightWhiteBallRadius = 65 ;
    final double leftBlackBallRadiusGain = 30 , rightBlackBallRadiusGain = 30 ;
    final double leftBlackBallRadius = 15 + leftBlackBallRadiusGain , rightBlackBallRadius = 15 + rightBlackBallRadiusGain ;
    final double leftOrbitRadius = 50 - leftBlackBallRadiusGain ;
    final double rightOrbitRadius = 50 - rightBlackBallRadiusGain ;

    // coordination of components under Java's coordinate system (frame , cursor , face , 2 black balls )
    double frameAbsoluteX , frameAbsoluteY ;
    double cursorRelativeX , cursorRelativeY ;
    double faceRelativeX , faceRelativeY ;
    double faceCenterX = faceRelativeX + 250 , faceCenterY = faceRelativeY + 250 ;
    double leftOrbitCenterX = faceLeftOrbitDistanceX , leftOrbitCenterY = faceLeftOrbitDistanceY ;
    double rightOrbitCenterX = faceRightOrbitDistanceX , rightOrbitCenterY = faceRightOrbitDistanceY ;
    double leftBlackBallCenterX , leftBlackBallCenterY , rightBlackBallCenterX , rightBlackBallCenterY ;

    // coordination of component under Cartesian coordinate system (cursor , 2 orbit centers , 2 black balls)
    double cursorRelativeCartesianX , cursorRelativeCartesianY ;
    double leftOrbitCenterCartesianX = leftOrbitCenterY , leftOrbitCenterCartesianY = leftOrbitCenterX ;
    double rightOrbitCenterCartesianX = rightOrbitCenterY , rightOrbitCenterCartesianY = rightOrbitCenterX ;
    double leftBlackBallCenterCartesianX , leftBlackBallCenterCartesianY , rightBlackBallCenterCartesianY , rightBlackBallCenterCartesianX ;

    // two slopes
    double leftCartesianM , rightCartesianM ;

    boolean isCursorInLeftObject = false , isCursorInRightObject = false ;
    boolean dragFaceState = false ;
    public MyFrame()
    {
    // basic location setting of face , 2 black balls and 2 white balls .
    faceLabel.setBounds(0 , 0 , (int)faceWidth , (int)faceHeight) ;
    faceLabel.setIcon(faceIcon);

    leftWhiteBallLabel.setBounds((int)(leftOrbitCenterX - leftWhiteBallRadius) , (int)(leftOrbitCenterY - leftWhiteBallRadius) , (int)(leftWhiteBallRadius*2) , (int)(leftWhiteBallRadius*2)) ;
    leftWhiteBallLabel.setIcon(leftWhiteBallIcon);

    leftBlackBallLabel.setBounds((int)(leftOrbitCenterX - leftBlackBallRadius) , (int)(leftOrbitCenterY - leftBlackBallRadius) , (int)(leftBlackBallRadius*2) , (int)(leftBlackBallRadius*2)) ;
    leftBlackBallLabel.setIcon(leftBlackBallIcon);

    rightWhiteBallLabel.setBounds((int)(rightOrbitCenterX - rightWhiteBallRadius) , (int)(rightOrbitCenterY - rightWhiteBallRadius) , (int)(rightWhiteBallRadius*2) , (int)(rightWhiteBallRadius*2)) ;
    rightWhiteBallLabel.setIcon(rightWhiteBallIcon);

    rightBlackBallLabel.setBounds((int)(rightOrbitCenterX - rightBlackBallRadius) , (int)(rightOrbitCenterY - rightBlackBallRadius) , (int)(rightBlackBallRadius*2) , (int)(rightBlackBallRadius*2)) ;
    rightBlackBallLabel.setIcon(rightBlackBallIcon);

    // basic setting of frame .
    this.setVisible(true) ;
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
    // the start point of setSize is (-15 , -8)
    this.setSize((int)(frameWidth+15) , (int)(frameHeight+titleBarHeight+8)) ;
    this.setLayout(null) ;
    this.add(leftBlackBallLabel) ;
    this.add(leftWhiteBallLabel) ;
    this.add(rightBlackBallLabel) ;
    this.add(rightWhiteBallLabel) ;
    this.add(faceLabel) ;
    this.addMouseListener(this) ;
    this.addMouseMotionListener(this) ;
    }

    // declare the location of 2 black ball centers returned from "getBlackBallLocation" method .
    public MyFrame(double leftBlackBallCenterX , double leftBlackBallCenterY , double rightBlackBallCenterX , double rightBlackBallCenterY)
    {
    this.leftBlackBallCenterX = leftBlackBallCenterX ;
    this.leftBlackBallCenterY = leftBlackBallCenterY ;
    this.rightBlackBallCenterX = rightBlackBallCenterX ;
    this.rightBlackBallCenterY = rightBlackBallCenterY ;
    }

    // retrieve the location of 2 black ball centers returned from "getBlackBallLocation" method .
    public double getLeftCenterX()
    {
    return leftBlackBallCenterX ;
    }

    public double getLeftCenterY()
    {
    return leftBlackBallCenterY ;
    }

    public double getRightCenterX()
    {
    return rightBlackBallCenterX ;
    }

    public double getRightCenterY()
    {
    return rightBlackBallCenterY ;
    }
    // Invoked when a mouse button is pressed on a component(frame) and then dragged.
    @Override
    public void mouseDragged(MouseEvent e) {
    // get the coordination of frame , cursor and face .
    getFrameAbsolutePosition() ;
    getCursorRelativePosition() ;
    getFaceRelativePosition() ;

    // if the face area is pressed and then being dragged .
    if (dragFaceState)
    {
    // update the coordination of face .
    faceLabel.setLocation((int)(cursorRelativeX - cursorFaceDistanceX) , (int)(cursorRelativeY - cursorFaceDistanceY)) ;

    // update the coordination of the two orbit centers .
    leftOrbitCenterX = faceRelativeX + faceLeftOrbitDistanceX ;
    leftOrbitCenterY = faceRelativeY + faceLeftOrbitDistanceY ;
    rightOrbitCenterX = faceRelativeX + faceRightOrbitDistanceX ;
    rightOrbitCenterY = faceRelativeY + faceRightOrbitDistanceY ;
    leftOrbitCenterCartesianX = leftOrbitCenterY ;
    leftOrbitCenterCartesianY = leftOrbitCenterX ;
    rightOrbitCenterCartesianX = rightOrbitCenterY ;
    rightOrbitCenterCartesianY = rightOrbitCenterX ;

    // update the location of two white balls and two black balls .
    leftWhiteBallLabel.setLocation((int)(leftOrbitCenterX - leftWhiteBallRadius) , (int)(leftOrbitCenterY - leftWhiteBallRadius)) ;
    rightWhiteBallLabel.setLocation((int)(rightOrbitCenterX - rightWhiteBallRadius) , (int)(rightOrbitCenterY - rightWhiteBallRadius)) ;
    leftBlackBallLabel.setLocation((int)(cursorRelativeX - cursorLeftBlackBallDistanceX) , (int)(cursorRelativeY - cursorLeftBlackBallDistanceY)) ;
    rightBlackBallLabel.setLocation((int)(cursorRelativeX - cursorRightBlackBallDistanceX) , (int)(cursorRelativeY - cursorRightBlackBallDistanceY)) ;
    }
    }
    // too long , the comment returned error .
    // be continue ...

  • @takworld6770
    @takworld6770 Год назад

    Public class main{
    Public static void main ( string args[]){
    System.out.print(" Really Helpfull, thanks");
    }
    }

  • @shaynazoedeguzman7418
    @shaynazoedeguzman7418 2 года назад +1

    Amazing! Much respect! TYVM bro! A perfect 10 tutorial!

  • @parkerpierce8931
    @parkerpierce8931 Год назад +1

    Really appreciate ya making all these videos! Made a pivot to code after 2 strokes this year and the way you explained the concepts really helps me digest and install the new skills . Are you still open to making more, or is this more or less a completed series? Just curious.

  • @NiceChange
    @NiceChange Год назад

    I thoroughly enjoyed this video. It was informative very easy to get through. It made me laugh so I felt comfortable which made the subject matter more absorbable and effective. Thank you ..Great work.

  • @elaprendiz7208
    @elaprendiz7208 3 года назад +3

    Hello Bro! I like so much your videos. I want ask something about Mouse Event. How i can use the events on objects. Like rectangle or ellipse. It's possible implementen inside the object? You can do some video using events on graphics object? Thanks for all.

  • @RoboopcBilgisayar
    @RoboopcBilgisayar Год назад

    thanks for video brocodes, How can I move the mouse cursor anywhere on the screen? and how can I make it click automatically when it reaches this position?

  • @deepdaddy1208
    @deepdaddy1208 4 года назад +3

    gosh im late, great content, love the effort you put in making the videos

    • @BroCodez
      @BroCodez  4 года назад +2

      Haha you're not late. thanks DBest

  • @_Anna_Nass_
    @_Anna_Nass_ 3 года назад

    I will like every video of yours I watch

  • @kobby1979
    @kobby1979 4 года назад +3

    bro code thank you very much now because of you I can code my own java gui application but please am having a little problem with api, am trying to create a music downloader software using api from different website but I can't figure it out so please can you make video about how to use api in creating java swing application please !!! hope to hear from you , I have learnt alot from you and hope to keep on learn

    • @PrayRNGesus69
      @PrayRNGesus69 4 года назад +1

      What api are you trying to use?

    • @kobby1979
      @kobby1979 4 года назад

      @@PrayRNGesus69 i have try spotify and deezer api

    • @kobby1979
      @kobby1979 4 года назад

      bro code please make a video for me cuz I can't stand it anymore

  • @nigistgebremeskel9519
    @nigistgebremeskel9519 Год назад

    🥰🥰🥰much love🥰🥰🥰

  • @miggiegarcia6213
    @miggiegarcia6213 Год назад

    Do you have any videos about mouse clicking and the image changing?

  • @keelgreene8060
    @keelgreene8060 2 года назад

    Awesome just what I've been looking for. Keep up the great content bro

  • @ngehbrandon9491
    @ngehbrandon9491 Год назад

    Thanks for this bro, but please how can we code mouselistner to multiple labels 🙏

  • @totoybeee9929
    @totoybeee9929 2 года назад

    Bro Code, can you please show me how to start like you just open the app first until creating project will appear, and to that last part before starting coding Bro Code.

  • @alec7059
    @alec7059 2 года назад

    Thank you very much! You saved me!

  • @commander_blaze7829
    @commander_blaze7829 2 года назад

    nice

  • @nabitawaluka2825
    @nabitawaluka2825 Год назад

    thanks so much for the video. its rely clear and understandable

  • @ahmadal-anzi7160
    @ahmadal-anzi7160 2 года назад

    Good

  • @sudhanshukumar9652
    @sudhanshukumar9652 Год назад

    In my program the icon is not adding . What should I do?😢

  • @lgui100
    @lgui100 Год назад

    Hi. Are all theese java lessons aplyable to cell phones as well? Because I don't see any emulator or cell phone image in any of them.. do they aply do android systems?

  • @kemann3815
    @kemann3815 3 года назад

    Awesome and great and all the good stuff! 👍

  • @elionayzuridasilveira4140
    @elionayzuridasilveira4140 4 месяца назад

    👍💯

  • @Paul122M
    @Paul122M 3 года назад +1

    Hello, is it possible to get the x, y position of the mouse in relation to a component? Mouse to Frame or panel for example? If yes what should I search for?

    • @bozobozo7432
      @bozobozo7432 3 года назад +1

      hi, try component.getMousePosition().getX(), in place of component put label, or other component(i didn't tested on other components but should work). If you want constant update mouse position then implements MouseMotionListener interface and put above code in desired method.
      And write later how it worked out

  • @progtest109
    @progtest109 2 года назад

    My label not displayed , what is it connected with.

  • @ninewaiyan928
    @ninewaiyan928 7 месяцев назад

    Thankful

  • @nawfalnjm5699
    @nawfalnjm5699 3 года назад +1

    great video ! thanks

  • @kravykriss
    @kravykriss 3 года назад

    Thanx soo much
    It helped me a lot with my homework

  • @eugenezuev7349
    @eugenezuev7349 5 месяцев назад

    Great!

  • @NatyTor
    @NatyTor 2 года назад

    ho bro! you so good! im realy anjoy in your videos man!!❤❤

  • @mindreader860
    @mindreader860 3 года назад +1

    Great Bro♥

  • @tanhoyzer
    @tanhoyzer Год назад

    You are the best! :)

  • @erginrusheku5637
    @erginrusheku5637 2 года назад

    i like your videos BRO

  • @petrbarabas4807
    @petrbarabas4807 3 года назад

    Nice tutorial,thanks mate

  • @majid1885
    @majid1885 3 года назад

    awesome, Thank you

  • @yasserj3693
    @yasserj3693 3 года назад

    You are a legend

  • @kurt5242
    @kurt5242 2 года назад

    Thanks

  • @maxwong1768
    @maxwong1768 2 года назад +1

    // Part 3
    // return true if cursor is within the face area .
    public boolean isCursorInFace()
    {
    boolean isCursorInFace = false ;

    // get the distance between the cursor and the face center .
    // √((y2-y1)^2 + (x2-x1)^2)
    double distance = Math.sqrt(Math.pow(cursorRelativeX - (faceRelativeX + faceWidth/2) , 2) + Math.pow(cursorRelativeY - (faceRelativeY + faceHeight/2) , 2)) ;

    // if that distance is less than the radius of face .
    if (distance

    • @Silly915
      @Silly915 Год назад

      you can reply to your own comments

  • @nobodynope2507
    @nobodynope2507 3 года назад +1

    yessssss i dont need jbuttons any more :)

  • @joojoo6010
    @joojoo6010 2 года назад

    i like this

  • @trailblazer6842
    @trailblazer6842 2 года назад

    thank you mate

  • @leviplays7466
    @leviplays7466 8 месяцев назад

    You're the Bro

  • @psgblogs
    @psgblogs Год назад

    ❤️

  • @zari_723
    @zari_723 2 года назад

    thanks

  • @ibrahimylmaz8378
    @ibrahimylmaz8378 2 года назад

    thanks bro

  • @riyazurrahmanm7049
    @riyazurrahmanm7049 2 года назад

    Thank u

  • @shofiqul0023
    @shofiqul0023 3 года назад

    where do you find these emoji pngs?

  • @theattacktitan4616
    @theattacktitan4616 3 года назад +1

    when I try this it can't decide wether I clicked or released

  • @scrimer1221
    @scrimer1221 12 дней назад

    am i the only one whose code with the emojis is not working????

  • @kamabokogonpachiro5783
    @kamabokogonpachiro5783 6 месяцев назад

    thx

  • @kingkock1
    @kingkock1 2 года назад

    ace thanks

  • @zariyashfeenmakbulstudent574
    @zariyashfeenmakbulstudent574 3 года назад

    👍🏻

  • @GerardoBelot
    @GerardoBelot 3 года назад

    Bro, I like you!! code sence please!! XD

  • @improvisthenics
    @improvisthenics Год назад

    people who watch Bro Code: 🗿🗿🗿🗿

  • @abdelkaremhomidi7322
    @abdelkaremhomidi7322 2 года назад

    broooooo

  • @adnanhabib3059
    @adnanhabib3059 Год назад

  • @francescotartaglia3700
    @francescotartaglia3700 8 месяцев назад

  • @angelcastineira2561
    @angelcastineira2561 2 года назад

    🐭🐭🐭

  • @huynhuctruong7201
    @huynhuctruong7201 2 года назад

    i love you :v

  • @Monsta1291
    @Monsta1291 2 года назад

    .

  • @MrLoser-ks2xn
    @MrLoser-ks2xn 2 года назад

    Thanks

  • @MrLoser-ks2xn
    @MrLoser-ks2xn Год назад