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
tef
May 30, 2004

-> some l-system crap ->
Reminds me of my favourite eclipse bug: Only on windows! https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514

Adbot
ADBOT LOVES YOU

lamentable dustman
Apr 13, 2007

🏆🏆🏆

tef posted:

Reminds me of my favourite eclipse bug: Only on windows! https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514

I ran into that when upgrading to u21 too, ended up fixing it with a shortcut argument. Really dumb.

Other then that eclipse is pretty stable. Mine stays open for weeks at a time usually till I restart the pc.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

tef posted:

Reminds me of my favourite eclipse bug: Only on windows! https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514

Sorry tef, but the best bug is the one where the forward Delete key stops working in Eclipse after the machine has been up for about 3 weeks, only on OS X: https://bugs.eclipse.org/bugs/show_bug.cgi?id=283415 :psyduck:

Mr. DNA
Aug 9, 2004

Megatronics?

tef posted:

... or writing a web app in one of the myriad frameworks (i'd recommend python+django fwiw).

You know, what I'm planning to eventually create would work well as a web app anyway. It's going to be a few simple learning tools for some of my Electrical Tech. students. I'll look into this option.

Thanks everyone! At the very least, I can now write simple code in Java too...

ZeeToo
Feb 20, 2008

I'm a kitty!
Probably hilariously dumb question, but I've stumped myself on it:


I'm trying to get a Java program where I put up a JFrame with a button, then start a timer. If the button isn't clicked within a short time, the program moves on. I can't seem to get this to happen; I can run a timer before or after the JFrame, but not during.

How do I set up a button where other things happen while listening for a click? Even better if I can interrupt on a click, but I don't need that nearly as much.

taint toucher
Sep 23, 2004


ZeeToo posted:

Probably hilariously dumb question, but I've stumped myself on it:


I'm trying to get a Java program where I put up a JFrame with a button, then start a timer. If the button isn't clicked within a short time, the program moves on. I can't seem to get this to happen; I can run a timer before or after the JFrame, but not during.

How do I set up a button where other things happen while listening for a click? Even better if I can interrupt on a click, but I don't need that nearly as much.

What is happening in the JFrame when you start the timer? Can you post some code because it's really difficult to know what is happening by your description.

ZeeToo
Feb 20, 2008

I'm a kitty!

Action Jackson! posted:

What is happening in the JFrame when you start the timer? Can you post some code because it's really difficult to know what is happening by your description.

Sorry, I thought that that would be enough. I copied an example out of a book and tried to adapt it as proof-of concept.

Build2 sets up a pretty ugly, basic menu system. When you press one of the buttons, it spits the counter onto the screen.

What's missing, because nowhere I tried to put it works and so I didn't see a reason to clutter this up further by leaving it in, was a do-while or the like with a counter++ line in it; the idea was just to have that running so I could see when I hit the button how long it had been running.

What I was trying to do was find where in here it would be waiting for a click, and have some sort of timer or counter running (hence the counter variable that doesn't seem to be used). That doesn't seem to be how it works, so I'm asking for help.

code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Build2 extends JFrame implements ActionListener
{
	public static final int WIDTH = 800;
	public static final int HEIGHT = 600;
	public int counter = 0;
	public JButton helloButton;


	private JTextField message;

	public Build2()
	{

			setSize(WIDTH, HEIGHT);
			setTitle("Icon Demonstration");
			Container content = getContentPane();
			content.setBackground(Color.white);
			content.setLayout(new BorderLayout());

			JLabel niceLabel = new JLabel("Nice day!");
			content.add(niceLabel, BorderLayout.NORTH);

			JPanel buttonPanel = new JPanel();
			buttonPanel.setLayout(new FlowLayout());
			helloButton = new JButton("Hello");
			ImageIcon dukeWavingIcon = new ImageIcon("test/a1.gif");
			helloButton.setIcon(dukeWavingIcon);
			helloButton.addActionListener(this);
			buttonPanel.add(helloButton);
			JButton byeButton = new JButton("Good bye");
			ImageIcon dukeStandingIcon = new ImageIcon("test/a2.gif");
			byeButton.setIcon(dukeStandingIcon);
			byeButton.addActionListener(this);
			buttonPanel.add(byeButton);
			content.add(buttonPanel, BorderLayout.SOUTH);

			message = new JTextField(30);
			content.add(message, BorderLayout.CENTER);


	}

	public void actionPerformed(ActionEvent e)
	{
		message.setText("Count is: "+counter);
	}


	public static void main(String[] args)
	{
		Build2 iconGUI = new Build2();
		iconGUI.setVisible(true);
	}
}

Chairman Steve
Mar 9, 2007
Whiter than sour cream
You can't use a while() { } loop because it's going to run on the same thread as the display, so it's going to block any ability for the Swing code to do anything until the while() { } loop breaks (inclusively, it will block your ability to interact with the JFrame).

You may want to look into implementing a TimerTask[1] object that closes the JFrame and kick it off using Timer[2]. When the user clicks the button, just use the TimerTask object's cancel() method.

I'd recommend using a class-level boolean to indicate whether or not the TimerTask has been cancelled. cancel() sets the boolean to true and the run() method will check that boolean before trying to execute. Because it's a multi-threaded application, I would recommend synchronizing around a lock object. If you're on Java 5 or greater, you can probably use a ReentrantLock object[3], or just declare a class-level Object and use it in a synchronized() { } object.

1. http://download.oracle.com/javase/1.4.2/docs/api/java/util/TimerTask.html
2. http://download.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html#schedule(java.util.TimerTask, long)
3. http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html

ZeeToo
Feb 20, 2008

I'm a kitty!
I figured I couldn't use it, but I didn't know why. That looks like exactly what I needed; thank you!

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
try-catch-finally is confusing me.

So I have all this crap (some crap removed because it's irrelevant):

code:
public String getValueFromCategory(final String category, final String value) {
	if (!report.exists() || !report.canRead()) // global File
		return null;
	try {
		final BufferedReader br = new BufferedReader(new FileInputStream(report));
		String line;
		while ((line = br.readLine()) != null) {
		// do a bunch of poo poo
			if (itAllWorked) {
				br.close();
				return line;
			}
		}
	br.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
Among the many things wrong with this code, apparently a finally block would fix code duplication, namely the br.close() I have twice and need two more times.

But
1) br is outside the scope of a finally block.
2) br's new FileInputStream() throws an exception, so if I move it outside the scope I need to put in a new try-catch block... and then that's outside the scope of a finally block.

Help :psyduck:
Commenting that my code is terrible is acceptable.
Or link me to a good guide on try-catch-finally, thanks

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
It's a stylistic pain in the rear end, basically:
code:
BufferedReader br = null;
try{
  br = ...
  ...
}finally{
  if (br != null) br.close();
}

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
It's even worse when you want to declare an instance variable as final but its constructor can throw an exception. :(

epswing
Nov 4, 2003

Soiled Meat
It's even worse when close() can throw an exception. :(

So you have a try/catch/finally in your finally.

I'm sure there's an xhibit joke I could be making here.

Edit: I heard you like to close resources, so I put a try/catch/finally in your try/catch/finally so you can close resources while you close resources?

epswing fucked around with this message at 17:02 on Nov 8, 2010

Fly
Nov 3, 2002

moral compass

Internet Janitor posted:

It's even worse when you want to declare an instance variable as final but its constructor can throw an exception. :(
If the constructor throws an exception, you don't have to close it though. Very often you can get away with this, but you'll have to catch the exception from the constructor somewhere else.
code:
final Closable c = new McStreamy();
try {
    // stuff.
    int i = c.read();
    // stuff.
}
catch (StreamException sex) {
    // clean up.
    //throw new RuntimException("I don't know what to do!", sex);
}
finally {
    c.close();
}

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Or just use this method: http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.Closeable)

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
or just use this

code:
private void close(final Closeable... closeables) {
	for (final Closeable closeable : closeables)
		if (closeable != null)
			try {
				closeable.close();
			} catch (IOException e) {
			}
}
so you can just do close(a, b, c);

(everything must be final!!)

Pivo
Aug 20, 2004


Guys, please help me out. Why is the "America/Anchorage" timezone returning an offset of -10 hours from GMT? It's -9 usually, -8 in DST. It is never -10.

code:
import java.util.Calendar;
import java.util.TimeZone;
public class TestingMain {
	public static void main(String[] args) {
		Calendar c = Calendar.getInstance();
		c.setTimeZone(TimeZone.getTimeZone("America/Anchorage"));
		
		// Jan 1 1970, 15:00:00:0000
		c.set(1970, 0, 1, 15, 0, 0);
		c.set(Calendar.MILLISECOND, 0);
		
		// print offset in hours
		// should print: -9.0
		// prints: -10.0
		System.out.println(c.get(Calendar.ZONE_OFFSET) / (3600.00 * 1000.0));
		
		// maybe because of DST oddities?
		System.out.println(c.get(Calendar.DST_OFFSET));
		// prints 0
	}

}

baquerd
Jul 2, 2007

by FactsAreUseless

Pivo posted:

Guys, please help me out. Why is the "America/Anchorage" timezone returning an offset of -10 hours from GMT? It's -9 usually, -8 in DST. It is never -10.

Looks like a straightforward bug. It also doesn't recognize "AKDT" or "AKST" at all. Historically, wikia tells us that some of the state is still in -10 and a large portion of the state used to be.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Pivo posted:

Guys, please help me out. Why is the "America/Anchorage" timezone returning an offset of -10 hours from GMT? It's -9 usually, -8 in DST. It is never -10.

Are you running the absolute latest dot-release of the JRE? The time zone stuff does get updated from time to time in those.

HKBGUTT
May 7, 2009


Ok, so i have just started learning java and wanted to make a app that uses swing to create a GUI interface. Anyway I encountered a problem with it that I can't really figure out.

So first here's the interface:


What the buttons does:
Legg til: Allow you to add a triangle to a array.(Max 5)
Areal: Calculates area for a given array.
Roter: Rotates a triangle.
Vis Data: Show's data.
Avslutt: Exit's the program.

The radiobuttons allows you to select a given triangle and draws it like this:


The problem:
Well the problem occurs when i follow these steps:
1.Draws a triangle by selecting its radiobutton.
2.Select the Show data or Area button.
3.Selects a new triangle from a radiobutton.

Now I have to press the Show data or Area button twice before they will display data, the first time I select a triangle and then selects the show data/area buttons everything is fine.

Anybody know what is causing this and how to prevent it?
Here is the code for the Area button(Identical to the Show data button):
code:
arealKnapp.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent h){
	//beregn areal
	hentPanel().remove(hentTegning()); //Removes the drawing
	hentPanel().add(hentTekst(test2.skrivAreal())); //Adds text.
	pack();
     }
});

