Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
kaniff
Feb 27, 2004

oh word?

mister_gosh posted:

I have a servlet which kicks off a separate jar (all my own code). I want to set up a queue for kicking off this separate operation because the operation can take some time and/or we can get multiple requests at a time. I want to process one at a time.

I think I could set up a first in/first out (FIFO) queue type process, but what I'm fuzzy on is how I can have the servlet connect to an already existing queue manager program?

Let's say John executes the servlet which in turn kicks off the separate process. 2 minutes later, John is still waiting for the separate process to finish (and the final servlet response) and Jane executes her own servlet connection. I want her to connect to the same queue manager class instance so that it can read the same queue FIFO values which are most current (and have her rightfully wait for John's to finish).

I'd prefer not to write temporary values to a filesystem in order to manage the queue. Is there something fundamental I am missing? I'm self taught, so perhaps I'm missing something very fundamental when it comes to connecting to a pre-existing class instance...

What about a threadpool of one? It essentially becomes a FIFO, but should do what you need.

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Since you own the other library anyway, why not give it a public API that you can just call from your servlet? Then you just need to create a worker thread to read your queue and make the API calls.

There are plenty of serviceable concurrent queue implementations in any modern version of Java; just look through java.util.

Plinkey
Aug 4, 2004

by Fluffdaddy
I've got a problem with painting in 2d to an InternalJFrame.

I have an app that is best described as an MDI. I have an InternalJFrame that has tabs on it that will each show different information from a database. What I'm having problems with is being able to manipulate the graphics of the JPanels I attach to the Tabs. (I'm not actually at the tabs yet, just trying to add the JPanel to the InternalJFrame and have it show some sample graphics.)

Here's some code:

code:
public class FlightCardPrint extends InternalJFrameAbstract implements Printable{

    private FlightCard flightCardInfo = new FlightCard();

    private PrintFramePanel printArea = new PrintFramePanel();

    int maxX;
    int maxY;
    
    public FlightCardPrint()
    {
        super.setLocation(20, 20);
        super.setSize(756,576);
        super.setResizable(true);
        super.setClosable(true);
        super.setMaximizable(false);
        super.setIconifiable(true);
       
        //* Add the print area to the frame.
        this.add(printArea);
        printArea.setSize(this.getHeight(), this.getWidth());
        printArea.setVisible(true);
    }
     
    //* Constructor, bring it all the info that will need to be printed
    //      in a flight card struct.
   /*
    public FlightCardPrint(FlightCard fc){
        flightCardInfo = fc;
    }

    //@Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

   // @Override
    public void setSQLConnection(SQLHelper DbHelper) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
And the JPanel to paint to that will eventually be put in Tabs in the InternalJFrame
code:
public class PrintFramePanel extends JPanel {

    /* Frist step is to send in the FlightCard information
     *
     *
     *
    */
   public PrintFramePanel()
   {}


    /* Anything that needs to be painted goes here. All flight cards will show
     * the same basic information...so this needs to take care of formatting...etc.
    */

    @Override
    public void paint(Graphics g)
    {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D)g;
        g2d.translate(this.getWidth(), this.getHeight() );
        FontMetrics metrics = g2d.getFontMetrics();

        //* Rectangle around everything
        g2d.drawRect(0, 0, (int)this.getWidth(),(int)this.getHeight());
        //* Dividing centerline.
        g2d.drawLine((int)(this.getWidth()/2) , 0 + metrics.getHeight()(int)(this.getWidth()/2),(int)this.getHeight());
        //* Rect around header/title
        g2d.drawRect(0, 0, (int)this.getWidth(), metrics.getHeight());

        g2d.drawString("Card #X", 10, metrics.getHeight() - metrics.getDescent());

    }

}
The stuff that is being printed into the JPanel is just some same stuff that I was using to play with sending to the printer (that I got working fine) but I can't get anything to show on the InternalJFrame. It's been a while since I've worked with 2D Drawing in JAVA and I feel like I'm missing something stupid here. All that shows up is the InternalJFrame on the "desktop" frame and it's blank.

Thanks for any input you guys can give me.

And a picture of what I've got so far because that might explain it a bit better : http://sa.plinkey.com/JavaApp.JPG


edit: Is this a problem with mixing swing a AWT components? I got the text to show up but its in the menu bar of the Internal Frame. When I add a button using a FlowLayout Manager the button shows up in the right spot of the Internal Frame's Content Pane. And all of my 2d drawing seems to be trapped in the menu bar...wtf.

