Making clickable hex grids

I try to implement MouseListener by using
public class HexBoard extends Frame implements MouseListenerbut the error message says I need to define the class as a abstract class. After trying that, i still get a error message in main says my class constructor is wrong. can anyone here help me please
import java.awt.*;
import java.awt.event.*;
public class HexBoard extends Frame {
    public static int board_size = 7;
    public static int width = 980;
    public static int height = 600;
    private static int cellSize = width / (board_size + 20);
    public static int radius = (cellSize + cellSize / 4) / 2;
    public static int center_x = width / 2 - radius / 4;
    public static int center_y = (height - radius) / 2;
    public static double[][] grids;
    public HexBoard() {
        grid();
        this.setSize(980, 600);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
    public void init() {
        grid();
    //addMouseListener(this);
    private void drawNeck(Graphics g, double x, double y, double r, int n, boolean filled) {
        Polygon p = new Polygon();
        for (int i = 0; i < n; i++) {
            p.addPoint((int) (x + r * Math.cos(i * 2 * Math.PI / n)),
                    (int) (y + r * Math.sin(i * 2 * Math.PI / n)));
        if (filled == true) {
            g.fillPolygon(p);
        } else {
            g.drawPolygon(p);
//Draws a n-Eck polygon with the given parameter
    public void drawNeck(Graphics g, double x, double y, double r, int n) {
        drawNeck(g, x, y, r, n, false);
//Draws a filled n-Eck polygon with the given parameter
    public void fillNeck(Graphics g, double x, double y, double r, int n) {
        drawNeck(g, x, y, r, n, true);
    //Draws oval
    public void draw_oval(Graphics g, double x, double y) {
        x = x - radius * Math.sqrt(2) * 0.5;
        y = y - radius * Math.sqrt(2) * 0.5;
        int x_value = (int) x;
        int y_value = (int) y;
        double r = radius * 1.5;
        int rr = (int) r;
        g.drawOval(x_value, y_value, rr, rr);
    //Draws oval
    public void draw_filloval(Graphics g, double x, double y) {
        x = x - radius * Math.sqrt(2) * 0.5;
        y = y - radius * Math.sqrt(2) * 0.5;
        int x_value = (int) x;
        int y_value = (int) y;
        double r = radius * 1.5;
        int rr = (int) r;
        g.fillOval(x_value, y_value, rr, rr);
//here the paint method which needs to be modificated
    public void paint(Graphics g) {
        for (int i = 0; i < board_size * board_size; i++) {
            //draw_oval(g, grids[0], grids[i][1]);
//draw_filloval(g, grids[i][0], grids[i][1]);
drawNeck(g, grids[i][0], grids[i][1], radius, 6);
// find the center of hexagon grids
public void grid() {
int count = 0;
grids = new double[board_size * board_size][2];
grids[0][1] = center_y;
if (board_size % 2 != 0) {
grids[0][0] = center_x - radius * (board_size + num_odd(board_size) - 1);
} else if (board_size % 2 == 0) {
System.out.printf("even");
grids[0][0] = center_x - radius * (board_size + num_even(board_size) - 1) + radius / 2;
for (int i = 1; i < board_size * board_size; i++) {
count = count + 1;
if (count == board_size) {
count = 0;
grids[i][0] = grids[i - board_size][0] + radius + radius / 2;
grids[i][1] = grids[i - board_size][1] - radius * Math.sqrt(3) * 0.5;
} else {
grids[i][0] = grids[i - 1][0] + radius + radius / 2;
grids[i][1] = grids[i - 1][1] + radius * Math.sqrt(3) * 0.5;
// finds the number of odd numbers smaller than a bigger odd number
public static int num_odd(int size) {
int[] temp = new int[board_size];
int num_odd = 0;
int count = 0;
for (int i = 0; i < size; i++) {
temp[i] = count;
if (temp[i] % 2 != 0) {
num_odd = num_odd + 1;
count = count + 1;
return num_odd;
// finds the number of even numbers smaller than a bigger even number
public static int num_even(int size) {
int[] temp = new int[board_size];
int num_even = 0;
int count = 0;
for (int i = 0; i < size; i++) {
temp[i] = count;
if (temp[i] % 2 == 0) {
num_even = num_even + 1;
count = count + 1;
System.out.printf("dd " + num_even);
return num_even;
public void changeSize(int size) {
board_size = size;
repaint();
public void mouseReleased(MouseEvent e) {
public static void main(String args[]) {
HexBoard hex = new HexBoard();
hex.setSize(width, height);
hex.setVisible(true);
}Edited by: gamewell on Apr 22, 2008 12:16 PM
Edited by: gamewell on Apr 22, 2008 12:17 PM
Edited by: gamewell on Apr 22, 2008 12:18 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

well, i didn't build the tile marix in the end. Instead, I calculated Euclidean distance between the hex grids center and a mouse Cursor point using nearest neighebor algorithm.
    public int CursorToGrid (int x, int y) {
        int grid_index = -1;
        double temp = Integer.MAX_VALUE;
        double distance[] = new double [board_size*board_size];
        // find the nearst neighbor using Euclidean distance
        for (int i = 0; i < board_size * board_size; i++) {
            distance[i] = Math.sqrt(Math.pow(grids[0]-x,2)+Math.pow(grids[i][1]-y,2));
System.out.println(distance[i]);
if (distance[i] < temp) {
temp = distance[i];
grid_index = i;
// check if a click outsite the hex map
if ( distance[grid_index] > radius) {
grid_index = 10000;
System.out.println("the grid " + grid_index);
return grid_index;
works:D                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • How to make a hex grid?

    I need to make a hex grid in Illustrator. There are two catches:
    1) The hex grid is a particular shape: I'm looking for an easy way to put together a particular pattern of hexes.
    2) There can be no duplicate lines. So I can't simply cut & paste the same single hex over and over, because everywhere the hexes overlapped there would be two lines. The final graphic from this is going to be output to a laser table. Anywhere the data shows two overlapping lines, the laser will burn twice, which ruins things, and could even be a fire hazard.
    So pardon my newbishness, but would any of you care to offer pointers?
    Thanks in advance.

    baudot,
    Sorry, there were a few errors in the moves and a step (4) too much in the instructions. Here is a corrected version:
    You may:
    1) Create one hexagon with radius R;
    2)  Direct Select the bottom and the three top segments and  Object>Transform>Move: X = 3/4 times the width (1.5*R) and Y = 0.5  times the height (about 0.866*R, you can copy the height form the Transform palette/panel)), and Copy; this creates independent  paths;
    3) Direct Select the two slanting paths and  Object>Transform>Move: X = -3/4 times the width and Y = 0.5 times  the height and Copy;
    Now you have the basic unit;
    4) Group everything;
    5)  Effect>Distort & Transform>Transform and Move = X = 1.5 times  the width (3*R) and Y = 0, set the number of horizontal copies;
    6)  Effect>Distort & Transform>Transform and Move = X = 0 and Y =  1  times the total height of the group, set the number of vertical  copies.
    With this, you just have one basic unit, and the rest is an effect.
    You may Object>Expand Appearance to get independent paths, especially if you wish to remove parts of the pattern.
    You may start with a white fill so you can see the closed paths, and you may remove the fill when done.
    I still believe this is the easiest/most accurate way.

  • Making clickable buttons to open xml images in gallery

    I want to do an xml grid image gallery similar to http://www.republicofcode.com/tutorials/flash/as3gridgallery/
    However, instead of using thumbnails, I already have images on my site that I want to make clickable buttons to open the images in the gallery...how would I script these buttons?
    [link removed by moderator]

    If you want it to be similar to the one you link then use the images in the grid like in the one you linked.

  • Having problem in making iteration in grid.

    Hello, I want to make a grid in which when user clicks on the first element of each array a pattern evolves, as shown in the jpg attached. Till now i am able to draw take clicks from the user and change color. But when i try to do the iteration either my vi hangs or does not work out. The pattern which should evolve in real time should be for eg if i click on the first element of 7th array and make it red, then after that the 1st element of the 6 th array will become red, after that 2nd element of array 5 and so on. I have attached the snapshot to make it more clear. I know the algorithm  but the problem is I am very new to labview so I am not able to implement it. And I don't understand one thing, if I add one or more event structure in the same loop why my vi hangs.I am attaching my vi till point it is working perfectly. Thanks in advance.
    Solved!
    Go to Solution.
    Attachments:
    snap shot.jpg ‏176 KB
    square grid making changes 1.vi ‏239 KB

    GJ;AKLDFJG wrote:
     If I make another event to clear grid, i need to fire the event having mouse up .
    What's wrong with "value changed" as you have now? Also make sure that the terminal is inside the event case so it correctly resets.
    GJ;AKLDFJG wrote:
    I also tried many other ways but the problem that occurs most of the time is that everything is grayed out after i press the clear button and if I try to use grid again it doesn't respond at all. It becomes black in color.
    It is not sufficient to initialize the 2D array in the shift register, you also need to rewrite all the 1D arrays. You did not include the subVI, so I cannot run to see what you are seeing.
    Why do you have these hidden stop buttons?
    Remember that the "lock front panel" settings is per event, and not per event case. You only disabled it for "array 1", but not for the other arrays.
    You also have race conditions due to overuse of local variables (Why do you write to (terminal or local var) and read from (local var) "output array"? Most likely, the read operation occurs before you write the new values to it, leading to unexpected results. Solution: delete the hidden controls and wire the 2D array (from the shift register) directly to the subVI input. There is no need for a front panel object. You can also delete the local variable "number of?": place the terminal inside the array case to replace the local and read the value from the "new value" event terminal in its event frame). You can change all the 1D arrays to indicators and eliminate the local variables, the mouse up will still work.
    Your subVI has way too many connectors to be manageable. If you would feed it the array of references, it would not need any outputs at all (defer panel updates while writing the arrays). The outputs also have incorrect representation. They should NOT be orange!
    Don't call the subVI with every iteration of the inner while loop, discarding the output values until the last iteration. Update the display once the loop has finished and after the case structure.
    There should not be while loops inside event cases, unless they are not interactive and are guaranteed fo complete quickly.
    Please attach the missing subVI.
    LabVIEW Champion . Do more with less code and in less time .

  • Making clickable links in GUI?

    Hi,
    Well, I'm making an GUI application and I wanted to have a clickable link to my website, I thought using HTML would be a good bet, but it doesn't work, I was thinking of using util but I'm not exactly sure..

    Swing related questions should be posted in the Swing forum.
    JEditorPane provide some basic support for loading HTML pages. Read the API for more info.
    You can invoke IE as follows:
    **  Here is a pure Windows solution
    **  Run the code and you will be taken to a tutorial that may provide
    **  a more generic solution
    public class WindowsFileProtocolHandler
         public static void main(String[] args)
              throws Exception
              String[] cmd = new String[4];
              cmd[0] = "cmd.exe";
              cmd[1] = "/C";
              cmd[2] = "start";
              cmd[3] = "http://www.javaworld.com/javaworld/javatips/jw-javatip66.html";
    //          cmd[3] = "will.xls";
    //          cmd[3] = "mailto:";
    //          cmd[3] = "a.html";
    //          cmd[3] = "file:/c:/java/temp/a.html";
              Process process = Runtime.getRuntime().exec( cmd );
    }

  • Making clickable links in a TextArea?

    Hi there,
    I made a TextArea where several URLs are being displayed in the form (http://www.url.com)...does anybody know if it is possible to make these hyperlinks? So the user can click on whichever one they want and view it in their primary browser?
    If someone can help me here, I'd reallly appreciate it. Would be great.
    Thanks in advance,
    -jtk

    I made a TextArea where several URLs are being
    displayed in the form (http://www.url.com)...does
    anybody know if it is possible to make these
    hyperlinks? So the user can click on whichever one
    they want and view it in their primary browser?instead of using a TextArea you could use a Jlist
    then add a mouse_clicked event and then call
    Runtime.getRuntime().exec("cmd /c start "+tempString);
    where tempString is your URL in the list
    chidychi

  • Making Clickable Executable

    After I have created a program, how can I make it click-executable (meaning, I can click an desktop icon and it will run). Do I need to create a batch file(Windows)? How do I support Macintosh users?

    Make it an executable Jar file using the Jar tool

  • Why does DW CC 2014.1 Fluid Grid load HTML file that contains Google Analytics Tracking Code script so slowly?

    I exclusively work in Fluid Grid since my site is a Responsive Web Design.  I'm having trouble with slow load time in DW CC 2014.1, when my file, as they all do of course, has the Google Analytics Tracking Code script.
    I'm on a Windows 8.1 using a Dell Precision M3800 Laptop with Memory 16GB (2x8GB) 1600MHz DDR3 . Each of our site's 180 or so web pages, of course, has its Google Analytics Tracking Code script. It is placed, following Google instructions, as the last entry in the <head>.  Google Analytics does not instruct to place the script in the JS Folder with an scr to it, but rather in the <head>.  It takes up to one and a half or two minutes for DW CC 2014.1 to load the Google Analytics Tracking Code script .  That is, the grid does not show in Live View until finally analytics.js shows up in the Document Toolbar. A minute or two can add up when every page you load takes this long.  And, making new Fluid Grid pages, as is done, through the Save As command; every new page made you have to deal with the minute or two wait time since all those pages have the Google Analytics Tracking Code script.  Therefore, this time component alone, assuming I'm accessing and/or making 20 pages per week (and in our business this is easily the case) the math is that I'm wasting between 17 and 35 hours per year just with DW CC 2014.1 loading the much needed Google Analytics Tracking Code script.
    I have loaded HTML files that do not have the Google Analytics Tracking Code script as a test and those files load at the normal quick speed.
    Therefore, the new Chromium Embedded Framework browser engine has a serious load problem when it confronts an HTML5 file with a Google Analytics Tracking Code script.  Oddly, the prior DW CC 2014 version, with the old browser engine did not have this slow-load problem since I was loading these same files in that DW CC version up until October 8th or so.
    I think this new browser engine is a Google platform that apparently has a problem rendering or loading a Google Analytics Tracking Code script.  That makes no sense.
    Anyone else had this particular slow-load problem with DW CC 2014.1?
    Thanks.

    Wow.  That sure solved the slow-load problem, at least using your suggested snippet in a simple test HTML file.
    Per Google's instructions, I pasted the snippet before the closing </head> tag.  And, even in that positioning in the file; the file loaded at the speed (about one second) that it did prior to DW 2014.1.
    Two questions.
    Will this snippet provide the same tracking data as my current GA snippet?
    Because my current GA snippet is in about 200 web pages, can I retain the old snippet in most of them and place the new snippet in my approximately 5 main web pages as well as my templates so my new pages, as well as my main pages, have the new snippet.  That is, can I have both snippets (i.e. old snippet in earlier pages and new snippet in main pages and new pages to be made going forward) in my website at the same time?
    Of course I would not have both the old and new snippet in a web page at the same time.
    I greatly appreciate any assistance anyone can provide me on this issue and thank all of you in advance.
    I've provided code for both simple test files below.
    Code for Asynchronous Syntax of GA script:
    <!doctype html>
    <!--[if lt IE 7]> <html class="ie6 oldie"> <![endif]-->
    <!--[if IE 7]>    <html class="ie7 oldie"> <![endif]-->
    <!--[if IE 8]>    <html class="ie8 oldie"> <![endif]-->
    <!--[if gt IE 8]><!-->
    <html class="">
    <!--<![endif]-->
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test Asynchronous GA Tracking Code In Head</title>
    <link href="css/boilerplate.css" rel="stylesheet" type="text/css">
    <link href="/css/style.css" rel="stylesheet" type="text/css">
    <!--
    To learn more about the conditional comments around the html tags at the top of the file:
    paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/
    Do the following if you're using your customized build of modernizr (http://www.modernizr.com/):
    * insert the link to your js here
    * remove the link below to the html5shiv
    * add the "no-js" class to the html tags at the top
    * you can also remove the link to respond.min.js if you included the MQ Polyfill in your modernizr build
    -->
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="js/respond.min.js"></script>
    <script type="text/javascript">
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-73425000-1']);
      _gaq.push(['_trackPageview']);
      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    </script>
    </head>
    <body>
    <div class="gridContainer clearfix">
      <div id="div1" class="fluid">
        <div id="test1" class="fluid ">This is the content for Layout Div Tag "test1"</div>
       <div id="test2" class="fluid ">This is the content for Layout Div Tag "test2"</div> 
    </div>
    </body>
    </html>
    Code for older GA script snippet:
    <!doctype html>
    <!--[if lt IE 7]> <html class="ie6 oldie"> <![endif]-->
    <!--[if IE 7]>    <html class="ie7 oldie"> <![endif]-->
    <!--[if IE 8]>    <html class="ie8 oldie"> <![endif]-->
    <!--[if gt IE 8]><!-->
    <html class="">
    <!--<![endif]-->
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test GA Tracking Code In Head</title>
    <link href="css/boilerplate.css" rel="stylesheet" type="text/css">
    <link href="/css/style.css" rel="stylesheet" type="text/css">
    <!--
    To learn more about the conditional comments around the html tags at the top of the file:
    paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/
    Do the following if you're using your customized build of modernizr (http://www.modernizr.com/):
    * insert the link to your js here
    * remove the link below to the html5shiv
    * add the "no-js" class to the html tags at the top
    * you can also remove the link to respond.min.js if you included the MQ Polyfill in your modernizr build
    -->
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="js/respond.min.js"></script>
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-73425000-1', 'auto');
      ga('send', 'pageview');
    </script>
    </head>
    <body>
    <div class="gridContainer clearfix">
      <div id="div1" class="fluid">
        <div id="test1" class="fluid ">This is the content for Layout Div Tag "test1"</div>
       <div id="test2" class="fluid ">This is the content for Layout Div Tag "test2"</div> 
    </div>
    </body>
    </html>

  • ALV Grid  screen limit for a long field

    Hi, i am having a problem making an ALV Grid of IDOC contents, i want to show de SDATA field of de EDIDD structure, but it is a 1000 char field, and when the ALV comes out i can only see part of the field.
    I think the problem is the scrollbar, because it seems it not allows to scroll unless a field is starting or ending at the right or left of the screen.
    It is a way to solve this problem?
    thanks
    best regards
    Mariano Billinghurst.

    a®s, thank you I have already tougth that solution but my client wants to see all in the alv to compare the lines.
    I anyonelse have an idea it is wellcome!
    thanks.
    mariano.

  • Clickable ads in PDF

    I am making clickable ads within a PDF that I am going to post on my company's website. I have been successful with all of the ads but one. When I type the url in and then I try to click on the ad it has somehow added more words, that look like the path to where the ad is stored on my computer, to the url and it comes back saying the website cannot be found. Any ideas on how to just make it use the url I am typing in and not add the additional words?

    Thanks for your help. I seem to have figured it out. It was simply that I needed to add an "http://" at the front of the url. None of the other ads required this, but the one that wasn't working did. Not sure what the difference was, but it's working now. Thanks again for your help!

  • Making transitions respond to onclick

    Ive managed the simple hover transition
    <style>
    #trans {
    opacity:100;
    transition: all 1st ease-in-out;
    #trans:hover {
    opacity:0;
    </style>
    but i would like to make it clickable instead of hover. The only example i found that illustrates clickable transitions is (http://css3.bradshawenterprises.com):
    <div id="cf2" class="shadow">
         <img class="bottom" src="/tests/images/Stones.jpg" />
         <img class="top" src="/tests/images/Summit.jpg" />
    </div>
    <p id="cf_onclick">Click me to toggle</p>
    #cf2 {
         position:relative;
         height:281px;
         width:450px;
         margin:0 auto;
    #cf2 img {
         position:absolute;
         left:0;
         -webkit-transition: opacity 1s ease-in-out;
         -moz-transition: opacity 1s ease-in-out;
         -o-transition: opacity 1s ease-in-out;
         transition: opacity 1s ease-in-out;
    #cf2 img.transparent {
         opacity:0;
    #cf_onclick {
         cursor:pointer;
    $(document).ready(function() {
         $("#cf_onclick").click(function() {
              $("#cf2 img.top").toggleClass("transparent");
    I tried implementing this but have had no luck and i dont see any way of
    adpating this for more complex moves. Anyone know of a simpler way of
    making clickable css transitions?

    ...

  • Hex Map

    Hey,
    I am creating a small hex-based board game for a programming class and am having some problems with the hex map.
    I have created the map as a 2D array of clickable Hexes each of which is a single JComponent. A Mouse Hex is actually a rectangular shape with a hexagonal shaped polygon drawn in its center. When the map is originally drawn it is drawn left to right, top to bottom and the map looks fine.
    Each hex also contains a mouse listener which can be used to place pieces on the board and move them around, a piece in my case is represented as an icon with the JComponent using its draw image function to set the icon when the mouse is clicked. This is where the problem comes in, when I click the mouse over the game board the icon appears... but so do the four corners of the rectangle underlying the hex. Since the underlying rectangles are overlapping in the case of the hex map this causes some flickering among the hexes as I see a whole mess of flickering rectangles as each piece is laid.
    I have considered several solutions to this problem but have been unable to find one that works, does anyone know of a solution to this problem?
    Thanks very much,
    Tim

    I'm looking at doing something similar, and I've been contemplating the same problem. The idea I've some up with is to define the Map as abolute and draw directly onto the graphic, this will give nothing to show through when the click event happens. Each cell has to be defined mathematically, a rectangle in the middle and then 12 right triagles around the edges (each point of the hex subdevided into 2 so the formulas for right triangles work) and then the coordinates of the mouse click have to mapped back into a logical game cell. I'll see how it goes, I'm still months away from implementation of any part of my game idea.
    Hope this helps.
    Good Luck.

  • 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.

  • Importing text file into 2D char array

    Hey folks. I've aged a few years trying to figure this project out. Im trying to make a crossword puzzle and am having problems importing the answer letters into a 2D array of 15*15. The text file would look something like this:
    LAPSE TAP RAH
    AVAIL OLE ODE
    BARGE PARADOX
    etc
    I have JTextFields that the user will answer and a button the user can press to see if the answers are right by comparing the 2D array answer with what the user inputted.-the user input would be scanned and put into a 2D array also.
    How should i go about inserting each letter into an array? The spaces i would later need to make code to grey out the text field. This is what i have so far. Forgive me if its sloppy.
         class gridPanel extends JPanel
              //----Setting Grid variables
              private static final int ROWS = 15;
              private static final int COLS = 15;
              String[] letters = { "A", "B", "C", "D", "E" };// To test entering strings into array
               gridPanel()
                 this.setBackground(Color.BLUE);
                 //.......Making my JTextField grid for user input
                 JTextField[][] grid = new JTextField[ROWS][COLS];
                 for(int ROWS = 0; ROWS<grid.length; ROWS++)
                     for(int COLS = 0; COLS<grid.length; COLS++)
                         grid[ROWS][COLS] = new JTextField(1);
                         add(grid[ROWS][COLS]);
                     //grid[ROWS][COLS].setText("" + letters[0]);
                 String an = null;
                 StringTokenizer tokenizer = null;
                 Character[][] answer = new Character[ROWS][COLS];
              try{
                 BufferedReader bufAns = new BufferedReader( new FileReader("C:\\xwordanswers.txt"));
                 for (int rowCurrent = 0; rowCurrent < ROWS; rowCurrent++)
              an = bufAns.readLine();
              tokenizer = new StringTokenizer(an);
              for (int colCurrent = 0; colCurrent < COLS; colCurrent++) {
              char currentValue = tokenizer.nextToken().charAt(0);//Needs to be changed to reflect each letter
                        answer[rowCurrent][colCurrent] = currentValue;
                    System.out.println(currentValue);
              }catch (IOException ioex)           
                        System.err.println(ioex);
                        System.exit(1);
            }//xword graphics end
          This obviously prints the first char of each word, it also gives me an "Exception in thread "main" java.util.NoSuchElementException" error for some reason.
    Any help is greatly appreciated.
    John

    If the file format is stored as follows:
    APPLE
    L A
    PARSE
    N E
    PEAR then we can parse this into a 2D char array:
    char[][] readMap(String fileName) {
        char[][] ret = new char[ROWS][COLS];
        FileInputStream FIS = new FIleInputStream(fileName);
        int i, j;
        for(i = 0; i < ROWS; i++)
            for(j = 0; j < COLS; j++)
                ret[i][j] = FIS.read();
        FIS.close();
        return ret;
    }Then you can use the resulting 2D char array in your answer checking mechanism.
    Hope this helps~
    Alex Lam S.L.

  • How to add one column for entry in the TLB screen?

    Hi all,
    Does anybody know how to add a customised column for free text in the TLB header screen? The reason is user needs to add ship or container no. This info will be later on interfaced via CIF exit to R/3.
    I think many of you have the same requirement.
    Thanks heaps!

    Thanks Digambar,
    Can you help to work out more detail on how to customize the code in the TLB screen?
    Are you thinking of adding one field in the table and making the ALV grid control editable? If you have any reference doc/link to do it, it would great!
    Cheers,

Maybe you are looking for

  • Number of elements in TDMS file

    Is there a way to determine the number of elements in a TDMS file?  The files I am creating have several signals all of the same length.  The only way I can think of is to do this is put it in a loop and read one element at a time until it reaches th

  • Oiix.Spawn error when installing 9iAS EE on Windows 2000

    I am performing a silent installation (with a response file) of Oracle9iAS Enterprise Edition on Windows 2000 with 512 MB RAM. At 59%, I get an error stating "This install was unsuccessful because: oracle.sysman.oii.oiix.OiixSpawner. Would you like t

  • After an firefox auto-update, there is a circle with slash over the icon (do not) and it will not launch.

    Firefox was doing one of its automatic updates and it never finished but a circle with a slash through it appeared on the icon and now Firefox won't launch. It gives the following error message: "The application "Firefox" cannot be launched. -10661"

  • Creative cloud apps (ALL) crashing after opening

    I purchased CC yesterday for a very very very time sensitive project. It crashes!!! I have tried everything that's been suggested on your website. What is wrong with the program/s? I am extremely frustrated with it. Windows 7 Dell XPS 8500 upgraded v

  • Can i watch my tv show purchases offline?

    My friends keep tellin me that i can watch my tv show purchases also offline but for some reason i'm not able to... i always have to sign online first . Anyone knows what i have to do to watch offline as well?????