public JPanel hentPanel(){
	return panel2;// panel 2 is the big white area
}
Code for the class that draws the triangles:
code:
	private Graphics2D g2;

	public Tegning(){
	}
// Tegning her
	public void paint(Graphics g){
		g2 = (Graphics2D) g;
		Polygon poly = new Polygon();
		super.paintComponent(g2);
		poly.addPoint(0, sider);
		poly.addPoint(sider, 0);
		poly.addPoint(sider, sider);
		if(juster.equals("HN")){
			poly.translate(50, 5);
		}
		else if(juster.equals("VN")){
			roter();
		}
		else if(juster.equals("VU")){
			roter();
			roter();
			g2.translate(-(sider/7.5),(sider/8));
		}
		else if(juster.equals("HU")){
			roter();
			roter();
			roter();
			g2.translate((sider/7.5),90);
		}
		g2.draw(poly);
	}
Code for one of the radiobuttons:
code:
nr4.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent h){
	hentPanel().remove(hentTekst()); //Removes text
	int temp = test2.hentSide(3);    // Set the triangle size.
	String temp2 = test2.hentJust(3);
	tegn1.settSider(temp);  
	tegn1.settJustering(temp2);
	panel2.add(tegn1);   //Adds the drawing to panel2
	tegn1.renderShape(); //Calls repaint();
	pack();
	}
});
If I remove super.paintComponent(g2); from the paint method the screen looks like this when the problem occours:


If you have any questions don't hesitate to ask!

HKBGUTT fucked around with this message at 22:15 on Nov 9, 2010

Pivo
Aug 20, 2004


Flobbster posted:

Are you running the absolute latest dot-release of the JRE? The time zone stuff does get updated from time to time in those.

Yep. The problem was, in my web application, I need to store a time in a MySQL TIME column.

To generate the time to store in that column, I create a Calendar object, set it to Jan 1 1970, set the HOUR_OF_DAY/MINUTE/SECOND to the appropriate time, and then write the timeToMillis() value to the database. This works for all cases EXCEPT where the time zone has changed. In 1970 America/Anchorage was GMT-10, nowadays it is GMT-09.

I fixed the issue by using today's date, but in case DST is active, setting DST_OFFSET to 0. We need to store the time in the database to be DST-agnostic, since we apply DST after-the-fact (since the column stores a TIME it does not refer to a specific date and would not make sense to be stored adjusted for DST at the time it was recorded)

Time zone sensitive code sucks so much. Now I need to comb through all my code that uses that table to make sure it doesn't make the Jan 1 1970 assumption.

Everything worked for time zones that don't change! Why did those drat Alaskans have to screw with my poo poo :)

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I think the solution to that is to store it as a timestamp which MySQL stores internally as the number of miliseconds since Jan 1, 1970. Then when you ask it for the time it will return it untouched, and in your Java program you can apply the correct offset.