Plinkey fucked around with this message at 20:23 on Mar 23, 2009

mister_gosh
May 24, 2002

rjmccall posted:

Since you own the other library anyway, why not give it a public API that you can just call from your servlet? Then you just need to create a worker thread to read your queue and make the API calls.

There are plenty of serviceable concurrent queue implementations in any modern version of Java; just look through java.util.

I guess I'm just confused overall on how to do this. the concurrent queue implementations address this? I guess you can tell I haven't worked with threads.

Basically I have a java program which may fire. Then a separate one may fire later. How does the other java process learn about the first one?

All of the queue examples I'm seeing assume that the multiple requests are all right there in front of you, and you need to divide them up.

Which is why I ask, is there a way to grab on to a previously running class instance (so that I can learn of its instance variables to learn the order of the queue, enqueue it up, etc).

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
I was saying that you should consider running your library code inside the same process as your servlet, setting up a thread to poll a concurrent queue being fed by multiple producers (the servlets). This should be rudimentary concurrency work, but you seem to be totally ignorant of threads, and possibly of basic OO design. In that case, I strongly suggest not doing what I previously recommended, because of the very real danger that you might get something to work.

Threads are a very difficult problem, and if you want to learn to do them properly, you will need to actually study — not necessarily in a formal setting, but in some way where you really pick up the ideas.

Summit
Mar 6, 2004

David wanted you to have this.
What's the simplest DOM style XML reader available in Java? I don't need to write XML files, just read them occasionally.

kaniff
Feb 27, 2004

oh word?

Cloud Dog posted:

What's the simplest DOM style XML reader available in Java? I don't need to write XML files, just read them occasionally.

Can't really go wrong with JDOM and SAX

TheDapperGinger
Sep 30, 2004

I wear national geographic jackets!
This is for a school project, I've been staring at it too long so its all blending together and I can't workout why this only outputs the last name in the text file. I'll be checking back regularly if you have questions or need the other class posted.
code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * NEEDS TO WRITE TO FILE DOES NOT YET.
 */

package Problem2;

import java.io.*;
import java.util.StringTokenizer;
import javax.swing.*;



/**
 *
 * @author Austin
 */
