Advice to implement a mouse listener for card game

Hi,
I am wondering about the best way to apply a mouselistener in my card game.
- i only want to listen for 'clicks'
- I have a JFrame with a JPanel inside. The JPanel has a null layout and many JLabels. The JLabels are the cards, i want to listen for mouse clicks on these 'cards'
I have seen it is not possible to apply a mouse listener to a JPanel or JLabel so is the most efficient way to apply the listener to the JFrame and then use getComponent () to determine which JLabel has been clicked ? or is there a better way ?
any thoughts appreciated . .

hey dubai, thanks for your quick help today, it is much appreciated !
i know the event should provide a reference to the source, i use the toString to overide the methods in the mouseEvent object and im printing this string to the console. It gives me the correct dimensions within my JPanel of where i clicked but the source is always given as the panel name. Have you any idea why it does not return the name of the JLabel ? I checked out the Action interface, thanks, it cud be very useful to seperate the code by using this.

Similar Messages

  • How to set mouse listener for title bar of JFrame ?

    Hi, all
    How to we can set mouse listener for title bar of JFrame ?
    Please help

    Again, why did you not state this in your original
    question? Do we have to ask you every time what your
    actual requirement is?
    As I said in your last posting, if you don't give us
    the reuqirement in you question we can't help you.
    Sometimes your solution may be on the right track
    sometimes it isn't. We waste time guessing what your
    are trying to do if you don't give us the
    requirement.
    I gave you the answer in your other posting on this
    topic. The AWTEventListener can listen to events
    other than MouseEvents.
    The Swing tutorial has a list of most of the events.
    Pick the events you want to listen for:
    http://java.sun.com/docs/books/tutorial/uiswing/events
    /handling.htmlthe first, i am sory because my requirement not clear so that it wasted everybody time.
    The second, thank for your answer
    The third, AWTEvenListener do not support listener event on title bar
    but ComponentListener can know when we can change frame position.
    please see below that ComponentListener can handle action:
    public void componentHidden(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Hidden");
        public void componentMoved(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Moved");
        public void componentResized(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Resized ");           
        public void componentShown(ComponentEvent e) {
            displayMessage(e.getComponent().getClass().getName() + " --- Shown");
        }Thanks for all supported your knowledge, you are great !

  • How to add mouse listener for a single row alone

    I have a requirement. In a JTable when I double click a particular row the cells in the row should set to the width which I have provided.
    The problem with my code is when I click fourth row in the table, the first row gets adjusted.
    So how I need help is
    only if I click the first row, the first row cell size should get adjusted not when I click fourth row.
    Similarly if I give some cell width and height for fourth row cells, then when I double click the fourth row, the fourth should alone get adjusted and not the other rows.
    Hope I have explained clearly.
    How can it be achieved?
    Please find below my code. Everything is hardcoded. So it may look messy. Please excuse.
    // Imports
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class SimpleTableExample extends JFrame {
    // Instance attributes used in this example
    private JPanel topPanel;
    private JTable table;
    private JScrollPane scrollPane;
    String data1 = "";
    String data2 = "123456789ABCDEFGHIJKLMNOPQRSTUVQWXYZabcdefghijklmnopqrstuvwxyzaquickbrownfoxjumpedoverthelazydog";
    int size = data2.length();
    // Constructor of main frame
    public SimpleTableExample() {
         // Set the frame characteristics
         setTitle("Simple Table Application");
         setSize(400, 200);
         setBackground(Color.gray);
         // Create a panel to hold all other components
         topPanel = new JPanel();
         topPanel.setLayout(new BorderLayout());
         getContentPane().add(topPanel);
         // Create columns names
         String columnNames[] = { "SEL", "DESIGN DATA", "PART NUMBER" };
         // Create some data
         String dataValues[][] = { { data1, data2, "67", "77" },
              { "", "43", "853" }, { "", "89.2", "109" },
              { "", "9033", "3092" } };
         DefaultTableModel model = new DefaultTableModel(dataValues, columnNames);
         model.addColumn("PART TITLE");
         model.addColumn("SPECIAL INSTRUCTIONS");
         table = new JTable(model) {
         public boolean isCellEditable(int rowIndex, int colIndex) {
              return false;
         // set specific row height
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         int colInd = 0;
         TableColumn col = table.getColumnModel().getColumn(colInd);
         int width = 50;
         col.setPreferredWidth(width);
         int colInd2 = 1;
         TableColumn col2 = table.getColumnModel().getColumn(colInd2);
         int width2 = 100;
         col2.setPreferredWidth(width2);
         int colInd3 = 2;
         TableColumn col3 = table.getColumnModel().getColumn(colInd3);
         int width3 = 10;
         col3.setPreferredWidth(width3);
         int colInd4 = 3;
         TableColumn col4 = table.getColumnModel().getColumn(colInd4);
         int width4 = 10;
         col4.setPreferredWidth(width4);
         int colInd5 = 4;
         TableColumn col5 = table.getColumnModel().getColumn(colInd5);
         int width5 = 10;
         col5.setPreferredWidth(width5);
         table.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
              if (e.getClickCount() == 2) {
              JTable target = (JTable) e.getSource();
              int row = target.getSelectedRow();
              int column = target.getSelectedColumn();
              TableColumn col1 = table.getColumnModel().getColumn(0);
              col1.setPreferredWidth(50);
              TableColumn col2 = table.getColumnModel().getColumn(1);
              col2.setPreferredWidth(400);
              table.getColumnModel().getColumn(1).setCellRenderer(
                   new TableCellLongTextRenderer());
              table.setRowHeight(50);
              TableColumn col5 = table.getColumnModel().getColumn(4);
              col5.setPreferredWidth(200);
         // Create a new table instance
         // table = new JTable(dataValues, columnNames);
         // Add the table to a scrolling pane
         scrollPane = new JScrollPane(table);
         topPanel.add(scrollPane, BorderLayout.CENTER);
    // Main entry point for this example
    public static void main(String args[]) {
         // Create an instance of the test application
         SimpleTableExample mainFrame = new SimpleTableExample();
         mainFrame.setVisible(true);
    class TableCellLongTextRenderer extends JTextArea implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
         boolean isSelected, boolean hasFocus, int row, int column) {
         this.setText((String) value);
         this.setWrapStyleWord(true);
         this.setLineWrap(true);
         // set the JTextArea to the width of the table column
         setSize(table.getColumnModel().getColumn(column).getWidth(),
              getPreferredSize().height);
         if (table.getRowHeight(row) != getPreferredSize().height) {
         // set the height of the table row to the calculated height of the
         // JTextArea
         table.setRowHeight(row, getPreferredSize().height);
         return this;
    Edited by: 915175 on Aug 3, 2012 4:24 AM

    Hi
    Try below code. Hope this will help
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    public class SimpleTableExample extends JFrame {
    private JPanel topPanel;
    private JTable table;
    private JScrollPane scrollPane;
    String data1 = "";
    String data2 = "123456789ABCDEFGHIJKLMNOPQRSTUVQWXYZabcdefghijklmnopqrstuvwxyzaquickbrownfoxjumpedoverthelazydog";
    int size = data2.length();
    // Constructor of main frame
    public SimpleTableExample() {
    // Set the frame characteristics
    setTitle("Simple Table Application");
    setSize(400, 200);
    setBackground(Color.gray);
    // Create a panel to hold all other components
    topPanel = new JPanel();
    topPanel.setLayout(new BorderLayout());
    getContentPane().add(topPanel);
    // Create columns names
    String columnNames[] = { "SEL", "DESIGN DATA", "PART NUMBER" };
    // Create some data
    String dataValues[][] = { { data1, data2, "67", "77" },
    { "", "43", "853" }, { "", "89.2", "109" },
    { "", "9033", "3092" } };
    DefaultTableModel model = new DefaultTableModel(dataValues, columnNames);
    model.addColumn("PART TITLE");
    model.addColumn("SPECIAL INSTRUCTIONS");
    table = new JTable(model) {
    public boolean isCellEditable(int rowIndex, int colIndex) {
    return false;
    // set specific row height
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    int colInd = 0;
    TableColumn col = table.getColumnModel().getColumn(colInd);
    int width = 50;
    col.setPreferredWidth(width);
    int colInd2 = 1;
    TableColumn col2 = table.getColumnModel().getColumn(colInd2);
    int width2 = 100;
    col2.setPreferredWidth(width2);
    int colInd3 = 2;
    TableColumn col3 = table.getColumnModel().getColumn(colInd3);
    int width3 = 10;
    col3.setPreferredWidth(width3);
    int colInd4 = 3;
    TableColumn col4 = table.getColumnModel().getColumn(colInd4);
    int width4 = 10;
    col4.setPreferredWidth(width4);
    int colInd5 = 4;
    TableColumn col5 = table.getColumnModel().getColumn(colInd5);
    int width5 = 10;
    col5.setPreferredWidth(width5);
    // Cell Render should apply on each column -- add by Rupali
    for(int i=0; i< table.getColumnModel().getColumnCount(); i++){
    table.getColumnModel().getColumn(i).setCellRenderer( new TableCellLongTextRenderer());
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    if (e.getClickCount() == 2) {
    JTable target = (JTable) e.getSource();
    int row = target.getSelectedRow();
    int column = target.getSelectedColumn();
    setTableCellHeight(table,row,column); //Added by Rupali
    TableColumn col1 = table.getColumnModel().getColumn(0);
    col1.setPreferredWidth(50);
    TableColumn col2 = table.getColumnModel().getColumn(1);
    col2.setPreferredWidth(400);
    TableColumn col5 = table.getColumnModel().getColumn(4);
    col5.setPreferredWidth(200);
    // Create a new table instance
    // table = new JTable(dataValues, columnNames);
    // Add the table to a scrolling pane
    scrollPane = new JScrollPane(table);
    topPanel.add(scrollPane, BorderLayout.CENTER);
    * Created By Rupali
    * This will set cell's height and column's width
    * @param table
    * @param row
    * @param column
    public void setTableCellHeight(JTable table, int row, int column) {
    // set the JTextArea to the width of the table column
    setSize(table.getColumnModel().getColumn(column).getWidth(),
    getPreferredSize().height);
    if (table.getRowHeight(row) != getPreferredSize().height) {
    // set the height of the table row to the calculated height of the
    // JTextArea
    table.setRowHeight(row, getPreferredSize().height);
    // Main entry point for this example
    public static void main(String args[]) {
    // Create an instance of the test application
    SimpleTableExample mainFrame = new SimpleTableExample();
    mainFrame.setVisible(true);
    class TableCellLongTextRenderer extends JTextArea implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    this.setText((String) value);
    this.setWrapStyleWord(true);
    this.setLineWrap(true);
    return this;
    }

  • How can i implement a mouse listener event on jtable cell?

    I create JTable using a resultset,at the end of each row i add an image using JLabel(set imageicon of the JLabel).
    i want to track the event when user click on that image.
    What can i do for that?.
    I tried by implementing mouseListener interface for the JLabel but it's not working properly.

    Hi,
    Add MouseListener to the JTable.
    when the user clicks on the table use the method
    getValueAt( int selectedRow,int selectedColumn) to get the contents.
    Object obj = getValueAt( int selectedRow,int selectedColumn) .
    (If obj instance of JLabel)
    do your functionality.
    Hope this helps
    Cheers :)
    Nagaraj

  • Implement a Mouse Listener and another Listener

    HI, i was wondering if it was possible to implement an Actionlistener and a Mouselistener at the same time, kind of like this (Syntax is impossible i know, but just to show a point)
    public class TrafficLight extends JApplet implements ActionListener and MouseListener ---You can't do it like that----, but if anybody knows how to actually do it, I would greatly appreciate it.

    When i do that, i get this error
    TrafficLight is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
    And i am doing this,
    public void mousepressed (MouseEvent e){
         }and this
    jLabel2.addMouseListener(this);I am probably forgetting somethig really simple.

  • Help Needed for Mouse Listener

    Ive created an item in a JPanel with a mouse listener for when it is clicked, I have a JFrame class called ScoreWindow(). What do i put into the mouse listener so that it will open up an instance of ScoreWindow().
    class MouseListener extends MouseAdapter{
            public void mouseClicked(MouseEvent e) {
        }Is the extent of my mouse listener so far (i know nearly nothing).
    The class i am adding this to is a shape drawn on a JPanel if this effects things, can you tell me what class type i need to make the item.
    Edited by: IInferno on Apr 23, 2009 3:49 PM
    Edited by: IInferno on Apr 23, 2009 4:18 PM

    So id add something like
    ScoreWindow window = new ScoreWindow;in the thing?
    this is my Network class so far which is the object i want to click to open the ScoreWindow class. I have run the ScoreWindow class already and it runs
    fine.(as far as ive coded it)
    package jeismus;
    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.Color;
    * @author Ben
    public class Network {
        public Network(JPanel s) {
            playArea = s;
            paintNetwork();
        public void paintNetwork() {
             Graphics g = playArea.getGraphics();
             Graphics2D g2 = (Graphics2D)g;
             sqr.setFrame(c, d, rectWidth, rectHeight);
             g2.draw(sqr);
             g2.dispose();
        private static class ScoreData {
          int x, y, NoteID, Octave;
          String Key, NoteDuration;
        class MouseListener extends MouseAdapter{
            public void mousePressed(MouseEvent e) {
            public void mouseClicked(MouseEvent e) {
        class MouseMotionListener extends MouseAdapter{
            public void mouseDragged(MouseEvent e) {
            public void mouseMoved(MouseEvent e) {
        public int getNetID(){
             return NetID;
        private int NetID;
        private ScoreData[] stringData;
        private double c = 200;
        private double d = 200;
        private double rectHeight = 30;
        private double rectWidth = 30;
        private double a = c + rectHeight;
        private double b = d + rectWidth;
        private int count = 0;
        private JPanel playArea;
        private Rectangle2D.Double  sqr = new Rectangle2D.Double();
        private Point2D startpoint = new Point2D.Double(a, b);
        private Point2D endpoint = new Point2D.Double(c, d);
    }

  • Implementing Country legal changes for US/Canada/Australia

    Hello Experts,
    We need your expertise advice in implementing Country Legal Changes for US/Canada/Australia.
    Currently we are at HRSP 29, implemented HRSP41 in this week and implementing HRSP 42 in next month, Can you please advice us are there any specific notes related to Country Legal Changes needs to be implemented (manually and automatically with HRSP42)?
    Any help would be appreciated!!!
    Thanks
    Sreeni

    Since you are talking of HRSP 41, you should be on SAP_HR EnhP6.04.
    You should visit service.sap.com/hrcanada to read on what notes must be applied after the base HRSP (or CLC).  If I remember correctly, the "Year-End Note for Canada" should be available on December 1st, and if required, a Delta Note will become available mid-December.  There may also be individual Notes to apply up to late February if some things need to be corrected for the T4/T4A process (Forms, Magmedia, etc...).
    You should also visit service.sap.com/hrusa for information on US Year-end, and the ERP HCM Payroll North America discussion forum (SAP ERP HCM Payroll North America).
    As for Australia, the SAP Service Marketplace webpage (when you visit /hrcanada or /hrusa) has a "menu" on the left hand side of the page where you could follow SAP ERP Human Capital Management > Country Information > Asia-Pacific > Australia.
    An other source of information may be the Wikis on the Country's Payroll (http://wiki.sdn.sap.com/wiki/display/ERPHCM/ERPHumanCapital+Management)

  • Need a Mouse Listener

    I have a main menu with a series of buttons, when you press a
    button, it triggers an animation for a fly-out menu with a series
    of buttons to trigger other events. Everything works fine up to
    this point.
    What I need is an independent hit area underneath the buttons
    on the fly-out menu so that when the mouse leaves the area, the
    fly-out menu will retract. The current methods require that the
    mouse be down or released, but I need a mouse listener for an
    'over' and 'out' state so that when the mouse is over the hit area,
    the fly-out menu will show and when the mouse leaves the hit area,
    the fly-out menu will retract.
    I've have googled and read and am now totally confused. Can
    anyone point me in the right direction to solve this
    problem?

    you shouldn't need setInterval, and its incorrectly set up.
    If you wanted to use a setInterval call instead of the onMouseMove
    event then you could do it as follows (but its NOT good
    programming, just providing it for illustrative purposes)
    remove the line Mouse.addListener... etc (you wouldn't do
    both an onMouseMove check and a setInterval check)
    and put in
    var ML = setInterval(mouseListener,"onMouseMove",500);
    That should work... I haven't tested it. Nor do I recommend
    it. I think you're better off with onMouseMove.
    If you are going to use the setInterval its better to change
    the name of the
    onMouseMove everywhere that it appears to something like
    onIntervalCheck just so it makes more sense to you if you
    look at it later on (or for someone else too). Using onMouseMove
    shouldn't be too demanding on the CPU - and if its noticeable it
    should only be for very short bursts.
    BTW You can also delete or comment out the trace actions...
    they were just there to help you understand how it works. Best not
    to leave them in when you do a final publish (or exclude trace
    actions in your publish settings)

  • Assigning mouse listener to JTableHeader

    Can anyone point me to an example or know how to assign a mouselistener to the individual column headers in JTable Header?

    I haven't tried to set a mouse listener for individual columns, but here is how you can set a listener for the entire header and check which column was clicked:
    JTableHeader tableHeader = table.getTableHeader();
    tableHeader.addMouseListener( new MouseAdapter()
         public void mouseClicked(MouseEvent e)
              TableColumnModel columnModel = table.getColumnModel();
              int column = columnModel.getColumnIndexAtX( e.getX() );
              if (e.getClickCount() == 1 && column == 0)
                   do something for column 0
    });

  • Multiple Buttons in JTable Headers:  Listening for Mouse Clicks

    I am writing a table which has table headers that contain multiple buttons. For the header cells, I am using a custom cell renderer which extends JPanel. A JLabel and JButtons are added to the JPanel.
    Unfortunately, the buttons do not do anything. (Clicking in the area of a button doesn't appear to have any effect; the button doesn't appear to be pressed.)
    Looking through the archives, I read a suggestion that the way to solve this problem is to listen for mouse clicks on the table header and then determine whether the mouse clicks fall in the area of the button. However, I cannot seem to get coordinates for the button that match the coordinates I see for mouse clicks.
    The coordinates for mouse clicks seem to be relative to the top left corner of the table header (which would match the specification for mouse listeners). I haven't figured out how to get corresponding coordinates for the button. The coordinates returned by JButton.getBounds() seem to be relative to the top left corner of the panel. I hoped I could just add those to the coordinates for the panel to get coordinates relative to the table header, but JPanel.getBounds() gives me negative numbers for x and y (?!?). JPanel.getLocation() gives me the same negative numbers. When I tried JPanel.getLocationOnScreen(), I get an IllegalComponentStateException:
    Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    Can someone tell me how to get coordinates for the button on the JTableHeader? Or is there an easier way to do this (some way to make the buttons actually work so I can just use an ActionListener like I normally would)?
    Here is relevant code:
    public class MyTableHeaderRenderer extends JPanel implements TableCellRenderer {
    public MyTableHeaderRenderer() {
      setOpaque(true);
      // ... set colors...
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setLayout(new FlowLayout(FlowLayout.LEADING));
      setAlignmentY(Component.CENTER_ALIGNMENT);
    public Component getTableCellRendererComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row,
                                                     int column){
      if (table != null){
        removeAll();
        String valueString = (value == null) ? "" : value.toString();
        add(new JLabel(valueString));
        Insets zeroInsets = new Insets(0, 0, 0, 0);
        final JButton sortAscendingButton = new JButton("1");
        sortAscendingButton.setMargin(zeroInsets);
        table.getTableHeader().addMouseListener(new MouseAdapter(){
          public void mouseClicked(MouseEvent e) {
            Rectangle buttonBounds = sortAscendingButton.getBounds();
            Rectangle panelBounds = MyTableHeaderRenderer.this.getBounds();
            System.out.println(Revising based on (" + panelBounds.x + ", "
                               + panelBounds.y + ")...");
            buttonBounds.translate(panelBounds.x, panelBounds.y);
            if (buttonBounds.contains(e.getX(), e.getY())){  // The click was on this button.
              System.out.println("Calling sortAscending...");
              ((MyTableModel) table.getModel()).sortAscending(column);
            else{
              System.out.println("(" + e.getX() + ", " + e.getY() + ") is not within "
                                 + sortAscendingButton.getBounds() + " [ revised to " + buttonBounds + "].");
        sortAscendingButton.setEnabled(true);
        add(sortAscendingButton);
        JButton button2 = new JButton("2");
        button2.setMargin(zeroInsets);
        add(button2);
        //etc
      return this;
    }

    I found a solution to this: It's the getHeaderRect method in class JTableHeader.
    table.getTableHeader().addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e) {
        Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
        Rectangle buttonBounds = sortAscendingButton.getBounds();
        buttonBounds.translate(panelBounds.x, panelBounds.y);
        if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){  // The click was on this button.
          ((MyTableModel) table.getModel()).sortAscending(column);
    });

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

  • Listening for mouse move from JFrame?

    Hi
    I'm facing a problem when I wanted to use the JFrame's method: addMouseListener( ) to listening for the mouse whether it moves from a JFrame.
    In my code the JFrame containts three components:
    public class NFrame extends JFrame{
    JPanel contentPane = (JPanel)super.getContentPane();
    contentPane.setLayout(new BorderLayout());
    JMenuBar jMenubar=new jMenuBar();
    JTabbedPane jTabPane=new JTabbedPane(JTabbedPane.LEFT,JTabbedPane.WRAP_TAB_LAYOUT);
    JPanel bottonPane=new JPanel();
    contentPane.add(jMenuBar,BorderLayout.NORTH);
    contentPane.add(jTabPane,BorderLayout.CENTER);
    contentPane.add(bottomPane,BorderLayout.SOUTH);
    addMouseListener(new MouseAdapter() {
    public void mouseExited(MouseEvent e) {
    System.out.println("Mouse remove from JFrame");
    Because the JTabbedPane has a default mouse Listener, thus the mouse event is caught by jTabPane and the application does not print the above message when mouse moves from jTabPane.
    Could anybody give me some hints?
    Thanks!

    In this case there should probably not be a sleep()
    at all. You might want to do that sort of thing when
    you have a new thread whose job is to have
    non-GUI-related functionality (like a clock ticking,
    or sprites moving in a game independently). For
    standard GUI interaction, the GUI thread takes care
    of things and you don't need to wait at all. You're
    already waiting, basically.Oh, I see! The OP is doing quite useless things!
    I didn't see such f**lish things in the past!
    The OP should learn the basics for GUI and event mechanism.
    http://java.sun.com/docs/books/tutorial/uiswing/

  • Need some OO design pointers for a Java card game I wrote for uni

    Hi,
    I hope a few of you Java sifus can help me understand I dilemma I keep finding myself in.
    I created a card game for a university assignment which works great but its not very OO at the moment.
    I only have 3 classes; a Card class, a Deck class and a Game class which contains all my GUI, AI, Game Controller, Player and Hand code.
    The assignment is over but I feel like enhancing the game, adding animation, multiplayer, several AI agents etc.
    The first thing I have attempted is animation and I've hit a brick wall. I am trying to create animation for my card game whereby I have an animation showing the cards being shuffled and then an animation which shows the cards being dealt to the players. The game then commences. The cards on the GUI then need to be clickable (MouseListeners?) to play the game. If you're running Windows 7, load up 'Hearts' and you'll know what I'm trying to achieve.
    I don't understand how the GUI, and Card class need to be seperated so that its good OO.
    If I give you a few snippets of code, it might explain the situation:
    A snippet of my card class is as follows:
    import javax.swing.*;
    public class Card extends JLabel //Each card is a JLabel
         private int value;                    //variable for the value of the card
         private int suit;                         //variable for the suit of the card
         private ImageIcon frontOfCard;     //Displays the image of the front of the cards
         private ImageIcon backOfCard;          //displays the image of the back of the cards
         public Card (int Value, int Suit, ImageIcon front, ImageIcon back)
              value = Value;               
              suit = Suit;               
              frontOfCard = front;     
              backOfCard = back;
              setIcon(backOfCard);     //To make it non-visible when dealt
         }As you can see, each card is a JPanel. I've been told by some I shouldn't extend JPanel but rather that I should have a BufferedImage/Image instance variable for each card as the image of the card. The thing is that I need each card displayed on the GUI which can then be clickable. When it is clicked, it is moved from the players hand, into the players move. - There needs to be an animation showing this.
    I've got the animation code figured out in terms of how to move 'images' around a screen to make a pleasing animation. The problem is there are no clickable listeners for images, so the Images needs to be inside some container; a widget which can fire events - Hence the reason I have chosen to extend JPanel for my Cards.
    and a Deck class, snippet is as follows:
    public class Deck extends JLabel //The deck will be shown on the GUI as a JLabel
         private ArrayList<Card> standardDeck;
         public Deck()
              standardDeck = new ArrayList<Card>();
              ImageIcon cardBack = new ImageIcon("CardBack.png");
              setPreferredSize(new Dimension(90, 135));
              setIcon(cardBack);
              int cardCount = 0;     //This variable counts the cards. Is used to assist in the name generation of the imageicon filename
              String str; //the imageIcon constructor accepts filenames as strings so this string holds the filename of the corresponding card image file.
              for (int a=0; a<4; a++) //putting the cards into the deck with the specifed parameters
                   for (int b=2; b<15; b++)
                        cardCount+=1;     //incrementing the card count (the card files are named 1-52 as integers)
                        str = Integer.toString(cardCount); //Integer is converted to string type before being added to string str variable
                        str += ".png"; //To complete the image filename, ".png" has to be concatenated to the string.
                        standardDeck.add(new Card(b, a, new ImageIcon(str), cardBack)); //creating and then adding the cards
         }This is how I envisage a new class diagram for my game:
    Card class
    Game Class <--- Holds a Deck instance, Players instances, and the GUI instance
    Player Class <-- Will contains hand 'instances' , but I will not create a seperate 'Hand' Class, I will use an ArrayList.
    AI Class extends Player Class
    GUI Class
    Deck Class <-- contains 52 cards
    My question is, how do I show the Cards on the GUI if my Cards are in a Deck and the Deck is held in the Game class?
    Please note that there are 52 cards, so potentially 52 images on the GUI, each of which needs to be clickable. When clicked, the cards are moved about, e.g. from the deck to a players hand, from a players hand back to the deck, from a players hand to a players current move hand.
    etc
    I've read that GUI, program control, and logic should be seperated. If thats the case, what do I have in my GUI class if the Cards (which are JPanels) are held in the Deck class which in turn is held in the Game class?
    Any help on this would be greatly appreciated!
    I know what I have written may not be fully clear. I find it hard sometimes to fully convey a problem at hand. Please let me know if you don't understand what I've written and I'll do my best to explain further.

    Faz_86 wrote:
    Hi,
    I hope a few of you Java sifus can help me understand I dilemma I keep finding myself in.
    I created a card game for a university assignment which works great but its not very OO at the moment.
    I only have 3 classes; a Card class, a Deck class and a Game class which contains all my GUI, AI, Game Controller, Player and Hand code.
    The assignment is over but I feel like enhancing the game, adding animation, multiplayer, several AI agents etc.
    Admirable, and the best way to learn, doing something that interests you.
    The first thing I have attempted is animation and I've hit a brick wall. I am trying to create animation for my card game whereby I have an animation showing the cards being shuffled and then an animation which shows the cards being dealt to the players. The game then commences. The cards on the GUI then need to be clickable (MouseListeners?) to play the game. If you're running Windows 7, load up 'Hearts' and you'll know what I'm trying to achieve.
    I don't understand how the GUI, and Card class need to be seperated so that its good OO.
    If I give you a few snippets of code, it might explain the situation:
    A snippet of my card class is as follows:
    Do a quick Google on the model view controller pattern. Your listeners are your controllers. Your JPanel, JButton, etc. are your view. The AI, Player, Card and Deck (and presumably something like Score) are your model. Your model should be completely testable and not dependent on either the controller or the view. Imagine you could play the game from the command line. Get that working first. Then you can add all the bells and whistles for the UI.
    import javax.swing.*;
    public class Card extends JLabel //Each card is a JLabel
    (redacted)
    As you can see, each card is a JPanel. I've been told by some I shouldn't extend JPanel but rather that I should have a BufferedImage/Image instance variable for each card as the image of the card. The thing is that I need each card displayed on the GUI which can then be clickable. When it is clicked, it is moved from the players hand, into the players move. - There needs to be an animation showing this.Extending JPanel is fine. As you noted, you need something to add listeners to. However, I would separate things a bit. First, a card really only has a rank and suit (and perhaps an association to either the deck or a player holding the card). The notion of setIcon() is where you are tripping up. The card itself exists in memory. You should be able to test a card without using a UI. Create a separate class (CardPanel or something similar) that has a reference to a Card and the additional methods needed for your UI.
    I've got the animation code figured out in terms of how to move 'images' around a screen to make a pleasing animation. The problem is there are no clickable listeners for images, so the Images needs to be inside some container; a widget which can fire events - Hence the reason I have chosen to extend JPanel for my Cards.
    and a Deck class, snippet is as follows:
    public class Deck extends JLabel //The deck will be shown on the GUI as a JLabel
         private ArrayList<Card> standardDeck;
         public Deck()
              standardDeck = new ArrayList<Card>();
              ImageIcon cardBack = new ImageIcon("CardBack.png");
              setPreferredSize(new Dimension(90, 135));
              setIcon(cardBack);
              int cardCount = 0;     //This variable counts the cards. Is used to assist in the name generation of the imageicon filename
              String str; //the imageIcon constructor accepts filenames as strings so this string holds the filename of the corresponding card image file.
              for (int a=0; a<4; a++) //putting the cards into the deck with the specifed parameters
                   for (int b=2; b<15; b++)
                        cardCount+=1;     //incrementing the card count (the card files are named 1-52 as integers)
                        str = Integer.toString(cardCount); //Integer is converted to string type before being added to string str variable
                        str += ".png"; //To complete the image filename, ".png" has to be concatenated to the string.
                        standardDeck.add(new Card(b, a, new ImageIcon(str), cardBack)); //creating and then adding the cards
         }This is how I envisage a new class diagram for my game:
    I am not an animation buff, so I will assume the above works.
    Card classRemove the UI aspects to this class, and I think you are all set here.
    Game Class <--- Holds a Deck instance, Players instances, and the GUI instancePresumably this is where main() resides. It will certainly have a reference to model classes (player, game, deck, etc.) and likely the master JFrame (or a controller class you create yourself).
    Player Class <-- Will contains hand 'instances' , but I will not create a seperate 'Hand' Class, I will use an ArrayList.Does a player really have multiple hands? It seems to me more of a one-to-one relationship (or a player has a one-to-many relationship to Card).
    AI Class extends Player ClassWhy extend Player? Create a Player interface, then have a HumanPlayer and AIPlayer implementation. Common parts could be refactored out into either a helper class (delegation) or AbstractPlayer (inheritance).
    GUI ClassMy assumption is that this class has a reference to the master JFrame.
    Deck Class <-- contains 52 cards
    Yes. You may end up recycling this class such that a Deck can also function as a Hand for a given player. If there are differences between the two, create an interface and have a Hand and a Deck implementation. Coding to interfaces is a good thing.
    My question is, how do I show the Cards on the GUI if my Cards are in a Deck and the Deck is held in the Game class?You need to pass a reference to the appropriate view class. That is how MVC works. The controller receives a request from the view, dispatches to some model functionality you write (such as GameRulesEngine, Deck, etc.) and returns a result to the view (which could be the same view or a different one, imagine someone clicking 'high scores').
    Please note that there are 52 cards, so potentially 52 images on the GUI, each of which needs to be clickable. When clicked, the cards are moved about, e.g. from the deck to a players hand, from a players hand back to the deck, from a players hand to a players current move hand.
    etc
    That is up to you to write the animation code. In principle, you have a mouse listener, and then you take the appropriate rendering steps.
    I've read that GUI, program control, and logic should be seperated. If thats the case, what do I have in my GUI class if the Cards (which are JPanels) are held in the Deck class which in turn is held in the Game class?
    See above.
    Any help on this would be greatly appreciated!
    You are welcome.
    I know what I have written may not be fully clear. I find it hard sometimes to fully convey a problem at hand. Please let me know if you don't understand what I've written and I'll do my best to explain further.No, you have been doing fine.
    - Saish

  • Why does a JButton automatically have a mouse listener registered with it?

    If I instantiate a JButton, I find there's a mouse listener already registered (see code below). Does anyone know why?
    Looking at the source code for JButton, I can't see how this is. If a create a dummy subclass of AbstractButton (of which JButton is a direct subclass) and instantiate that, it has no mouse listeners, and likewize with Button. So what is it about JButton?
    The reason I ask is that I've seen in a book on swing that you must call enableEvents(AWTEvent.MOUSE_EVENT_MASK) on a JButton if you want processMouseEvent to get executed. But it actually gets executed even if enableEvents hasn't been called, and the only reason for this is surely that there is a mouse listener registered, which there is, but why?
    Might the reason be that JButton extends Accessible?
    Code:
    JButton jb = new JButton("Dummy");
    MouseListener[] mls = (MouseListener[])(jb.getListeners(MouseListener.class));
    JOptionPane.showMessageDialog(this, (new Integer(mls.length)).toString(), "Number of Mouse Listeners", JOptionPane.INFORMATION_MESSAGE);

    Hello,
    That listener is installed by the JButton's UI. You might want to have a look at the source code of BasicButtonUI and BasicButtonListener to understand what they are used for. For example, mousePressed in BasicButtonListener is used to call setArmed on the JButton.
    My best advice is for you not to worry about this at all.

  • A Listener For JTable Row Selection Changed?

    Never mind... Thought of a couple other things after I posted and found ListSelectionListener. This looks like it fulfills my requirement nicely. - cimmerian76
    >>>
    TableModelListener isn't what I am looking for here. Basically, I'm looking for something that behaves in a way that is analogous to
    TreeSelectionListener's valueChanged(...). Perhaps I'm looking in the wrong places, but the only things I've found were RowSet listener (not even close)
    and TableModelListener (not exactly what I'm looking for - I'm not concerned about data in the table changing).
    The tool I'm writing displays additional information about the object in the row selected in an adjacent panel.
    This display should change every time a user selects a different row.
    I can mimic the behavior I want using a mouse listener on the table, so this isn't an emergency.
    It's more about curiosity. If I can find something that produces this functionality directly, I would prefer to use that.
    <<<
    Message was edited by:
    cimmerian76

    Hi,
    you can use this to handle selection events for the table:
    yourTable.getSelectionModel().addListSelectionListener(... );
    Now e.g. the class containing your main can implement interface ListSelectionListener.

Maybe you are looking for

  • HT1848 Can you transfer songs from one iTunes account to a new iTunes account?

    I have a friend that had a shared iTunes account with her ex-boyfriend.  They both used the account to purchase songs for themselves.  They have since separated and she has set up her own iTunes account.  She wants to transfer the songs from her iPho

  • Low memory (IPod 4,1)

    (IPod 4,1) From I installing ios 6 I have problem with memory :low memory

  • Can't print a PDF on 11x17 paper

    I am using Acrobat 10.1.9 on a mac OS 10.8.5 and can not print a PDF on 11x17 paper.  Even if I change the default paper size to 11x17 in my system prefrerences, it doesn't recognize the default setting, and prints on 8.5x11 paper no matter what.  I

  • Serviceability Reports Archive more than 7 days?

    I can't seem to find where I can set the report duration from the last 7 days to 30 days? I see in 5.0 you can set this, but in 4.1.3, I cant seem to find this. Thanks!

  • Help for Avid Editor: Cutting In defaults to Canvas

    When I cut into a timeline from the Preview window, FCP automatically jumps to the Canvas(Record) window, so that I have to hit Q to switch back to Preview window to keep watching dailies. Is there an option to leave the focus/control in the Preview