Original Post
I was looking over the forum this morning and found a large thread discussing Swing and AWT. It was said that many Swing GUIs tend to be slow because programmers often stick a lot of code in event handlers, and people do their program logic inside the Swing thread. While I'm accquainted with threads, I'm not sure what is meant by the Swing thread, nor am I sure exactly what good practices are for event handlers. Take the following code for example: Does that code display any nasty tendencies I should avoid with regards to threads, event handlers, or anything else? I really would like to create efficient GUIs in Swing. Thanks!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Driver {
private Graphics2D g2;
private JPanel dArea;
int mapWidth, mapHeight, mHiP, mWip;
// etc...
public static void main(String[] args) {
// The following code I found suggested by Sun in a tutorial
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Driver d = new Driver();
d.createGUI();
}
});
}
private void createGUI() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(555,600);
frame.setLocation(50, 50);
frame.setJMenuBar(createMenu());
// set up other GUI components...
frame.setVisible(true);
}
private JMenuBar createMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("A menu");
JMenuItem item = new JMenuItem("A menu option");
// Add event handler to menu option
// is this acceptable? Is this bogging down my GUI?
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do a bunch of logic...
Room.size = Room.size / 2 + 1;
mWiP = Room.size * mapWidth;
mHiP = Room.size * mapHeight;
dArea.setPreferredSize(new Dimension(mWiP, mHiP));
dArea.revalidate();
dArea.update(g2);
dArea.repaint();
}
});
menu.add(item);
menuBar.add(menu);
return menuBar;
}
}