public class GradeDriver {
public static String strtemp;
public static String input;
public static String studentname;
public static String studentid;
public static Double dbltemp;
public static Double exam1scores;
public static Double exam2scores;
public static Double exam3scores;
public static Double exam4scores;
public static Double homeworkscores;
public static Double[] averages;
public static char chartemp;
public static char[] lettergrades;
public static int i=0;
public static int linecount=0;
public static boolean swapped=false;
public static GradeClass[] gc;
public static GradeClass[] gctemp = new GradeClass[0];


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {

        BufferedWriter bw = new BufferedWriter(new FileWriter("gradereport.txt"));
       BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
      
       strtemp=br.readLine();
       strtemp=br.readLine();
       while(br.ready())
       {
        strtemp=br.readLine();
        linecount+=1;
       }
       br.close();
       //initialize the variables to the linecount of the file sans the headings
       
       averages = new Double[linecount];
       lettergrades = new char[linecount];
       gc = new GradeClass[linecount];
       br = new BufferedReader(new FileReader("grades.txt"));

       strtemp=br.readLine();
       strtemp=br.readLine();
       
       
       

       while(br.ready())
       {
        int incrementer=0;
       input=br.readLine();
       StringTokenizer st = new StringTokenizer(input,",");
       studentname=st.nextToken();
       
       studentid=st.nextToken();
       
       exam1scores=Double.parseDouble(st.nextToken());
       exam2scores=Double.parseDouble(st.nextToken());
       exam3scores=Double.parseDouble(st.nextToken());
       exam4scores=Double.parseDouble(st.nextToken());
       homeworkscores=Double.parseDouble(st.nextToken());

       //======================================================================
       
       gc[i]= new GradeClass(studentname,studentid,exam1scores,
       exam2scores,exam3scores,exam4scores,homeworkscores);
       
      System.out.println(gc[i].getname());
       averages[i]=gc[i].Gradecalc();
       lettergrades[i]=gc[i].calclettergrade();


       //======================================================================
       i+=1;

       }
       br.close();
       JTextArea outputarea = new JTextArea(20,50);

/*
int n = gc.length;
    for (int pass=1; pass < n; pass++) {
        for (int z=0; z < n-pass; z++) {
            if ((gc[z].getname()).compareToIgnoreCase(gc[z+1].getname())<0)
            {
                System.out.println(gc[z]);
                // exchange elements
                gctemp[0] = gc[z];
                gc[z] = gc[z+1];
                gc[z+1] = gctemp[0];
            }
        }
    }

/*
    for (int pass=1; pass < gc.length; pass++) {  // count how many times
        // This next loop becomes shorter and shorter
        for (i=0; i < gc.length-pass; i++) {
            if ((gc[i].getname()).compareToIgnoreCase(gc[i+1].getname())>0)
            {
               
    gctemp[0]=gc[i];
    gc[i]=gc[i+1];
    gc[i+1]=gctemp[0];

            }
        }
    }



 */
outputarea.setEditable(false);

i=0;
for(i=0;i<gc.length;i++)
{

outputarea.append("Grade Report for: " + gc[0].getname()+ "\n"
        +"=======================================\n"
        +"=  Student ID:  " + gc[i].getid() + "\n"
        +"=           GPA: " + Math.ceil(averages[i]) + "\n"
        +"=Letter Grade: " + lettergrades[i] + "\n");

}
System.out.println(gc[i].getname());
 FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
    
    //Close the output stream
JScrollPane soutputarea = new JScrollPane(outputarea);
       JOptionPane.showMessageDialog(null,soutputarea);


} 

Huckle
May 19, 2007
Chuckle With Huckle!
I have this assignment due tomorrow..

quote:

Fifteen numbered tiles are placed in a 4x4 grid, with one empty slot. Tiles are moved horizontally or vertically into the empty slot. The object is to slide the tiles to get to the above configuration. You can then mix up the tiles and try again. Tiles can only be moved by sliding into the empty location. (In the figure above, 12 can move down or 15 to the right. No other tiles may move.)
Variations include images rather than numbers, and when arranged properly they form one large picture. (The format is different, but the concept is the same.)
You are to write a Java program to implement the sixteen puzzle. Clicking on one of the squares adjacent to the empty square (either 12 or 15 in the diagram above) should result in moving the clicked block into the empty space. This should, obviously, make the vacated space empty. Clicking on any other square should have no effect.
The program should start with the puzzle in order, and a sequence of clicks can be used to "mix it up" it before solving.
Your program should also have a "Solve" button that arranges the tiles in order and a "Randomize" button that mixes them up. However, note that you cannot just randomly distribute the tiles, or the puzzle may be unsolvable. To properly randomize, you have to start with the tiles in sequence and make a series of 'random' legal moves.

I've been working on this for 6+ hours, just rewriting and rewriting the code. I'm totally stuck. I have to use somewhat basic java (I'm just using a simple JFrame button GUI and changing the labels.)

Here is my most recent attempt:
http://asfawdgfevgef32f32.pastebin.com/m5402843d

I just have no idea how I should go about this. I don't know how I can let the numbers shift up and down, or to the right or left - yet not diagonally without having a ton of if statements in every action listener.

Also, I have absolutely no idea on how I should go about changing the button labels every time.

Can anybody point me in the right direction?

Thanks in advance for any help with this.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

redfoxxx posted:

code:
       strtemp=br.readLine();
       strtemp=br.readLine();
       while(br.ready())
       {
        strtemp=br.readLine();
        linecount+=1;
       }
       br.close();

Meditate upon this passage, young one.

TheDapperGinger
Sep 30, 2004

I wear national geographic jackets!

rjmccall posted:

Meditate upon this passage, young one.

I'm not sure I understand what you mean. What's wrong with that snippet. What I was trying to do was pre-count the number of data lines read from a text file with 2 header lines.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Huckle posted:

I have this assignment due tomorrow..

Awesome.

The significant problem here is that, when you click on a button, you need to know its position within the grid, as well as the position of the empty space. If you're going to do this by relabeling the buttons, you obviously can't use the button labels to figure out the button's positions, so you'll have to determine it based on something that doesn't change. Now, there are two relevant objects here: there is a button, and there is an action listener associated with the button. You will need to put this information on one of these objects. Pick.

Changing the text of the label is easy; look at JButton's public API.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

redfoxxx posted:

I'm not sure I understand what you mean. What's wrong with that snippet. What I was trying to do was pre-count the number of data lines read from a text file with 2 header lines.

That'll teach me not to actually read your code — although, why are you actually doing this? What about this problem requires you to read the entire file first?

Anyway, look at the code that prints out reports, and tell me why it always prints the name of the first student (i.e. the student at index 0).

TheDapperGinger
Sep 30, 2004

I wear national geographic jackets!

rjmccall posted:

That'll teach me not to actually read your code — although, why are you actually doing this? What about this problem requires you to read the entire file first?

Anyway, look at the code that prints out reports, and tell me why it always prints the name of the first student (i.e. the student at index 0).

That one is my bad, the 0 in that case is left in while i was testing. In the file we were given the program always prints the last name in the file. It should have read gc[i] just like the rest of the output block. I should have commented it out before posting it, and I should have used pastebin.

[edit]also I should mention that we are reading data from a csv and populating an array of a class for student grades which is why I had to cheat and count the lines first. [/edit]

Huckle
May 19, 2007
Chuckle With Huckle!
Thanks. I've actually made a working puzzle that resets.

http://wadawdfwegfwweg234g.pastebin.com/m5a373b5c

Have any ideas for the randomization feature? I can't just randomize it all - I need the computer to make random legal moves. I'm lost here.

csammis
Aug 26, 2003

Mental Institution

Huckle posted:

Have any ideas for the randomization feature? I can't just randomize it all - I need the computer to make random legal moves. I'm lost here.

code:
Generate solved puzzle
From set of squares adjacent to empty square, randomly choose one
Shift chosen square
Repeat for fifteen moves (or whatever)

ayb
Sep 12, 2003
Kills Drifters for erections
Little confused here. We have to have our user define how big they want the dataset to be then enter the numbers. We then have to calculate the sum, find the biggest one, and find how many times the biggest one appears

code:
import java.util.Scanner;

public class Lab10a_Mike{

 public static void main(String args[])
 {
     int x[] = new int[];
     int j,k;
     int sum = 0;
     Scanner input = new Scanner(System.in);

     System.out.print("How many numbers in dataset? ");
     k = input.nextInt();

     System.out.println("Enter the list of numbers in the Dataset? ");
     for (j=0; j<k; j++){
         x[k] = input.nextInt();

     }

     //set the biggest to the first number in the array
     int biggest = x[0];
     //int count = 0;
     for (int i = 0; i < k; i++){
         if (x[i] > biggest)
            biggest = x[i];
          sum += x[i];
     }

     System.out.println("\nThe sum of the integers was: "+sum);
     System.out.println("Biggest was " + biggest);
     //System.out.println("It appeared: " +count + " time(s)");
     System.exit(0);
 }
}
I am unclear how to get it to allow the user to set the array size since if I make it say

int x[] = new int[k];

I still get a runtime error. I can manually set it to a maximum size(the teachers example used int a[]= new int[5] but if I enter a size bigger than 5 when running the program it crashes. I also get 0 for sum and 0 for biggest no matter what I would enter. Where am I going wrong?

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

ayb posted:

stuff

When arrays are declared they have to have a set size because sequential memory is allotted to them when instantiated. They can not grow past that size otherwise you will get an array out of bounds error.

If you need the array to be dynamic and grow based on the amount of items you will either need to use a different data structure (ArrayList). You could also create a function that returns an array of the correct size with the new item in it (google java growing array).

Obviously use an ArrayList assuming advance data structures are allowed in your class.

lamentable dustman fucked around with this message at 23:33 on Mar 26, 2009

ayb
Sep 12, 2003
Kills Drifters for erections

dvinnen posted:

When arrays are declared they have to have a set size because sequential memory is allotted to them when instantiated. They can not grow past that size otherwise you will get an array out of bounds error.

If you need the array to be dynamic and grow based on the amount of items you will either need to use a different data structure (ArrayList). You could also create a function that returns an array of the correct size with the new item in it (google java growing array).

Obviously use an ArrayList assuming advance data structures are allowed in your class.

I understand now. I emailed the professor and he said to just use a fixed size and not do anything more advanced yet. I have it set and I can enter my numbers but I still can't get it to sum up or tell me what's the biggest

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

ayb posted:

I understand now. I emailed the professor and he said to just use a fixed size and not do anything more advanced yet. I have it set and I can enter my numbers but I still can't get it to sum up or tell me what's the biggest

take a look at these lines:

code:
for (j=0; j<k; j++){
         x[k] = input.nextInt();
     }

ayb
Sep 12, 2003
Kills Drifters for erections

dvinnen posted:

take a look at these lines:

code:
for (j=0; j<k; j++){
         x[k] = input.nextInt();
     }

gah! As soon as I read that I found the problem. Does spotting little errors like this get easier as you do more programming?

spiritual bypass
Feb 19, 2008

Grimey Drawer

ayb posted:

gah! As soon as I read that I found the problem. Does spotting little errors like this get easier as you do more programming?

Sure does. As you make more stupid mistakes, you'll learn the ones that you make most often and hopefully look for those first when your program doesn't work right.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

ayb posted:

I understand now. I emailed the professor and he said to just use a fixed size and not do anything more advanced yet. I have it set and I can enter my numbers but I still can't get it to sum up or tell me what's the biggest
Since it's very simple, I don't feel bad about helping you with this:
code:
int j, k;
int sum = 0;
Scanner input = new Scanner(System.in);

System.out.print("How many numbers in dataset? ");
k = input.nextInt();
int x[] = new int[k];
What exception did you get when you allegedly tried this?

ayb
Sep 12, 2003
Kills Drifters for erections

Lysidas posted:

Since it's very simple, I don't feel bad about helping you with this:
code:
int j, k;
int sum = 0;
Scanner input = new Scanner(System.in);

System.out.print("How many numbers in dataset? ");
k = input.nextInt();
int x[] = new int[k];
What exception did you get when you allegedly tried this?

it said

quote:

Exception in thread "main" java.long.ArrayIndexOutOfBoundsException: 5
at Lab10a_Mike.main(Lab10a_Mike.java:16)"

I just doing the above code again and it is working. Literally the only thing I changed was cutting the int x[] = new int[5]; , making it int x[] = new int[k]; and then putting it after I ask the user how many spaces they want. It's working now but I literally didn't do anything different this time.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

ayb posted:

code:
at Lab10a_Mike.main(Lab10a_Mike.java:16)

That "16" is the line number from which the exception was thrown. It was thrown because you were trying to set index k (i.e. the (k+1)th element) of an array with only k elements. It was fixed as a happy side-effect of fixing the bug dvinnen pointed out.

Twernmilt
Nov 11, 2005
No damn cat and no damn cradle.
I'm running into an OutOfMemoryError while I'm using a double buffer. It draws the first frame fine, but give me the error when it draws the second frame. I'm new to Java so I'm guessing that I'm missing something simple. Also, if I'm going about this all wrong, let me know.

I'm trying to render only the visible portion of a large image to the screen and then apply a grid over it. x and y are the upper left coordinates on the large image. xres and yres indicate the screen resolution. So it should render only a screen sized portion of the image every time drawStuff() is called. What is the best method for limiting how many frames are rendered per second? Sleep doesn't seem like my best option.

Code posted below.

Twernmilt fucked around with this message at 17:37 on Mar 28, 2009

Mill Town
Apr 17, 2006

Twernmilt posted:

I'm running into an OutOfMemoryError while I'm using a double buffer. It draws the first frame fine, but give me the error when it draws the second frame. I'm new to Java so I'm guessing that I'm missing something simple. Also, if I'm going about this all wrong, let me know.

This leads me to believe that you are allocating a new buffer or reloading the image each time without getting rid of the old copy. Post the rest of your code so we can see what's actually happening.

Twernmilt
Nov 11, 2005
No damn cat and no damn cradle.
Primary Class

code:
package ImagePanningTest;

import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;

public class ImagePanningTest extends JFrame implements KeyListener {

    public void keyTyped(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_1 && yscreen >= 25){
            yscreen -= 25;
        }
        else if (e.getKeyCode() == KeyEvent.VK_0 && yscreen <= 3725){
            yscreen += 25;
            System.out.println("gogogogo");
        }
        else if (e.getKeyCode() == KeyEvent.VK_LEFT && xscreen >= 25){
            xscreen -= 25;
        }
        else if (e.getKeyCode() == KeyEvent.VK_RIGHT && xscreen <= 3725){
            xscreen += 25;
        }
        drawStuff();
    }
    public void keyPressed(KeyEvent e) {
    }
    public void keyReleased(KeyEvent e) {
    }

    BackgroundImage image = new BackgroundImage();
    private int xres;
    private int yres;
    private int xscreen;
    private int yscreen;

	public static void main(String[] args) {
		new ImagePanningTest(800, 600);
	}

	public ImagePanningTest(int x, int y) {
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setUndecorated(true);
                this.setFocusable(true);
		this.setSize(x, y);
                this.xres    = x;
                this.yres    = y;
                this.xscreen = 0;
                this.yscreen = 0;
		this.setVisible(true);
                this.addKeyListener(this);
                this.requestFocus();

		this.createBufferStrategy(2);
                mainLoop();
	}

	private void mainLoop() {
		drawStuff();
	}

	private void drawStuff() {
        BufferStrategy buffer = this.getBufferStrategy();
        Graphics backimage = null;

        try {
            backimage = buffer.getDrawGraphics();
            image.draw(backimage, xscreen, yscreen, xres, yres);
    	}
        finally {
        backimage.dispose();
        }

        buffer.show();
        Toolkit.getDefaultToolkit().sync();
	}

}
The Image Class

code:
package zombiepicknick;

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;

public class BackgroundImage {

    private BufferedImage grid;
    private BufferedImage background;

    public BackgroundImage() {
        try {
            grid = ImageIO.read (new File("Grid03.png"));
        }
        catch (IOException e) {
        }

        try {
            background = ImageIO.read (new File("Background.png"));
        }
        catch (IOException e) {
        }
    }

    public void draw (Graphics image, int x, int y, int xres, int yres) {
        image.drawImage(background, 0, 0, xres, yres,
                                   x, y, x+xres, y+yres, null);
        for (int i = 0; i <= xres-25; i+=25)
            for (int j = 0; j <= yres-25; j+=25)
                image.drawImage(grid, i, j, null);
    }
}

Mill Town
Apr 17, 2006

OK, I ran your code on my system, and... it just worked. Well, except for the keypress handling. In the Java spec, the keycode of a key even is only meaningful for KEY_PRESSED and KEY_RELEASED events, not KEY_TYPED. On my system, every time I pressed a key, getKeyCode returned VK_UNDEFINED.

You should probably move that logic to keyPressed() rather than keyTyped. It works perfectly there. You can also catch the up and down arrow keys instead of using 0 and 1!

Now, since the code seems to run fine, maybe there's something about the specific image you are using that causes the problem. Can you post your images please?

Edit: I ran java with the -verbose:gc option to see if there were any memory leaks, and it doesn't look like it. Memory usage stayed around 55M as I panned around the image. If your image is sufficiently large, though, you might be running out of heap. Try running java with the -Xmx128M or even -Xmx256M option to give yourself more heap. Don't forget to put the options before the class name in the command line or they will be interpreted as arguments to main!

Mill Town fucked around with this message at 16:16 on Mar 29, 2009

Twernmilt
Nov 11, 2005
No damn cat and no damn cradle.
Yea, I meant for that all to be key presses. It works when I increase my heap to 256. The image is just over 5mb, which I know is large, but that's why I'm only drawing small sections of it to the buffer. My plan was to have it load the image one time, when BackgroundImage is instantiated, and then have a much smaller buffer image rendered. It feels like the way I'm going about this is clunky, is there a more elegant way to pan over large images? I thought about breaking it up into pieces and only loading the ones I need, but that seems overly complicated.

Mill Town
Apr 17, 2006

Twernmilt posted:

Yea, I meant for that all to be key presses. It works when I increase my heap to 256. The image is just over 5mb, which I know is large, but that's why I'm only drawing small sections of it to the buffer. My plan was to have it load the image one time, when BackgroundImage is instantiated, and then have a much smaller buffer image rendered. It feels like the way I'm going about this is clunky, is there a more elegant way to pan over large images? I thought about breaking it up into pieces and only loading the ones I need, but that seems overly complicated.

I'm certainly not aware of a good, clean way to do it. From reading your code, it looks like your image is 3750 pixels per side, which is about 40 MB when uncompressed (53 MB if you have an alpha channel). I think you're just going to have to live with it.

ayb
Sep 12, 2003
Kills Drifters for erections
Since my work computer doesn't have the jdk on it and I can't install any software, is there anywhere on the web I can go to see the output of my code? I found a compiler that tells me if there are any errors then gives me the .class file but I need to see the results. It's all pretty basic and should only have 5-6 lines out output.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
You might have Java installed, even if you don't have the JDK. Try dropping to a command line and running java.

ayb
Sep 12, 2003
Kills Drifters for erections

rjmccall posted:

You might have Java installed, even if you don't have the JDK. Try dropping to a command line and running java.

I tried and it gave me a whole host of errors.

Exception in thread "main" java.lang.NoClassDefFoundError: Lab11a_me
cause by: java.lang.ClassNotFoundException: Lab1a_me
at java.net.URLClassLoader$1.run(Unknown Source)

and so on for a few more lines

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

ayb posted:

I tried and it gave me a whole host of errors.

Exception in thread "main" java.lang.NoClassDefFoundError: Lab11a_me
cause by: java.lang.ClassNotFoundException: Lab1a_me
at java.net.URLClassLoader$1.run(Unknown Source)

and so on for a few more lines

Have you never run Java before? Try java -cp . Lab11a_me or something.

csammis
Aug 26, 2003

Mental Institution

ayb posted:

I tried and it gave me a whole host of errors.

Exception in thread "main" java.lang.NoClassDefFoundError: Lab11a_me
cause by: java.lang.ClassNotFoundException: Lab1a_me
at java.net.URLClassLoader$1.run(Unknown Source)

and so on for a few more lines

This means there's either something wrong with your code or with the command line you're using to run it. Post both.

ayb
Sep 12, 2003
Kills Drifters for erections
My mistake guys, I had my .java file in the proper folder but never copied the the .class file in there. Code ran fine after I did that and boy do I feel dumb!

ymgve
Jan 2, 2004


:dukedog:
Offensive Clock
What's a good way to profile my code? I'm using the hprof module now, and it works, but slows down my code by about 100x or something.

Anyway, here's a snippet of output from hprof:
code:
rank   self  accum   count trace method
   1  8.47%  8.47%  309532 303963 LocalSearch.minConnectingEdgeWeight
   2  5.06% 13.53%     590 303871 LocalSearch.weightExtensionSparseSet
   3  4.31% 17.84%  140894 303870 LocalSearch.addTree
   4  4.06% 21.90%  736184 303958 java.util.AbstractList$Itr.next
   5  3.80% 25.71%  202628 303819 util.Graph.addEdge
   6  3.78% 29.49% 1050916 303957 java.util.AbstractList$Itr.hasNext
   7  3.04% 32.54%  405256 303804 util.Graph.addVertex
   8  2.80% 35.34%  746645 303947 java.util.ArrayList.get
   9  1.97% 37.30%   57760 303983 util.ClusterHelper.joinClusters
  10  1.76% 39.07% 1064884 303944 java.util.ArrayList.size
  11  1.63% 40.69%  447182 303865 java.util.AbstractList$Itr.hasNext
  12  1.62% 42.32%  406436 303799 util.SparseMap.put
  13  1.60% 43.92%  294038 303866 java.util.AbstractList$Itr.next
  14  1.51% 45.43%  746645 303946 java.util.AbstractList$Itr.checkForComodification
  15  1.51% 46.94%  405256 303816 java.util.ArrayList.add
  16  1.48% 48.42%  855654 303795 util.SparseMap.containsKey
  17  1.44% 49.86%  405256 303814 util.SparseMap.get
  18  1.24% 51.11%  375182 303639 util.Edge.compareTo
Does the 5.06% of LocalSearch.weightExtensionSparseSet include the time of all method calls done from weightExtensionSparseSet, or is it just for time spent inside that exact method?

kloa
Feb 14, 2007


Not a coding question, but are the first few links still relevant to learning Java? I'm taking a Programming in Java course this Fall and wouldn't mind getting a head start by learning over the summer before the course begins.

http://math.hws.edu/javanotes/ is the main site I was wondering whether or not was still up to date with 2009, (technology evolves pretty quick) so I just wanted to make sure this site would benefit me before I began reading it.

Adbot
ADBOT LOVES YOU

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE

kloa posted:

Not a coding question, but are the first few links still relevant to learning Java? I'm taking a Programming in Java course this Fall and wouldn't mind getting a head start by learning over the summer before the course begins.

http://math.hws.edu/javanotes/ is the main site I was wondering whether or not was still up to date with 2009, (technology evolves pretty quick) so I just wanted to make sure this site would benefit me before I began reading it.

Unless your class will be using the betas for Java 7 it looks like it'll cover just about everything you'll need to worry about. Java 6 added in annotations and a few other features that you probably won't run into in your intro to Java course.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply