QueryTest2public class QueryTest2 extends JPanel Provide a user interface to enter artist names and see their tracks. |
Fields Summary |
---|
JList | list | DefaultListModel | model | private static SessionFactory | sessionFactory |
Constructors Summary |
---|
public QueryTest2()Build the panel containing UI elements
setLayout(new BorderLayout());
model = new DefaultListModel();
list = new JList(model);
add(new JScrollPane(list), BorderLayout.SOUTH);
final JTextField artistField = new JTextField(30);
artistField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateTracks(artistField.getText());
}
});
}
});
add(artistField, BorderLayout.EAST);
add(new JLabel("Artist: "), BorderLayout.WEST);
|
Methods Summary |
---|
public static void | main(java.lang.String[] args)Set up Hibernate, then build and display the user interface.
// Load configuration properties, read mappings for persistent classes.
Configuration config = new Configuration();
config.addClass(Track.class).addClass(Artist.class);
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
// Set up the UI
JFrame frame = new JFrame("Artist Track Lookup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new QueryTest2());
frame.setSize(400, 180);
frame.setVisible(true);
| private void | updateTracks(java.lang.String name)Update the list to contain the tracks associated with an artist
model.removeAllElements(); // Clear out previous tracks
if (name.length() < 1) return; // Nothing to do
try {
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
try {
Artist artist = CreateTest.getArtist(name, false, session);
if (artist == null) { // Unknown artist
model.addElement("Artist not found");
return;
}
// List the tracks associated with the artist
for (Iterator iter = artist.getTracks().iterator() ;
iter.hasNext() ; ) {
Track aTrack = (Track)iter.next();
model.addElement("Track: \"" + aTrack.getTitle() +
"\", " + aTrack.getPlayTime());
}
} finally {
// No matter what, close the session
session.close();
}
} catch (Exception e) {
System.err.println("Problem updating tracks:" + e);
e.printStackTrace();
}
|
|