Pivo
Aug 20, 2004


MEAT TREAT posted:

I think the solution to that is to store it as a timestamp which MySQL stores internally as the number of miliseconds since Jan 1, 1970. Then when you ask it for the time it will return it untouched, and in your Java program you can apply the correct offset.

When I designed this feature, I was thinking about data integrity/correctness. If we store a timestamp in MySQL, there is an implied year/month/date there. This is incorrect, we are storing a time of day e.g. 5:00 PM. We later use this time and extrapolate it to multiple dates, e.g. this action occurs every Tuesday from this day on at 5:00PM.

So storing any implied date in the database is incorrect in this case. As a hack it can be done but I don't like it.

Using Jan 1 1970 as the date when working with Calendar was a hack in itself but it worked. I guess it was foolish of me to assume no timezones have changed in the past 40 years.

Pivo fucked around with this message at 00:33 on Nov 10, 2010

Outlaw Programmer
Jan 1, 2008
Will Code For Food

Aleksei Vasiliev posted:

or just use this

code:
private void close(final Closeable... closeables) {
	for (final Closeable closeable : closeables)
		if (closeable != null)
			try {
				closeable.close();
			} catch (IOException e) {
			}
}
so you can just do close(a, b, c);

(everything must be final!!)

Why does everything need to be final here?

Pivo posted:


When I designed this feature, I was thinking about data integrity/correctness. If we store a timestamp in MySQL, there is an implied year/month/date there. This is incorrect, we are storing a time of day e.g. 5:00 PM. We later use this time and extrapolate it to multiple dates, e.g. this action occurs every Tuesday from this day on at 5:00PM.

So storing any implied date in the database is incorrect in this case. As a hack it can be done but I don't like it.


Why bother shoehorning what you want into Timestamp or Date objects at all? Why not store it as a number representing milliseconds past midnight? The Java Date/Time APIs are pretty deficient here because, as you noticed, they force everything to be a Date; you can't just have a timespan or HH:mm:ss.

Once you have millis past midnight, you can construct a Date or Calendar that represents whatever day you want at midnight in your desired timezone. Then just add the millis past midnight.

Fly
Nov 3, 2002

moral compass

Outlaw Programmer posted:

Why does everything need to be final here?
Because non-final variables add to code complexity and functional-style programming is great. [/seriouspost] In Java final allows one to write simple closures with anonymous classes, for example.

Pivo
Aug 20, 2004


Outlaw Programmer posted:

Why bother shoehorning what you want into Timestamp or Date objects at all? Why not store it as a number representing milliseconds past midnight? The Java Date/Time APIs are pretty deficient here because, as you noticed, they force everything to be a Date; you can't just have a timespan or HH:mm:ss.

Once you have millis past midnight, you can construct a Date or Calendar that represents whatever day you want at midnight in your desired timezone. Then just add the millis past midnight.

That's pretty much what I'm doing. SQL TIME column is millis past midnight, or at least JDBC gives you an object that returns millis past midnight.

The only issue with this is that the millis past midnight have to be normalized to the same timezone before being inserted into the database, which is what I was doing with my Jan 1 1970 Calendar object.

From an architectural point of view I probably screwed the pooch there, I should have just stored the time in the input timezone, but I have to live with the decision that for example if you give me 3PM Alaskan time, it's gotta be stored in the database as 7PM Eastern time.

Pivo fucked around with this message at 10:03 on Nov 10, 2010

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slgt skal flge slgters gang



I need to parse a document that has the following structure:

code:
<students>
	<name>John Doe</name>
	<enrolled>2010-01-01</enrolled>
	<gender>male</gender>
	<name>Jane Doe</name>
	<enrolled>2010-01-01</enrolled>
	<gender>female</gender>
