Home | Links | About

Helpful Java Tips

I have been working a lot with Java the past few months working on my Minesweeper solver. (This is currently the older version; the new version includes new solvers) It is written in Java, so there have been a lot of cool things I have learned because of this project.

Here they are (in no particular order):

Setting the UI to look less Swingy
As much as some might like the default look of the Swing, I do not. It just does not fit with the rest of the windows on my screen. So, there is a really simple way to have the java UI match your operating system!

try
{
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
}
catch(Exception E)
{
System.out.println("Error setting look and feel");
}


Overlaying labels in Swing
I wanted to make two JLabel's stack on each other, while still being able to see both labels. It turns out there is a really easy way to do this using a JLayeredPane!
When you add the JLabel to a panel, just pass the argument JLayeredPane.DEFAULT_LAYER or JLayeredPane.PALETTE_LAYER.

JLayeredPane panel = new JLayeredPane();

JLabel below = new JLabel("I am below");
below.setLocation(0, 0);
panel.add(below, JLayeredPane.DEFAULT_LAYER);

JLabel above = new JLabel("I am above");
cellLabel.setLocation(0, 0);
keyPanel.add(cellLabel, JLayeredPane.PALETTE_LAYER);


The only downside is you have to use absolute positioning, but it works!

Making threads and stopping threads
I also had to work on managing some threads which was completely new to me.

Here is how you can make a thread.


  1. Make sure the class you want to make into a thread implements Runnable

  2. Create a public void run() method of what you want the thread to do when you run it

  3. Now start the thread;

    Thread myThread = new Thread(myClass);
    myThread.run();



And if you want to stop your thread you can call myThread.interrupt();

Although this will not really do to much, since you have to write the code to interrupt the thread yourself!

The way I decided to do this was in my run method.

public void run()
{
try
{
// Code
if(Thread.interrupted())
{
throw new InterruptedException();
}
// Code
}
catch(InterruptedException ex)
{
// We have been interrupted!
}
}


After the you call Thread.interrupted() it will remove the interrupted flag, so you have to handle it right away. You should add these statements throughout your thread and throughout the methods that your thread calls, so it can be interrupted quicker.