Invisible awt as a listener?

I was wondering if there was a way to have an invisible awt application that listened to all the characters typed on the keyboard and do something to them. I don't need help doing something to them I just didn't know if I could accept input with an invisible awt application.

No, AWT receives key events only if there is some focused window.
Even with Win32 API it is not a simple task - you have to use hooks.

Similar Messages

  • Invisible awt using listeners??? PLEASE ANSWER!!!

    I was wondering if there was a way to have an invisible awt application that listened to all the characters typed on the keyboard and do something to them. I don't need help doing something to them I just didn't know if I could accept input with an invisible awt application.

    WOW three identical posts!!
    http://forum.java.sun.com/thread.jsp?forum=54&thread=388348&tstart=0&trange=15
    http://forum.java.sun.com/thread.jsp?forum=54&thread=388355&tstart=0&trange=15
    http://forum.java.sun.com/thread.jsp?forum=54&thread=388353&tstart=0&trange=15

  • How to hook(Listen) to java's exception handler?

    Hello Guys,
    If you know you can replace or add new EventQueue in AWT event queue listener, so what ever events occurs, will be received by own extended class of EventQueue.
    Now how to listen to the global exception listener,
    Like,
    I want to monitor for a perticular execution of a program , which says how many exceptions are raised by Java, and which are the exceptions.
    So is there any method where i can listen using some interface for exceptions...???
    -Regards,
    Nachiket

    Hello,
    I tried to find out somethings on java.beans.ExceptionListener, but i am unable to find out any help or anything which explains how to use it.
    Regards,
    Nachiket

  • AWT thread blocking issue.

    I have a listener which is called on AWT thread, this listener does lot of backend processing by creating another thread, while the processing is going on the AWT thread is blocked causing painting issue.
    public void actionPerformed(ActionEvent e)
    // create a new thread
    Thread t = new Thread();
    t.start();
    //wait till the thread t is done
    while ( ! t.complete)
    wait();
    action Permormed is called on AWT thread.
    On a website there was solution to this was -
    Create a second thread to dispatch Events, popping them off the SystemEventQueue.
    How can I achieve this? need your comments....

    It is very dangerous to block AWT event dispatch threads. You must never do it. If you need to block your currently active GUI to wait until some process finishes, the common practice is to show modal dialog. This dialog will block the input until the process has finished. After the process finishes, you just hide the dialog.

  • Make button invisible when flv starts again

    Hi,
    Please, can some one help me and tell me how to have a button
    instance become invisible when the play button from the skin.swf
    file is clicked? There may be another way to acomplish what I am
    trying to do.
    I have a Flash 8 file with a FLVPlayback component pointing
    to a FLV file. I am using an external skin for the controls. When
    the video is finished I have it displaying a button, but if the
    person wants to start the video again the button needs to become
    invisible again. I am assuming I need to create an actionscript
    that says if the video is playing (at all ) the button is
    invisible. But how?.. is the big question for me.
    Any help would be great.
    Thanks
    thepopguy

    This is possible. You need actionscript to check the status
    of the video, if it is playing then the button goes invisible. This
    is called an event listener. You need to give the component an
    instance name - like vid. Then use this code on the frame:
    //listen for movie to play
    var vidList:Object = new Object();
    vidList.playing = function(){
    button1._visible = false;
    //any other actions go here
    vid.addEventListener ("playing",vidList);
    stop;
    //listen for movie to stop
    var vidList2:Object = new Object();
    vidList2.stopped = function(){
    button1._visible = true;
    //any other actions go here
    vid.addEventListener ("stopped",vidList2);
    stop;
    ============
    This code will actually listen for the movie to play, and
    then it will make the button invisible. It also listens for the
    movie to stop, and it make it visible again.
    Sample:
    http://www.johnkalnin.com/flashhelp/Vid-isPlaying-inv.html
    Flash 8 source:
    http://www.johnkalnin.com/flashhelp/Vid-isPlaying-inv.fla

  • Capturing keyboard Scancodes from console

    Hello,
    I had tried captuaring what would be the scan code for left arrow by using Java.I used the System.in.read().but that did not help.
    If some one is aware of how to get these scancodes from the console in Java,please let me know about that.
    Thank you.

    I fear this is not possible. The left arrow appears to be interpreted by the JVM as though you wish to move your input cursor one space to the left.
    The way mine is working is the JVM won't actually send the input data, through System.in to the application code, until I enter a newline (hit enter). If I type "123<enter>" I get the three ascii codes for the numbers 1, 2, and 3, plus the linefeed (a 10). If I type "123<leftarrow><enter>", the JVM only passes in a 1 and a 2, along with the linefeed.
    Perhaps someone has more insight on how the console input works, and whether there are any hooks or setting we can futz with to change its behavior.
    Scan codes are of course very simple to get when dealing with AWT/Swing, by listening for key events, then interrogating the event data. But that's not a solution to this.

  • Dealing with AffineTransform mouse driven rotation

    Hi there,
    I'm implementing the mouse control to navigate through an image representing a map. Pan and zoom where trivial operations, but I'm getting in trouble when trying to rotate the BufferedImage.
    I actually can perform the rotation, but because the map coordinate system gets rotated too. I have applied a trigonometric correction when performing a pan after a rotation. This was the hard part... my problem is that I have inverted the axis when panning, so dragging the mouse to the bottom of the canvas becomes a horizontal translation if we had a rotation by PI rads.
    Because original Java code is pretty big, I have coded a simple example that pans, zooms or rotates a square.
    The magic happens here:
    def performPan(self,diff):
            xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
            ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
            diff.x -= (diff.x - xa)
            diff.y -= (diff.y - ya)
            center = self.canvas.squareCenter()
            # if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)       
            self.transform.translate(diff.x, diff.y)
            #if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
        def performZoom(self,diff):     
              zoomLevel = 1.0+0.01*diff.y;
              if zoomLevel <= 0:
                  zoomLevel = 0
              center = self.canvas.windowCenter()          
              self.transform.scale(zoomLevel, zoomLevel)
        def performRotation(self,diff):
             angleStep = diff.y * 0.1
             self.theta += diff.y
             self.theta %= 2*lang.Math.PI
             center = self.canvas.squareCenter()
             self.transform.rotate(angleStep, center.x, center.y)
        def toWindowCoordinates(self,diff):
            try:
                self.transform.inverseTransform(diff,diff)
            except:
                print "error en window coordinates"I have already tried changing diff.x and diff.x sign, and commenting that trigonometric correction and uncommeting the lines concatenating two rotations surrounding the translation without sucess.
    Please, I'd appreciate some feedback. Brainstorms are welcome. :-)
    Thanks, Vicente.
    The full code:
    from javax import swing
    from java import awt, lang;
    class Listener(swing.event.MouseInputAdapter):
        def __init__(self,subject):
            self.offset = awt.geom.Point2D.Double()
            self.anchor = awt.geom.Point2D.Double()
            self.canvas = subject
            self.transform = subject.transform
            self.rectangle = subject.rectangle
            self.theta = 0.0
        def mousePressed(self,e):
            self.anchor.x = e.getX()
            self.anchor.y = e.getY()
            self.offset.x = e.getX()
            self.offset.y = e.getY()
        def mouseDragged(self,e):
            self.offset.x = e.getX()
            self.offset.y = e.getY()
            diff = awt.geom.Point2D.Double()   
            tx = self.offset.x - self.anchor.x
            ty = self.offset.y - self.anchor.y
            diff.x = tx
            diff.y = ty      
            self.anchor.x = self.offset.x
            self.anchor.y = self.offset.y
            class Painter(lang.Runnable):
                def __init__(self,canvas, listener):
                    self.canvas = canvas
                    self.listener = listener
                def run(self):
                    if e.isControlDown():
                        self.listener.performRotation(diff)
                    elif swing.SwingUtilities.isLeftMouseButton(e):       
                        self.listener.performPan(diff)       
                    if swing.SwingUtilities.isRightMouseButton(e):
                        self.listener.performZoom(diff)
                    self.canvas.repaint()
            work = Painter(self.canvas, self)
            swing.SwingUtilities.invokeLater(work)
        def mouseReleased(self,e):
            self.color = awt.Color.red
            self.canvas.repaint()
        def performPan(self,diff):
            xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
            ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
            diff.x -= (diff.x - xa)
            diff.y -= (diff.y - ya)
            center = self.canvas.squareCenter()
            if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)       
            self.transform.translate(diff.x, diff.y)
            if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
        def performZoom(self,diff):     
              zoomLevel = 1.0+0.01*diff.y;
              if zoomLevel <= 0:
                  zoomLevel = 0
              center = self.canvas.windowCenter()          
              self.transform.scale(zoomLevel, zoomLevel)
        def performRotation(self,diff):
             angleStep = diff.y * 0.1
             self.theta += diff.y
             self.theta %= 2*lang.Math.PI
             center = self.canvas.squareCenter()
             self.transform.rotate(angleStep, center.x, center.y)
        def toWindowCoordinates(self,diff):
            try:
                self.transform.inverseTransform(diff,diff)
            except:
                print "error en window coordinates"
    class Canvas(swing.JPanel):
        def __init__(self):
            self.rectangle = awt.geom.Rectangle2D.Double(0,0,50,50)
            self.transform = awt.geom.AffineTransform()   
            self.wcenter = awt.geom.Point2D.Double()
            self.rcenter = awt.geom.Point2D.Double()
            listener = Listener(self)
            swing.JPanel.addMouseMotionListener(self,listener)
            swing.JPanel.addMouseListener(self,listener)
        def paintComponent(self,g2d):
            self.super__paintComponent(g2d)
            g2d.setTransform(self.transform)
            g2d.fill(self.rectangle)
        def windowCenter(self):
            if self.wcenter.x == 0 or self.wcenter.y == 0:
                self.wcenter.x = self.getHeight()/2.0
                self.wcenter.y = self.getWidth()/2.0     
            return self.wcenter
        def squareCenter(self):
            if self.rcenter.x == 0 or self.rcenter.y == 0:
                self.rcenter.x = self.rectangle.getBounds2D().height/2.0
                self.rcenter.y = self.rectangle.getBounds2D().width/2.0       
            return self.rcenter
    frame = swing.JFrame(   title="test",
                            visible=1,
                            defaultCloseOperation = swing.JFrame.EXIT_ON_CLOSE,
                           preferredSize = awt.Dimension(400,400),
                            maximumSize = awt.Dimension(800,600),
                            minimumSize = awt.Dimension(200,200),
                            size = awt.Dimension(500,500)
    frame.add(Canvas(), awt.BorderLayout.CENTER)
    frame.pack()

    I forgot to mention that the example is written in
    Jython, because the Java was pretty big, but it is
    legible bu a Java programmer. :-)It's legible, but most of us w/out a jython compiler would have to re-write the code if we wanted to try it out. That may hurt your chances of getting a useful response (as opposed to my useless responses). ... Or it might not.
    Good luck!
    /Pete

  • AWT Event Listener not listening...

    Hi,
    I'm having problems with an AWT Event Listener on a JFrame.
    Basically, im making a tank game, so the first screen to appear is an inventory screen. The when you click start on this screen, you create a GameScreen which extends JFrame. i have an AWT Event Listener added to this frame using this code:
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener(){
    public void eventDispatched(AWTEvent e) {
    if(((KeyEvent)e).getKeyCode() == KeyEvent.VK_DOWN && e.getID() == KeyEvent.KEY_PRESSED)
    It's checking events on the arrow keys and the tab and enter keys.
    So when the this round of the game has finished, i setVisible to false, and make the inventory visible again.
    The problem is, when i set make the GameScreen visible again, the listeners aren't working.
    It seems to be working fine for 'enter', that is VK_ENTER, but not for the arrow keys...
    Any1 have any ideas??
    Any help would be great!
    Thanks,
    D.

    I am willing to bet that your problem lies in that once you return the main game screen from the inventory screen that you need to set the focus back to the main game screen. I believe, as events go, the component that has the focus is the one that will receive the events and process them according to their listener code. As I am not sure where your focus goes once you close the inventory screen and open the main screen, it could be that the wrong component has the focus.
    As far as getting the focus to the correct component is concerned, I remember myself and Malohkan having a discussion as to how to get this to work, and he came up with a work-around. That thread is somewhere in this forum. I'm not sure if it will solve your problem, but it might be something worth looking into.
    -N.

  • JFrame or AWT Container Listener

    Hi,
    i have created a window with below components
    1) JComboBox
    2) Radio Button Group( it holds two buttons)
    3) Date picker
    and a JButton
    my button will be in disabled state and on change of properties of any of above components like
    on change of date
    changing the selected radio button
    changing the combo box selected item
    i need to set the button enabled.
    what the best way to do. i tried with action Listeners of both JFrame and Container. but could n't succeeded.
    please point me to right way to do the same
    Thanks in advance
    R

    Show us what you have tried and we'll see what's wrong. Post only relevant code, not your entire program.
    {color:#0000ff}http://mindprod.com/jgloss/sscce.html{color}
    db

  • Invisible JScrollPane?

    I have a JList matched up with a JTextArea. Inside the JList I want it to list numbers corresponding to the line in the JTextArea. I have the JList's and JTextArea's JScrollPanes synched up. But, I only want the JTextArea's JScrollPane to show up. Is it possible to have the JList's JScrollPane be invisible but because it is synched up with the JTextArea's JScrollPane still scroll through the JList? If you do not know what I mean or want more of my code, let me know.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    public class cfmCodeCounter1_1 extends JFrame
         private JLabel lblEnter;
         private JTextArea input, output;
         private JList row;
         private JButton parse, clear, exit;
         private JScrollPane scroller, scroller2, scroller3;
         private Container c;
         private Vector <String> rowVec;
         private boolean threadflag = false; // Used so only one thread for the CaretListener runs at one time
         private cfmCodeCounter1_1()
              try
                   this.setTitle("ColdFusion Parser - NGIT");
                   // Vector
                   rowVec = new Vector<String>();
                   // Display Label
                   lblEnter = new JLabel("Enter Code Below: ");
                   lblEnter.setVisible(true);
                   // JTextAreas
                   input = new JTextArea(10, 30); // (rows, columns)
                   input.setEditable(true);
                   scroller = new JScrollPane(input);
                   input.requestFocus();
                   output = new JTextArea(5, 19); // (rows, columns)
                   output.setEditable(false);
                   scroller2 = new JScrollPane(output);
                   output.requestFocus();
                   // Selectable List
                   row = new JList(rowVec);
                   row.setVisibleRowCount(10);
                   row.setFixedCellWidth(50);
                   row.setFixedCellHeight((input.getPreferredSize().height/10));
                   scroller3 = new JScrollPane(row);
                   // Set up scroller and scroller3
                   scroller.getVerticalScrollBar().setModel(scroller3.getVerticalScrollBar().getModel());
                   // Set up listener for input and row
                   TextHandler txthandle = new TextHandler();
                   input.addCaretListener(txthandle);
                   // Button
                   parse = new JButton("Parse Code");
                   clear = new JButton("Clear");
                   exit = new JButton("Exit");
                   // Set Layout
                   c = getContentPane();
                   SpringLayout layout = new SpringLayout();
                   c.setLayout(layout);
                   c.add(lblEnter);
                   c.add(scroller3);
                   c.add(scroller);
                   c.add(scroller2);
                   c.add(parse);
                   c.add(clear);
                   c.add(exit);
                   // Place lblEnter
                   layout.putConstraint(SpringLayout.WEST, lblEnter,
                                 10,
                                 SpringLayout.WEST, c);
                 layout.putConstraint(SpringLayout.NORTH, lblEnter,
                                 10,
                                 SpringLayout.NORTH, c);
                // Place scroller3 aka row
                   layout.putConstraint(SpringLayout.WEST, scroller3,
                                 10,
                                 SpringLayout.WEST, c);
                 layout.putConstraint(SpringLayout.NORTH, scroller3,
                                 5,
                                 SpringLayout.SOUTH, lblEnter);
                   // Place scroller aka input
                   layout.putConstraint(SpringLayout.WEST, scroller,
                                 -1,
                                 SpringLayout.EAST, scroller3);
                 layout.putConstraint(SpringLayout.NORTH, scroller,
                                 0,
                                 SpringLayout.NORTH, scroller3);
                    // Place scroller2 aka output
                   layout.putConstraint(SpringLayout.WEST, scroller2,
                                 5,
                                 SpringLayout.EAST, scroller);
                 layout.putConstraint(SpringLayout.NORTH, scroller2,
                                 0,
                                 SpringLayout.NORTH, scroller);
                // Place parse
                   layout.putConstraint(SpringLayout.WEST, parse,
                                 10,
                                 SpringLayout.WEST, c);
                 layout.putConstraint(SpringLayout.NORTH, parse,
                                 5,
                                 SpringLayout.SOUTH, scroller);
                // Place clear
                   layout.putConstraint(SpringLayout.WEST, clear,
                                 5,
                                 SpringLayout.EAST, parse);
                 layout.putConstraint(SpringLayout.NORTH, clear,
                                 0,
                                 SpringLayout.NORTH, parse);
                // Place exit
                   layout.putConstraint(SpringLayout.WEST, exit,
                                 5,
                                 SpringLayout.EAST, clear);
                 layout.putConstraint(SpringLayout.NORTH, exit,
                                 0,
                                 SpringLayout.NORTH, clear);
                   // Button Event Handler
                   ButtonHandler handler = new ButtonHandler();
                   parse.addActionListener(handler);
                   clear.addActionListener(handler);
                   exit.addActionListener(handler);
                   this.addWindowListener(new WindowAdapter()
                             public void windowClosing(WindowEvent e)
                                  System.exit(0);
                   setSize(650, 300);
                   setVisible(true);
              catch(Exception e)
                   e.printStackTrace();
                   JOptionPane.showMessageDialog(null, "General Error: See Command Line.", "ERROR - NGIT", JOptionPane.ERROR_MESSAGE);
                   System.exit(0);
         private class TextHandler implements Runnable, CaretListener
              public void caretUpdate(CaretEvent e)
                   if (!threadflag)
                        threadflag = true;
                        Thread txtThread = new Thread(this);
                        txtThread.start();
              public void run()
                   rowVec.removeAllElements();
                   for (int i = 1; i <= input.getLineCount(); i++)
                        rowVec.add("" + i);          
                   row.setListData(rowVec);
                   threadflag = false;
                   // Find current row of cursor
                   int numrows = 1;
                   char[] chararr = input.getText().toCharArray();
                   int caretPos = input.getCaretPosition();
                   for (int i = (caretPos-1); i >= 0; i--)
                        if (chararr[i] == '\n')
                             numrows++;
                   row.setSelectedIndex((numrows-1));
                   row.ensureIndexIsVisible((numrows-1));
    //Code Continues

    Thank you, you did catch an error that I had. I did not want output to have requestFocus(), as you can see just above it I actually wanted input to have it. Also, I put "input.requestFocus()" after I set the visible to true and it works. Thank you for that.
    But, I have two main questions. One is, can you do what I described above and have one jscrollpane be invisible, yet still work since it is synched up with another jscrollpane that is visible?
    The other question goes with this code below. I do not necessarily want it to scroll to the bottom of the page, just to where the cursor ends. Let's say I already have code in the input JTextArea, and I paste more code above it, I do not want it to scroll to the bottom of the JTextArea, just to where the cursor ends up. I cannot figure out why it is not autoscrolling.
    private class TextHandler implements Runnable, CaretListener
              public void caretUpdate(CaretEvent e)
                   if (!threadflag)
                        threadflag = true;
                        Thread txtThread = new Thread(this);
                        txtThread.start();
              public void run()
                   rowVec.removeAllElements();
                   for (int i = 1; i <= input.getLineCount(); i++)
                        rowVec.add("" + i);          
                   row.setListData(rowVec);
                   // Find current row of cursor
                   int numrows = 1;
                   char[] chararr = input.getText().toCharArray();
                   int caretPos = input.getCaretPosition();
                   for (int i = (caretPos-1); i >= 0; i--)
                        if (chararr[i] == '\n')
                             numrows++;
                   row.setSelectedIndex(numrows-1);
                   row.ensureIndexIsVisible(numrows-1);
                   System.out.println("ACTUAL: " + row.getSelectedIndex());
                   threadflag = false;
         }

  • Jtable cell listening to mouse event source

    Hi, I have a JTable with single cell selections enabled.
    I can also get the mouseClicked event working, but the cure is worse than the illness, because every cell I click on will cause a jframe to pop-up.
    Ideally only column 0 or 1 listens to the mouseClicked event.
    Can someone please tell mehow to work that into the JTable cell (sorry for the tediously long code, its only a small part)
    import javax.swing.JComponent;
    ...lots of import...
    public class CCYTable extends JPanel
      JTable newtable;
      JLabel tableHeader;
      public CCYFrame NewFrame;
      private boolean DEBUG = false;
      private int showInfoTimer = 10000; // info tip box will pop up for this period of time...
      // if both column and row selection are enabled, then individual cell selection
      // is also enabled.
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
      String LoC = "Letter of Credit";
       ...more variable...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("uy or Sell", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
              ... ideally I would like to work the mouseClicked listener in here but... 
            return info;
          } // end of JComponent's method getToolTipText
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        if (clickForDetail)
          newtable.addMouseListener(new MouseAdapter()
            public void mouseClicked(MouseEvent mevt)
              { // ...but JTable wants it like this...
                // launch a new pop-up to replace the tool tip box
                NewFrame = new CCYFrame("blabla");
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
       * For sizing columns. If all column heads are wider than the column-cells'
       * contents, then just use column.sizeWidthToFit().
      private void initColumnSizes(JTable newtable)
        TableDefinition tblmodel = (TableDefinition)newtable.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth=0, cellWidth=0;
        Object[] longValues = tblmodel.longValues;
        TableCellRenderer headerRenderer = newtable.getTableHeader().getDefaultRenderer();
        TableCellRenderer rightRenderer = new RightRenderer();
        for (int i = 0; i < 7; i++)
          column = newtable.getColumnModel().getColumn(i);
          comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
          headerWidth = comp.getPreferredSize().width;
          comp = newtable.getDefaultRenderer(tblmodel.getColumnClass(i)).
                          getTableCellRendererComponent(
                                 newtable, longValues,
    true, true, 0, i);
    cellWidth = comp.getPreferredSize().width;
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    TableColumn col2 = newtable.getColumnModel().getColumn(2);
    col2.setCellRenderer( rightRenderer );
    TableColumn col2Width = newtable.getColumnModel().getColumn(2);
    col2Width.setPreferredWidth(2);
    TableColumn col6 = newtable.getColumnModel().getColumn(6);
    col6.setCellRenderer( rightRenderer );
    TableColumn col6Width = newtable.getColumnModel().getColumn(6);
    col6Width.setPreferredWidth(2);
    }// end of method initColumnSizes
    private void enableCellSelection(JTable newtable)
    if (ALLOW_COLUMN_SELECTION)
    if (ALLOW_ROW_SELECTION) {newtable.setCellSelectionEnabled(true);}
    newtable.setColumnSelectionAllowed(true);
    ListSelectionModel colSM = newtable.getColumnModel().getSelectionModel();
    colSM.addListSelectionListener(new ListSelectionListener()
    public void valueChanged(ListSelectionEvent lsevt)
    if (lsevt.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)lsevt.getSource();
    if (lsm.isSelectionEmpty()) {}
    else
    //int selectedCol = lsm.getMinSelectionIndex();
    //NewFrame = new CCYFrame("more blabla!");
    }//end of method enableCellSelection
    ...a lot of code follows...
    TIA :-)

    Hi, thanks for the tip, but I get following compile-time error:
    <identifier> expected
    newtable.addMouseListener(new MouseAdapter()
    .............................................^
    package newtable does not exist
    newtable.addMouseListener(new MouseAdapter()
    ...............^
    2 errors
    And here is how I've modified the code :
    public class CCYTable extends JPanel
      JTable newtable;
      ...lots of variables...
      private boolean ALLOW_COLUMN_SELECTION = true;
      private boolean ALLOW_ROW_SELECTION = true;
      private boolean clickForDetail = true; // click on cell to launch frame with detail
      protected String[] colHeaderInfo =
        {"Name of Instrument, move mouse to instrument for general detail of service.",
          ...lots of text for tooltipbox...
      // get values from database, use an "invisible column" for unique key
      // description, conditions etc from Oracle...
       ...lots more String variables...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
            return info;
          } // end of JComponent's method getToolTipText
          newtable.addMouseListener(new MouseAdapter()  //  HELP: compiler throws error here !!!!!!!!
            public void mouseClicked(MouseEvent e)
              java.awt.Point p = mevt.getPoint();
              int rowIndex = rowAtPoint(p);
              int colIndex = columnAtPoint(p);
              int realColIndex = convertColumnIndexToModel(colIndex);
              Object currentValue = getValueAt(rowIndex, colIndex);
              if ((rowIndex == 0) and (colIndex == 0))
                // do stuff for this particular JTable cell ...
          //Put table header info
          protected JTableHeader createDefaultTableHeader()
            return new JTableHeader(columnModel)
              public String getToolTipText(MouseEvent mevt)
                String tip = null;
                java.awt.Point p = mevt.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = columnModel.getColumn(index).getModelIndex();
                return colHeaderInfo[realIndex];
        ToolTipManager.sharedInstance().setDismissDelay(showInfoTimer);
        newtable.setPreferredScrollableViewportSize(new Dimension(770, 350));
        JScrollPane scrollpane = new JScrollPane(newtable);
        initColumnSizes(newtable);
        enableCellSelection(newtable);
        add("North", tableHeader);
        add("Center", scrollpane);
      }On the other hand, this code works after a fashion but it is not what is needed because it listens to every JTable cell :
    public class CCYTable extends JPanel
      JTable newtable;
      ...unbelievably more variable definitions, etc...
      public void init()
        //setSize(300,300);
        tableHeader = new JLabel("Bids and Offers", JLabel.CENTER);
        setLayout(new BorderLayout());
        newtable = new JTable(new TableDefinition())
          //Put cell info here, from Oracle CellInfo varchar2
          public String getToolTipText (MouseEvent mevt)
            String info = null;
            java.awt.Point p = mevt.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColIndex = convertColumnIndexToModel(colIndex);
            Object currentValue = getValueAt(rowIndex, colIndex);
            if (realColIndex == 0)
            { if (currentValue.equals(LoC))
              { info = "Click to read general description of our \"" + LoC + "\" service." ;
                if (rowIndex == 0)  // HELP:  compiles okay but won't specifically select rowIndex == 0 and colIndex == 0
                {this.addMouseListener(new clickListener(newtable, rowIndex, colIndex));
            return info;
          } // end of JComponent's method getToolTipText
         ... lots more code...
      // ==============================
      class clickListener extends MouseAdapter
        private JTable newtable;
        private int rowIndex;
        private int colIndex;
        public clickListener(JTable newtable, int rowIndex, int colIndex)
          this.newtable = newtable;
          this.rowIndex = rowIndex;
          this.colIndex = colIndex;
        public void mouseClicked(MouseEvent mevt)
          NewFrame = new CCYFrame("blablabla");
      }// end of method clickListenerIdeally I should be able to use a selection criteria like this :
    java.awt.Point p = mevt.getPoint();
    rowIndex = rowAtPoint(p);
    colIndex=colAtPoint(p);
    if ((rowIndex == 0) && (colIndex == 0)) {//do something}but this is going to be a bad Chrissy for me?

  • GlassPane functionality in AWT

    Hi all,
    I have a program I am trying to write that uses a Panel from an applet. The panel has a mouseListener that I want to block, so I figured I would use the JFrame's GlassPane to intercept the mouse events, which works fine if the underlying panel is a JPanel, but not if it is an awt.Panel, which is what I need (probably a difference between heavyweight vs. lightweight components).
    So how can I go about intercepting the mouse events for an AWT Panel if it will always be on top of any of my Swing components? Are there any AWT components that I can make invisible and place on top of the Panel?
    Thanks for any help...
    (oh, I was thinking of removing or qualifying the mouse events inside the Panel's mouse listener, but the Panel needs to be serialized and then re-displayed in the Applet for which it was originally designed, so I would rather not do that...)

    Anybody any help with this?
    I have been experimenting with Window, but it doesn't take any of the Events either:
         JFrame frame = new JFrame("Glass Pane Test");
         JLabel jl = new JLabel ("Swing");
         JPanel jp = new JPanel();
         jp.add(jl);
         jp.addMouseListener(new MouseAdapter() {
           public void mouseClicked(MouseEvent e) {
              System.out.println("SWING: Not the Glass Pane Event");
         Label l2 = new Label("AWT");
         Panel p = new Panel();
         p.add(l2);
         p.addMouseListener(new MouseAdapter() {
           public void mouseClicked(MouseEvent e) {
              System.out.println("AWT: Not the Glass Pane Event");
         frame.getGlassPane().addMouseListener(new MouseAdapter() {
           public void mouseClicked(MouseEvent e){
              System.out.println("SWING: I AM The Glass Pane Event");
         JWindow w = new JWindow ();
         w.addMouseListener(new MouseAdapter() {
           public void mouseClicked(MouseEvent e){
              System.out.println("AWT: I AM The Glass Pane Event");
         w.setBounds(frame.getBounds());
    /*1*/     frame.getContentPane().add(jp);
         frame.pack();
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.setVisible(true);
    /*2*/     //frame.getGlassPane().setVisible(true);
    /*3*/     w.show();
    /*3*/     w.toFront();
         System.out.println(w.isVisible());If I comment out /*3*/ and uncomment /*2*/ Then we can see the behaviour of Panel with the glass pane (by switching /*1*/ between add(jp) and add(p). Then we reinstate /*3*/ and comment out /*2*/ and all the comments go to the Panel/JPanel, none go to the Window... Id there a way to make the Window get all the Mouseevents?

  • Can I build a GUI application with SWING only without [import java.awt.*;]

    I have seen several threads (in forums), books and tutorials about SWING and I see that they all mix SWING with AWT (I mean they import both Swing and AWT in their code).
    The conclusion that comes out is:
    It is good to learn about SWING and forget AWT as it won't be supported later. I have decided to do so, and I never include <<import java.awt.*;>> in my code.
    But I see that you cannot do much without <<import java.awt.*;>>. For example this line which changes the background color:
    <<frame.getContentPane().setBackground(Color.red)>>
    works only with <<import java.awt.*;>>. I have seen that codes in this and other forums import awt to change the background. Why is that?
    After all, I wonder, what can I do;
    My question is, can I change the background (and of course do all other things listener, buttons etc) without using <<import java.awt.*;>>.
    I would like to avoid using <<import java.awt.*;>> and using awt since my program will not work later.
    In addition, I believe there is no point to learn awt, which later will not exist.
    I know, I must have misunderstood something. I would appreceate it very much, if anyone could give me even a short answer.
    Thank you in advance,
    JMelsi

    Since swing is a layer on top of awt, AWT will exist for as long as swing does.
    If sun does ever remove AWT they will have to replace it something else swing can layer on to and you will probably only have to replace your import statements.
    The main difference is the way there drawn to the screen.
    You can do custom drawing on swing components but you can't on AWT.
    If your using a desktop PC system it's probably best to use swing just in case you wish to do some custom drawing.
    awt uses less memory than swing and is faster but swing can be extended. awt comes only as standard.
    Say for example you wish to implement a JButton with a ProgressBar below the button text, this can be done with swing!

  • Item listener & combo boxes......please help me....thanks

    I did a applet that shows 4 jcombobox......the combo 2 is filling if the combo 1 is actioned, the combo3 is filling if the combo2 is actioned and the combo 4 have to be filled if the combo 3 is actioned.
    I did it...using item listener......it works fine....the first time....(in the console appears the lines that i specify using System.out.println).....but after...when i select any combo....i see in the console...that the itemlistener action is done several times......i don�t know why......do you have any idea or suggestion about it?............
    Thanks in advance...
    Mary
    This is the code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.lang.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    public class w3_a extends JApplet {
    Container contentPane;
    int i=10, j=20, k=30, l=40;
    private JComboBox jcb1;
    private JComboBox jcb2;
    private JComboBox jcb3;
    private JComboBox jcb4;
    private JTabbedPane jtp;
    private GriddedPanel jp1;
    private GriddedPanel jp2;
    public void init() {
    contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    add_JComboBoxes_GUI();
    add_JTabbedPanes_GUI();
    fill_combo1();
    void add_JComboBoxes_GUI() {
    jp1 = new GriddedPanel();
    jp1.setBorder( new EmptyBorder(new Insets(5, 5, 5, 5)) );
    jcb1 = new JComboBox();
    jcb2 = new JComboBox();
    jp1.add(jcb1);
    jp1.add(jcb2);
    contentPane.add(jp1, BorderLayout.NORTH);
    jcb1.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(ItemEvent e) {
    System.out.println("Accion 1 - Element");
    fill_combo2();
    jcb2.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(ItemEvent e) {
    System.out.println("Accion 2 - Element");
    fill_combo3();
    void add_JTabbedPanes_GUI() {
    jtp = new JTabbedPane();
    jtp.addTab("Datos Generales", new Panel_Data());
    contentPane.add(jtp);
    class Panel_Data extends JPanel {
    public Panel_Data() {
    // Primer panel de JTabbedPane de Datos Generales
    jp2 = new GriddedPanel();
    jp2.setBorder( new EmptyBorder(new Insets(5, 5, 5, 5)) );
    jcb3 = new JComboBox();
    jcb4 = new JComboBox();
    jp2.add(jcb3);
    jp2.add(jcb4);
    jtp.add(jp2);
    contentPane.add(jtp, BorderLayout.SOUTH);
    jcb3.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(ItemEvent e) {
    System.out.println("Accion 3 - Element");
    fill_combo4();
    jcb4.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(ItemEvent e) {
    System.out.println("Accion 4 - Element");
    void fill_combo1() {
    System.out.println("Start fill_combo1()");
    jcb1.removeAllItems();
    jcb1.addItem("combo1 " + (++i));
    jcb1.addItem("combo1 " + (++i));
    jcb1.addItem("combo1 " + (++i));
    System.out.println("End fill_combo1()");
    return;
    void fill_combo2() {
    System.out.println("Start fill_combo2()");
    jcb2.removeAllItems();
    jcb2.addItem("combo2 " + (++j));
    jcb2.addItem("combo2 " + (++j));
    jcb2.addItem("combo2 " + (++j));
    System.out.println("End fill_combo2()");
    return;
    void fill_combo3() {
    System.out.println("Start fill_combo3()");
    jcb3.removeAllItems();
    jcb3.addItem("combo3 " + (++k));
    jcb3.addItem("combo3 " + (++k));
    jcb3.addItem("combo3 " + (++k));
    System.out.println("End fill_combo3()");
    return;
    void fill_combo4() {
    System.out.println("Start fill_combo4()");
    jcb4.removeAllItems();
    jcb4.addItem("combo4 " + (++l));
    jcb4.addItem("combo4 " + (++l));
    jcb4.addItem("combo4 " + (++l));
    System.out.println("End fill_combo4()");
    return;

    Hi!!!
    Thanks by answer to me.....
    Yes ...i already understand why is happening in it.....
    I did modifications to my code to remove the listeners and after to add them....but no yet obtain my goal that the combo 2 is filling if the combo 1 is actioned, the combo3 is filling if the combo2 is actioned and the combo 4 have to be filled if the combo 3 is actioned.
    I think that at least should it to work for combo1 and combo2, because i don't know how to specify to add or remove the listener from the class de Panel_Data would be .....because i think that with:
    jcb3.removeItemListener(this);
    jcb3.addItemListener(this);
    jcb4.removeItemListener(this);
    jcb4.addItemListener(this);
    i am removing and adding the itemlistener from the main class w10_a (for combo3 and combo4)...... and not for the Panel_Data class.
    ie,
    jcb4.removeItemListener(
    //here is my doubt i don't know how to specify
    //to add or to remove the itemlistener from the
    //Panel_Data class for combo3 and combo4
    jcb4.addItemListener(
    //here is my doubt i don't know how to specify
    //to add or to remove the itemlistener from the
    //Panel_Data class for combo3 and combo4
    Well...i hope that you could help me please in give me some suggestions about it...
    Thanks in advance...
    Mary
    Here is my code modified:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import java.lang.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    public class w10_a extends JApplet implements ItemListener{
    Container contentPane;
    int i=10, j=20, k=30, l=40;
    private JComboBox jcb1;
    private JComboBox jcb2;
    private JComboBox jcb3;
    private JComboBox jcb4;
    private JTabbedPane jtp;
    private GriddedPanel jp1;
    private GriddedPanel jp2;
    public void init() {
    contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    add_JComboBoxes_GUI();
    add_JTabbedPanes_GUI();
    fill_combo1();
    void add_JComboBoxes_GUI() {
    jp1 = new GriddedPanel();
    jp1.setBorder( new EmptyBorder(new Insets(5, 5, 5, 5)) );
    jcb1 = new JComboBox();
    jcb2 = new JComboBox();
    jp1.add(jcb1);
    jp1.add(jcb2);
    contentPane.add(jp1, BorderLayout.NORTH);
    jcb1.addItemListener(this);
    jcb2.addItemListener(this);
    void add_JTabbedPanes_GUI() {
    jtp = new JTabbedPane();
    jtp.addTab("Datos Generales", new Panel_Data());
    contentPane.add(jtp);
    class Panel_Data extends JPanel implements ItemListener {
    public Panel_Data() {
    // Primer panel de JTabbedPane de Datos Generales
    jp2 = new GriddedPanel();
    jp2.setBorder( new EmptyBorder(new Insets(5, 5, 5, 5)) );
    jcb3 = new JComboBox();
    jcb4 = new JComboBox();
    jp2.add(jcb3);
    jp2.add(jcb4);
    jtp.add(jp2);
    contentPane.add(jtp, BorderLayout.SOUTH);
    //Implementamos ActionListener para cada acci�n ejecutada
    jcb3.addItemListener(this);
    jcb4.addItemListener(this);
    public void itemStateChanged(ItemEvent e) {
    if ( e.getItemSelectable() == jcb3 ) {
    System.out.println("Accion 3 - Element");
    fill_combo4();
    if ( e.getItemSelectable() == jcb4 ) {
    System.out.println("Accion 4 - Element");
    public void itemStateChanged(ItemEvent e) {
    if ( e.getItemSelectable() == jcb1 ) {
    System.out.println("Accion 1 - Element");
    fill_combo2();
    if ( e.getItemSelectable() == jcb2 ) {
    System.out.println("Accion 2 - Element");
    fill_combo3();
    void fill_combo1() {
    System.out.println("Start fill_combo1()");
    jcb1.removeItemListener(this);
    jcb1.removeAllItems();
    jcb1.addItem("combo1 " + (++i));
    jcb1.addItem("combo1 " + (++i));
    jcb1.addItemListener(this);
    jcb1.addItem("combo1 " + (++i));
    System.out.println("End fill_combo1()");
    void fill_combo2() {
    System.out.println("Start fill_combo2()");
    jcb2.removeItemListener(this);
    jcb2.removeAllItems();
    jcb2.addItem("combo2 " + (++j));
    jcb2.addItem("combo2 " + (++j));
    jcb2.addItemListener(this);
    jcb2.addItem("combo2 " + (++j));
    System.out.println("End fill_combo2()");
    void fill_combo3() {
    System.out.println("Start fill_combo3()");
    jcb3.removeItemListener(this);
    jcb3.removeAllItems();
    jcb3.addItem("combo3 " + (++k));
    jcb3.addItem("combo3 " + (++k));
    jcb3.addItemListener(this);
    jcb3.addItem("combo3 " + (++k));
    System.out.println("End fill_combo3()");
    void fill_combo4() {
    System.out.println("Start fill_combo4()");
    jcb4.removeItemListener(this);
    jcb4.removeAllItems();
    jcb4.addItem("combo4 " + (++l));
    jcb4.addItem("combo4 " + (++l));
    jcb4.addItemListener(this);
    jcb4.addItem("combo4 " + (++l));
    System.out.println("End fill_combo4()");

  • Custom graphics in java.awt.ScrollPane

    Hi all,
    I have to draw a custom created image in a scroll pane. As the image is very large I want to display it in a scroll pane. As parts of the image may change within seconds, and drawing the whole image is very time consuming (several seconds) I want to draw only the part of the image that is currently visible to the user.
    My idea: creating a new class that extends from java.awt.ScrollPane, overwrite the paint(Graphics) method and do the drawings inside. Unfortunately, it does not work. The background of the scoll pane is blue, but it does not show the red box (the current viewport is not shown in red).
    Below please find the source code that I am using:
    package graphics;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.ScrollPane;
    import java.awt.event.AdjustmentEvent;
    public class CMyComponent extends ScrollPane {
         /** <p>Listener to force a component to repaint when a scroll bar changes its
          * position.</p>
         private final class ScrollBarAdjustmentListener implements java.awt.event.AdjustmentListener {
              /** <p>The component to force to repaint.</p> */
              private final Component m_Target;
              /** <p>Default constructor.</p>
               * @param Target The component to force to repaint.
              private ScrollBarAdjustmentListener(Component Target) { m_Target = Target; }
              /** <p>Forces to component to repaint upon adjustment of the scroll bar.</p>
               *  @see java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event.AdjustmentEvent)
              public void adjustmentValueChanged(AdjustmentEvent e) { m_Target.paint(m_Target.getGraphics()); }
         public CMyComponent() {
              // Ensure that the component repaints upon changing of the scroll bars
              ScrollBarAdjustmentListener sbal = new ScrollBarAdjustmentListener(this);
              getHAdjustable().addAdjustmentListener(sbal);
              getVAdjustable().addAdjustmentListener(sbal);
         public void paint(Graphics g) {
              setBackground(Color.BLUE);
              g.setColor(Color.RED);
              g.fillRect(getScrollPosition().x, getScrollPosition().y, getViewportSize().width, getViewportSize().height);
         public final static void main(String[] args) {
              java.awt.Frame f = new java.awt.Frame();
              f.add(new CMyComponent());
              f.pack();
              f.setVisible(true);
    }

    Dear all,
    I used the last days and tried several things. I think now I have a quite good working solution (just one bug remains) and it is very performant. To give others a chance to see what I have done I post the source code of the main class (a canvas drawing and implementing scrolling) here. As soon as the sourceforge project is accepted, I will publish the whole sources at there. Enjoy. And if you have some idea for my last bug in getElementAtPixel(Point), then please tell me.
    package internetrail.graphics.hexgrid;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Area;
    import java.awt.image.BufferedImage;
    import java.util.WeakHashMap;
    import java.util.Map;
    /** <p>Hex grid view.</p>
    * <p>Visualizes a {@link IHexGridModel}.</p>
    * @version 0.1, 03.06.2006
    * @author Bjoern Wuest, Germany
    public final class CHexGridView extends Canvas implements ComponentListener, IHexGridElementListener {
         /** <p>Serial version unique identifier.</p> */
         private static final long serialVersionUID = -965902826101261530L;
         /** <p>Instance-constant parameter for the width of a hex grid element.</p> */
         public final int CONST_Width;
         /** <p>Instance-constant parameter for 1/4 of the width of a hex grid element.</p> */
         public final int CONST_Width1fourth;
         /** <p>Instance-constant parameter for 3/4 of the width of a hex grid element.</p> */
         public final int CONST_Width3fourth;
         /** <p>Instance-constant parameter for 1.5 times of the width of a hex grid element.</p> */
         public final int CONST_Width1dot5;
         /** <p>Instance-constant parameter for 4 times of the width of a hex grid element.</p> */
         public final int CONST_Widthquad;
         /** <p>Instance-constant parameter for the height of a hex grid element.</p> */
         public final int CONST_Height;
         /** <p>Instance-constant parameter for 1/2 of the height of a hex grid element.</p> */
         public final int CONST_Heighthalf;
         /** <p>Instance-constant parameter for the double height of a hex grid element.</p> */
         public final int CONST_Heightdouble;
         /** <p>The steepness of a side of the hex grid element (calculated for the upper left arc).</p> */
         public final double CONST_Steepness;
         /** <p>The model of this hex grid </p> */
         private final IHexGridModel m_Model;
         /** <p>A cache for already created images of the hex map.</p> */
         private final Map<Point, Image> m_Cache = new WeakHashMap<Point, Image>();
         /** <p>The graphical area to draw the selection ring around a hex element.</p> */
         private final Area m_SelectionRing;
         /** <p>The image of the selection ring around a hex element.</p> */
         private final BufferedImage m_SelectionRingImage;
         /** <p>The current position of the hex grid in pixels (top left visible corner).</p> */
         private Point m_ScrollPosition = new Point(0, 0);
         /** <p>Flag to define if a grid is shown ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowGrid = true;
         /** <p>Flag to define if the selected hex grid element should be highlighted ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowSelected = true;
         /** <p>The offset of hex grid elements shown on the screen, measured in hex grid elements.</p> */
         private Point m_CurrentOffset = new Point(0, 0);
         /** <p>The offset of the image shown on the screen, measured in pixels.</p> */
         private Point m_PixelOffset = new Point(0, 0);
         /** <p>The index of the currently selected hex grid element.</p> */
         private Point m_CurrentSelected = new Point(0, 0);
         /** <p>The width of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageWidth;
         /** <p>The height of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageHeight;
         /** <p>The maximum number of columns of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxColumn;
         /** <p>The maximum number of rows of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxRow;
         /** <p>Create a new hex grid view.</p>
          * <p>The hex grid view is bound to a {@link IHexGridModel} and registers at
          * that model to listen for {@link IHexGridElement} updates.</p>
          * @param Model The model backing this view.
         public CHexGridView(IHexGridModel Model) {
              // Set the model
              m_Model = Model;
              CONST_Width = m_Model.getElementsWidth();
              CONST_Height = m_Model.getElementsHeight();
              CONST_Width1fourth = CONST_Width/4;
              CONST_Width3fourth = CONST_Width*3/4;
              CONST_Width1dot5 = CONST_Width*3/2;
              CONST_Heighthalf = CONST_Height/2;
              CONST_Widthquad = CONST_Width*4;
              CONST_Heightdouble = CONST_Height*2;
              CONST_Steepness = (double)CONST_Heighthalf / CONST_Width1fourth;
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // Register this canvas for various notifications
              m_Model.addElementListener(this);
              addComponentListener(this);
              // Create the selection ring to highlight hex grid elements
              m_SelectionRing = new Area(new Polygon(new int[]{-1, CONST_Width1fourth-1, CONST_Width3fourth+1, CONST_Width+1, CONST_Width3fourth+1, CONST_Width1fourth-1}, new int[]{CONST_Heighthalf, -1, -1, CONST_Heighthalf, CONST_Height+1, CONST_Height+1}, 6));
              m_SelectionRing.subtract(new Area(new Polygon(new int[]{2, CONST_Width1fourth+2, CONST_Width3fourth-2, CONST_Width-2, CONST_Width3fourth-2, CONST_Width1fourth+2}, new int[]{CONST_Heighthalf, 2, 2, CONST_Heighthalf, CONST_Height-2, CONST_Height-2}, 6)));
              m_SelectionRingImage = new BufferedImage(CONST_Width, CONST_Height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g = m_SelectionRingImage.createGraphics();
              g.setColor(Color.WHITE);
              g.fill(m_SelectionRing);
         @Override public synchronized void paint(Graphics g2) {
              // Caculate the offset of indexes to show
              int offsetX = 2 * (m_ScrollPosition.x / CONST_Width1dot5) - 2;
              int offsetY = (int)(Math.ceil(m_ScrollPosition.y / CONST_Height) - 1);
              m_CurrentOffset = new Point(offsetX, offsetY);
              // Check if the image is in the cache
              Image drawing = m_Cache.get(m_CurrentOffset);
              if (drawing == null) {
                   // The image is not cached, so draw it
                   drawing = new BufferedImage(m_ImageWidth, m_ImageHeight, BufferedImage.TYPE_INT_ARGB);
                   Graphics2D g = ((BufferedImage)drawing).createGraphics();
                   // Draw background
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, m_ImageWidth, m_ImageHeight);
                   // Draw the hex grid
                   for (int column = 0; column <= m_MaxColumn; column += 2) {
                        for (int row = 0; row <= m_MaxRow; row++) {
                             // Draw even column
                             IHexGridElement element = m_Model.getElementAt(offsetX + column, offsetY + row);
                             if (element != null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)), CONST_Height*row, null); }
                             // Draw odd column
                             element = m_Model.getElementAt(offsetX + column+1, offsetY + row);
                             if (element!= null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)+CONST_Width3fourth), CONST_Heighthalf*(row*2+1), null); }
                   // Put the image into the cache
                   m_Cache.put(m_CurrentOffset, drawing);
              // Calculate the position of the image to show
              offsetX = CONST_Width1dot5 + (m_ScrollPosition.x % CONST_Width1dot5);
              offsetY = CONST_Height + (m_ScrollPosition.y % CONST_Height);
              m_PixelOffset = new Point(offsetX, offsetY);
              g2.drawImage(drawing, -offsetX, -offsetY, null);
              // If the selected element should he highlighted, then do so
              if (m_ShowSelected) {
                   // Check if the selected element is on screen
                   if (isElementOnScreen(m_CurrentSelected)) {
                        // Correct vertical offset for odd columns
                        if ((m_CurrentSelected.x % 2 == 1)) { offsetY -= CONST_Heighthalf; }
                        // Draw the selection circle
                        g2.drawImage(m_SelectionRingImage, (m_CurrentSelected.x - m_CurrentOffset.x) * CONST_Width3fourth - offsetX - ((m_CurrentSelected.x + 1) / 2), (m_CurrentSelected.y - m_CurrentOffset.y) * CONST_Height - offsetY, null);
         @Override public synchronized void update(Graphics g) { paint(g); }
         public synchronized void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // And flush the cache
              m_Cache.clear();
         public void componentMoved(ComponentEvent e) { /* do nothing */ }
         public void componentShown(ComponentEvent e) { /* do nothing */ }
         public void componentHidden(ComponentEvent e) { /* do nothing */ }
         public synchronized void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } }
              // Update the currently shown image if the update element is shown, too
              if (isElementOnScreen(Element.getIndex())) { repaint(); }
         /** <p>Returns the model visualized by this grid view.</p>
          * @return The model visualized by this grid view.
         public IHexGridModel getModel() { return m_Model; }
         /** <p>Returns the current selected hex grid element.</p>
          * @return The current selected hex grid element.
         public IHexGridElement getSelected() { return m_Model.getElementAt(m_CurrentSelected.x, m_CurrentSelected.y); }
         /** <p>Sets the current selected hex grid element by its index.</p>
          * <p>If the selected hex grid element should be highlighted and is currently
          * shown on the screen, then this method will {@link #repaint() redraw} this
          * component automatically.</p>
          * @param Index The index of the hex grid element to become the selected one.
          * @throws IllegalArgumentException If the index refers to a non-existing hex
          * grid element.
         public synchronized void setSelected(Point Index) throws IllegalArgumentException {
              // Check that the index is valid
              if ((Index.x < 0) || (Index.y < 0) || (Index.x > m_Model.getXElements()) || (Index.y > m_Model.getYElements())) { throw new IllegalArgumentException("There is no hex grid element with such index."); }
              m_CurrentSelected = Index;
              // If the element is on screen and should be highlighted, then repaint
              if (m_ShowSelected && isElementOnScreen(m_CurrentSelected)) { repaint(); }
         /** <p>Moves the visible elements to the left by the number of pixels.</p>
          * <p>To move the visible elements to the left by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the left.
          * @return The number of pixels moved to the left. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveLeft(int Pixels) {
              int delta = m_ScrollPosition.x - Math.max(0, m_ScrollPosition.x - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.x -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements up by the number of pixels.</p>
          * <p>To move the visible elements up by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move up.
          * @return The number of pixels moved up. This is always between 0 and {@code
          * abs(Pixels)}.
         public synchronized int moveUp(int Pixels) {
              int delta = m_ScrollPosition.y - Math.max(0, m_ScrollPosition.y - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.y -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements to the right by the number of pixels.</p>
          * <p>To move the visible elements to the right by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the right.
          * @return The number of pixels moved to the right. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveRight(int Pixels) {
              int delta = Math.min(m_Model.getXElements() * CONST_Width3fourth + CONST_Width1fourth - getSize().width, m_ScrollPosition.x + Math.max(0, Pixels)) - m_ScrollPosition.x;
              if (delta != 0) {
                   m_ScrollPosition.x += delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements down by the number of pixels.</p>
          * <p>To move the visible elements down by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move down.
          * @return The number of pixels moved down. This is always between 0 and
          * {@code abs(Pixels)}.
         public synchronized int moveDown(int Pixels) {
              int delta = Math.min(m_Model.getYElements() * CONST_Height + CONST_Heighthalf - getSize().height, m_ScrollPosition.y + Math.max(0, Pixels)) - m_ScrollPosition.y;
              if (delta != 0) {
                   m_ScrollPosition.y += delta;
                   repaint();
              return delta;
         /** <p>Checks if the hex grid element of the given index is currently
          * displayed on the screen (even just one pixel).</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @return {@code true} if the hex grid element of the given index is
          * displayed on the screen, {@code false} if not.
         public synchronized boolean isElementOnScreen(Point ElementIndex) { return isElementInScope(ElementIndex, m_CurrentOffset, new Point(m_CurrentOffset.x + m_MaxColumn, m_CurrentOffset.y + m_MaxRow)); }
         /** <p>Checks if the hex grid element of the given index is within the given
          * indexes.</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @param ReferenceIndexLeftTop The left top index of the area to check.
          * @param ReferenceIndexRightBottom The right bottom index of the area to check.
          * @return {@code true} if the hex grid element of the given index is within
          * the given area, {@code false} if not.
         public synchronized boolean isElementInScope(Point ElementIndex, Point ReferenceIndexLeftTop, Point ReferenceIndexRightBottom) { if ((ElementIndex.x >= ReferenceIndexLeftTop.x) && (ElementIndex.x <= ReferenceIndexRightBottom.x) && (ElementIndex.y >= ReferenceIndexLeftTop.y) && (ElementIndex.y <= (ReferenceIndexRightBottom.y))) { return true; } else { return false; } }
         /** <p>Return the {@link IHexGridElement hex grid element} shown at the given
          * pixel on the screen.</p>
          * <p><b>Remark: There seems to be a bug in retrieving the proper element,
          * propably caused by rounding errors and unprecise pixel calculations.</p>
          * @param P The pixel on the screen.
          * @return The {@link IHexGridElement hex grid element} shown at the pixel.
         public synchronized IHexGridElement getElementAtPixel(Point P) {
              // @FIXME Here seems to be some bugs remaining
              int dummy = 0; // Variable for warning to indicate that there is something to do :)
              // Calculate the pixel on the image, not on the screen
              int px = P.x + m_PixelOffset.x;
              int py = P.y + m_PixelOffset.y;
              // Determine the x-index of the column (is maybe decreased by one)
              int x = px / CONST_Width3fourth + m_CurrentOffset.x;
              // If the column is odd, then shift the y-pixel by half element height
              if ((x % 2) == 1) { py -= CONST_Heighthalf; }
              // Determine the y-index of the row (is maybe decreased by one)
              int y = py / CONST_Height + m_CurrentOffset.y;
              // Normative coordinates to a single element
              px -= (x - m_CurrentOffset.x) * CONST_Width3fourth;
              py -= (y - m_CurrentOffset.y) * CONST_Height;
              // Check if the normative pixel is in the first quarter of a column
              if (px < CONST_Width1fourth) {
                   // Adjustments to the index may be necessary
                   if (py < CONST_Heighthalf) {
                        // We are in the upper half of a hex-element
                        double ty = CONST_Heighthalf - CONST_Steepness * px;
                        if (py < ty) { x--; }
                   } else {
                        // We are in the lower half of a hex-element
                        double ty = CONST_Heighthalf + CONST_Steepness * px;
                        if (py > ty) {
                             x--;
                             y++;
              return m_Model.getElementAt(x, y);
    }Ah, just to give you some idea: I use this component to visualize a hex grid map with more than 1 million grid elements. And it works, really fast, and requires less than 10 MByte of memory.

Maybe you are looking for

  • ITunes 9.2 Hanging on "Restoring iPhone Frimware.."

    Sorry if this has been posted before Whenever I run iTunes and try to update any of my devices (iPad, iPhone 3GS & 4 or iPod Touch) the pop up window gets as far as "Restoring iPhone Firmware.." The progress bar get to about 4mm away from being full

  • Ipod touch wont connect to wifi unless close to router

    My ipod won't connect to my wifi unless I'm about 5-10 feet away from the router. Is this normal with the 1st gen ipod touches? I can't use a lot of apps because I need an internet connection to use them.

  • AFP Shares are not accessable after updating to 10.8.2

    Hi, I have just upgraded a server to run 10.8.2 as well as the latest version of the Server App. I can now not connect to the server from the various mac clients in the office using AFP. I can however connect from the Windows 7 clients that are using

  • Date Picker & File Upload components

    Hi all, I would like to have a Date Picker in a column in the table view (htmlb for java). Kindly let me know how I can do it. Similiarly can I make use of File Upload (htmlb for java )component inside the table view. I want to have a column which wo

  • Export integration interface error

    I am getting error "'Program internal error:null" when trying to run export integration interface in Demantra where i have specified view as well as filename(comma delimiter). Does anyone know what could be possible reason? It works when i remove fil