Some tips in Java

You are programming in Java and you want to know some simple but new things? So read this post and maybe you’ll know some new things 🙂 .

The first tip is about the focus. What is a focus? If you have a JTextField and you want to have the cursor automatically activated in it when you open the window, you put a focus. Here is the code :


SwingUtilities.invokeLater(new Runnable()
public void run()




Here the JTextField name is jtf and you have to do this like this if you want to put the pan.setVisible(true); after the focus (for example if you want to put the “visibility” at the end of the code).

Now you have a grid of buttons and you want to know which one is clicked. It’s very simple, you just have to set a name to your buttons :

JButton[][] myGrid = new JButton [10][10];

for(int i = 0; i < myGrid.length; i++ ) {
for(int j = 0; j < myGrid[0].length; j++ ) {
myGrid[i][j] = new JButton();
myGrid[i][j].setName("" + i + j);


Here I put the name with myGrid[i][j].setName("" + i + j); and the name will be 00 for the first button and so on. And now if you want to have the name, you must do this in a listener :

String name = ((JButton) ev.getSource()).getName();

int a = name.charAt(0)-48;
int b = name.charAt(1)-48;

And here you have the name and you can use it as you want.

A last very little tip (it’s pretty sure you already know it), how to unactivate a button. It’s very simple, when you’ve created your button, just put this :


You have to change button with the name of your button.

It’s the end of this post. If you have any question, feel free to ask. Hope it will help you and I’ll try to make an other post about tips in Java.