</students>
Since that is kindof a dumb layout (I'd have preferred if they weren't sequential but encapsulated in their own <student> elements), I'm having trouble parsing it. I'm trying to do something similar to this, which won't work, since it operates on Nodes and not Elements:

code:
	Student student = null;
	Node node = studentsRoot.getFirstChild();
	while (node != null) {
		String name = node.getNodeName();
		String value = node.getNodeValue();
		if (name.equals("name")) {
			//we're now at a new student, so process that one and start a new one.
			if (student != null) {
				process(student);
			}
			student = new Student();
			student.setName(value);
		} else if (name.equals("enrolled")) {
			student.setEnrolledDate(value);
		} else if (name.equals("gender")) {
			student.setGender(value);
		} else {
			throw new RuntimeException("Unknown node in students -- "+name+": "+value);
		}
		node = node.getNextSibling();
	}
But I can't find any methods on Element for iterating sequentially on them like this?

aleph1
Apr 16, 2004

Carthag posted:

But I can't find any methods on Element for iterating sequentially on them like this?

Element is a subclass of Node, so your code should work just fine?

Edit: the reason your code is not working is because you can't get the text contained in an element by calling getNodeValue() on it - that always returns null.
The text you want is in the child of that element node as a text node, so what you want to do instead is:
code:
String value = node.getFirstChild().getNodeValue();
(and possibly check that the child actually exists and is of Node.TEXT_NODE type)

aleph1 fucked around with this message at 17:45 on Nov 10, 2010

oRenj9
Aug 3, 2004

Who loves oRenj soda?!?
College Slice
I'm having a problem with type erasure on two of our Intel Macs that isn't occurring on any other machines, Linux or Windows. Somebody checked in some code that looks about like this:

php:
<?
class User {
  public static int updateUser(final List<Product> products, final Connection conn) 
  {...}

[...]

  public static void updateUser(final List<Organizations> orgs, final Connection conn)
  {...}
}
?>
For some reason, that code compiles on every machine except for the two Macs running OSX. Everyone is using Java 1.6 and Eclipse is configured identically on every machine.

Here's the Java version from the OSX machine:
code:
java -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)
Here's the Java version from my Ubuntu machine:
code:
java -version
java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.2) (6b18-1.8.2-4ubuntu2)
OpenJDK 64-Bit Server VM (build 16.0-b13, mixed mode)
Any ideas as to why this doesn't work on the Mac?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

oRenj9 posted:

I'm having a problem with type erasure on two of our Intel Macs that isn't occurring on any other machines, Linux or Windows. Somebody checked in some code that looks about like this:

php:
<?
class User {
  public static int updateUser(final List<Product> products, final Connection conn) 
  {...}

[...]

  public static void updateUser(final List<Organizations> orgs, final Connection conn)
  {...}
}
?>
For some reason, that code compiles on every machine except for the two Macs running OSX. Everyone is using Java 1.6 and Eclipse is configured identically on every machine.

Here's the Java version from the OSX machine:
code:
java -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)
Here's the Java version from my Ubuntu machine:
code:
java -version
java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.2) (6b18-1.8.2-4ubuntu2)
OpenJDK 64-Bit Server VM (build 16.0-b13, mixed mode)
Any ideas as to why this doesn't work on the Mac?
I think the OpenJDK is wrong in this case. I just downloaded the jdk from Oracle on Windows and it does the same thing as the Mac.

Diametunim
Oct 26, 2010
I'm in need of a little java help for school. We're currently working on Programming Othello/Reversi whatever the gently caress you choose to call it by using recursion. Now I've gotten mine to work for the most part however the left column and bottom row aren't playable because my recursion decides to check out of bounds and eclipse returns an error. I haven't for the life of me a clue on how to fix it.

My other problem is that we're required to have some form of A.I to play against. It doesn't have to be smart but I haven't a clue on how to program any form of A.I and our teacher for the class didn't teach us how to do it either. So I'm coming to the goons for help.

Anyways, Here's my recursion for checking to the left it works for every column besides the last one.

Obuttons being the name for my game board array, everything else should be somewhat self explanatory?

code:
if(Obuttons[clicked.getColumn()-1][clicked.getRow()].getIcon()==different)
					{
						System.out.println("THERE ARE DROIDS TO THE LEFT PEWPEWPEW");
						if(cLeft(Obuttons[clicked.getColumn()-1][clicked.getRow()]))
						{
							System.out.println("You sir, have a valid move to the left");
							fLeft(Obuttons[clicked.getColumn()][clicked.getRow()]);
							Turn = 1;
							whoisturn.setText("Turn: Droid");
							whoisturn.setBorder(null);
						}
					}
