Thursday, July 16, 2009

Using javax.swing.JDialog




public class MyDiaglog extends JDialog {
private JButton jButton1 = new JButton();
private JTextField jTextField1 = new JTextField();

public MyDiaglog() {
this(null, "", false);
setVisible(true);
}

public MyDiaglog(Frame parent, String title, boolean modal) {
super(parent, title, modal);
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}

private void jbInit() throws Exception {
this.setSize( new Dimension( 400, 300 ) );
this.getContentPane().setLayout( null );
jButton1.setText("jButton1");
jButton1.setBounds(new Rectangle(270, 50, 73, 22));
jTextField1.setBounds(new Rectangle(130, 85, 110, 20));
this.getContentPane().add(jTextField1, null);
this.getContentPane().add(jButton1, null);
jButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jButton1_actionPerformed(e);
}
});
}
private void jButton1_actionPerformed(ActionEvent e)
{
jTextField1.setText("hello");
}
}

using ThreadLocal()


Have you ever needed variables that were local to the scope of a thread, where each thread managed its storage, and it would be impossible for one thread to access the state information of another thread?


import java.util.Random;

public class ThreadLocal1 {

// Define/create thread local variable
static ThreadLocal threadLocal =
new ThreadLocal();
// Create class variable
static volatile int counter = 0;
// For random number generation
static Random random = new Random();

// Displays thread local variable, counter,
// and thread name
private static void displayValues() {
System.out.println (
threadLocal.get() + "\t" + counter +
"\t" + Thread.currentThread().getName());
}

public static void main (String args[]) {

// Each thread increments counter
// Displays variable info
// And sleeps for the random amount of time
// Before displaying info again
Runnable runner = new Runnable() {
public void run() {
synchronized(ThreadLocal1.class) {
counter++;
}
threadLocal.set(
new Integer(random.nextInt(1000)));
displayValues();
try {
Thread.sleep (
((Integer)threadLocal.get()).intValue());
displayValues();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

// Increment counter, access thread local from
// a different thread, and display the values
synchronized(ThreadLocal1.class) {
counter++;
}
threadLocal.set(
new Integer(random.nextInt(1000)));
displayValues();

// Here's where the other threads
// are actually created
for (int i=0; i<5; i++) {
Thread t = new Thread(runner);
t.start();
}
}
}