What's Wrong with This Code? Java Swing and Threading - ' Thread Blocking' (
Page 2 of 5 )
: The Code">
Ready to test your coding knowledge?
In this article, I challenge you to examine two Java Swing examples, specifically using threads. Each are wrong, in a subtle but painful way.
ADVERTISEMENT
See if you can identify the problem before I show you the best way to correct the offending code.
Let's start with a thread blocking example.
I created a simple Swing class file. I am sure this is extremely common. On the surface, it looks perfectly acceptable. In this class, I extend from a JFrame and add a simple button to the frame.
Take a look at the code, and see if you can spot the issues:
package com.zarrastudios.example;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameExample1 extends JFrame {
private JButton btnActivate;
public FrameExample1() {
super("Frame Example 1");
initAndLayoutComponents();
initListeners();
pack();
}
private void initListeners() {
btnActivate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//Simulate database access
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void initAndLayoutComponents() {
btnActivate = new JButton("Activate");
JPanel main = new JPanel(new BorderLayout());
JPanel north = new JPanel(new FlowLayout());
JPanel center = new JPanel();
center.setBackground(Color.pink);
north.add(btnActivate);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
setContentPane(main);
}
public static void main(String args[]) {
FrameExample1 fe1 = new FrameExample1();
fe1.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});
fe1.setVisible(true);
}
}
I'll give you the answers on the next page. But before you move forward, do your best to identify the problem.