Here is my recursion for checking down
code:
					if(Obuttons[clicked.getColumn()][clicked.getRow()+1].getIcon()==different)
					{
						System.out.println("DROIDS BELOW YOU! OMGOMGOMG");
						if(cDown(Obuttons[clicked.getColumn()][clicked.getRow()+1]))
						{
							fDown(Obuttons[clicked.getColumn()][clicked.getRow()]);
							System.out.println("You sir, have a valid move below you, or something like that.");
							Turn = 1;
							whoisturn.setText("Turn: Droid");
							whoisturn.setBorder(null);
						}
					}
and lastly here is the error thrown to me by eclipse if you click on the last left column or the very bottom row.
code:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
	at Othello.mouseClicked(Othello.java:166)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)
If you need to see some other part of my code let me know and I'll paste it up.

Contra Duck
Nov 4, 2004

#1 DAD

oRenj9 posted:

I'm having a problem with type erasure on two of our Intel Macs that isn't occurring on any other machines, Linux or Windows. Somebody checked in some code that looks about like this:

php:
<?
class User {
  public static int updateUser(final List<Product> products, final Connection conn) 
  {...}

[...]

  public static void updateUser(final List<Organizations> orgs, final Connection conn)
  {...}
}
?>
For some reason, that code compiles on every machine except for the two Macs running OSX. Everyone is using Java 1.6 and Eclipse is configured identically on every machine.

Here's the Java version from the OSX machine:
code:
java -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)
Here's the Java version from my Ubuntu machine:
code:
java -version
java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.2) (6b18-1.8.2-4ubuntu2)
OpenJDK 64-Bit Server VM (build 16.0-b13, mixed mode)
Any ideas as to why this doesn't work on the Mac?

That shouldn't compile. Generics are only checked at compile time and are then discarded so the bytecode produced actually looks like this:

code:
class User {
  public static int updateUser(final List products, final Connection conn) 
  {...}

[...]

  public static void updateUser(final List orgs, final Connection conn)
  {...}
}
And since you can't have two methods with the name and parameters, the compiler should fail.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
So I'm trying to write my first Swing app and I'm a bit confused on how I switch between panels and how they are supposed to talk to each other.

code:
public class Main {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Whatever");
        
        FirstPanel firstPanel = new FirstPanel();
        frame.getContentPane().add(firstPanel);
        frame.setVisible(true);
    }
    public static void main (String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
So lets say FirstPanel implements ActionListener. Lets say FirstPanel has a button on it, and when I click it I want to stop displaying FirstPanel and display SecondPanel. What's the right way to do that? How about if I wanted to use some input from FistPanel on SecondPanel?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Contra Duck posted:

And since you can't have two methods with the name and parameters, the compiler should fail.

While this is indeed a restriction on the Java language which OpenJDK's compiler apparently doesn't enforce correctly after type erasure, the JVM itself allows overloading based on the return type, which is presumably why the erased code loads and runs.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slgt skal flge slgters gang



aleph1 posted:

Element is a subclass of Node, so your code should work just fine?

Edit: the reason your code is not working is because you can't get the text contained in an element by calling getNodeValue() on it - that always returns null.
The text you want is in the child of that element node as a text node, so what you want to do instead is:
code:
String value = node.getFirstChild().getNodeValue();
(and possibly check that the child actually exists and is of Node.TEXT_NODE type)

poo poo, of course. This works:

code:
	Student student = null;
	Node node = studentsRoot.getFirstChild();
	while (node != null) {
		String name = node.getNodeName();
		if (name.equals("#text")) {
			node = node.getNextSibling();
			continue;
		}
		String value = node.getFirstChild().getNodeValue();
		if (name.equals("name")) {
			//we're now at a new student, so process that one and start a new one.
			if (student != null) {
			//etc...
Thanks :)

_aaron
Jul 24, 2007
The underscore is silent.

Diametunim posted:

(...Othello stuff...)
I'm not sure what your fleft method does, but you pass the value at the actual clicked row and column to that method, but when you do if check for different, you're using the column - 1 (or the row + 1). I'm obviously not familiar with the rest of your code, but my guess is that clicking the far left column gives you a column value of 0; when you subtract 1 from this, you get -1, and that's not a valid array index, hence your exception. Same thing for the bottom row - adding 1 will put you outside the bounds of the array.

If that's not correct, I'd need to see some more code.

Diametunim
Oct 26, 2010

_aaron posted:

I'm not sure what your fleft method does, but you pass the value at the actual clicked row and column to that method, but when you do if check for different, you're using the column - 1 (or the row + 1). I'm obviously not familiar with the rest of your code, but my guess is that clicking the far left column gives you a column value of 0; when you subtract 1 from this, you get -1, and that's not a valid array index, hence your exception. Same thing for the bottom row - adding 1 will put you outside the bounds of the array.

If that's not correct, I'd need to see some more code.
Sorry about that, I posed the wrong method. fleft however flips the pieces when a move is made. I actually solved the problem by throwing in this little line here before each of my check statements
code:
if(clicked.getRow/Column +1/-1 <8) 
Where Row/Column is either the Row or Column depending on what method I was editing and the same goes for the +1/-1 and the <8 just tells the program to stop at the 8th row/column.

I think? I hope I'm explaining that right. But I solved my problem.

Thanks for your help.

Jo
Jan 24, 2005

:allears:
Soiled Meat
I'm running into a problem with input. When doing this, sometimes my player entity will simply stop moving for reasons I can't explain. It didn't seem to happen with any other style of input polling. Are there any glaring logic errors here?

code:
public void keyPressed( java.awt.event.KeyEvent e ) {
		switch( e.getKeyCode() ) {
			case KeyEvent.VK_ESCAPE:
				engine.done = true;
				break;
			case KeyEvent.VK_D:
				directionQueue.push( Entity.DIRECTION_RIGHT );
				break;
			case KeyEvent.VK_W:
				directionQueue.push( Entity.DIRECTION_UP );
				break;
			case KeyEvent.VK_A:
				directionQueue.push( Entity.DIRECTION_LEFT );
				break;
			case KeyEvent.VK_S:
				directionQueue.push( Entity.DIRECTION_DOWN );
				break;
		}

		if( directionQueue.peekFirst() != previousDirection ) { // Ah!  We have a new direction.
			Player p = engine.entityman.getPlayer();
			int newDir = directionQueue.peekFirst();
			previousDirection = newDir;

			p.setOrientation( newDir );
			p.setAcceleration( p.getMaxAcceleration() );
		}
	}

	public void keyReleased( java.awt.event.KeyEvent e ) {
		switch( e.getKeyCode() ) {
			case KeyEvent.VK_D:
				directionQueue.remove( (Integer)Entity.DIRECTION_RIGHT );
				//directionQueue.remove( directionQueue.indexOf( Entity.DIRECTION_RIGHT ) );
				break;
			case KeyEvent.VK_W:
				directionQueue.remove( (Integer)Entity.DIRECTION_UP );
				break;
			case KeyEvent.VK_A:
				directionQueue.remove( (Integer)Entity.DIRECTION_LEFT );
				break;
			case KeyEvent.VK_S:
				directionQueue.remove( (Integer)Entity.DIRECTION_DOWN );
				break;
		}

		if( directionQueue.isEmpty() ) {
			Player p = engine.entityman.getPlayer();
			p.setAcceleration( 0 );
			p.setSpeed( 0 );
		} else {
			Player p = engine.entityman.getPlayer();
			int newDir = (Integer)directionQueue.peekFirst();
			previousDirection = newDir;

			p.setOrientation( newDir );
			p.setAcceleration( p.getMaxAcceleration() );
		}
	}

baquerd
Jul 2, 2007

by FactsAreUseless
Either max acceleration is being set to zero or the directionQueue is empty after a key release event from what you've shown here. Is this threaded? What class is directionQueue?

Adbot
ADBOT LOVES YOU

Jo
Jan 24, 2005

:allears:
Soiled Meat

baquerd posted:

Either max acceleration is being set to zero or the directionQueue is empty after a key release event from what you've shown here. Is this threaded? What class is directionQueue?

DirectionQueue is local to the InputMan class. Yes, this is multithreaded. I do not know where acceleration could be changing. Max acceleration is constant.

EDIT:

Whaaa? Added some more print statements:

jo@Euclid:~/source/tilegame/dist$ java -jar Tilegame.jar
KEY DOWN:S
KEY UP:S
KEY DOWN:S
KEY UP:S
...

This is from HOLDING the 's' key. Why would multiple key events be generated from a single key hold?

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