001.
package
com.java.myapp;
002.
003.
import
java.awt.EventQueue;
004.
import
java.sql.Connection;
005.
import
java.sql.DriverManager;
006.
import
java.sql.ResultSet;
007.
import
java.sql.SQLException;
008.
import
java.sql.Statement;
009.
import
javax.swing.DefaultListModel;
010.
import
javax.swing.JList;
011.
import
javax.swing.JOptionPane;
012.
import
javax.swing.JFrame;
013.
import
javax.swing.JLabel;
014.
import
javax.swing.SwingConstants;
015.
import
javax.swing.JScrollPane;
016.
import
java.awt.event.MouseAdapter;
017.
import
java.awt.event.MouseEvent;
018.
019.
public
class
MyForm
extends
JFrame {
020.
021.
022.
023.
024.
public
static
void
main(String[] args) {
025.
EventQueue.invokeLater(
new
Runnable() {
026.
public
void
run() {
027.
MyForm frame =
new
MyForm();
028.
frame.setVisible(
true
);
029.
}
030.
});
031.
}
032.
033.
034.
035.
036.
public
MyForm() {
037.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
038.
setBounds(
100
,
100
,
409
,
243
);
039.
setTitle(
"ThaiCreate.Com Java GUI Tutorial"
);
040.
getContentPane().setLayout(
null
);
041.
042.
043.
DefaultListModel model =
new
DefaultListModel();
044.
045.
Connection connect = ConnectDB();
046.
Statement s =
null
;
047.
048.
try
{
049.
050.
s = connect.createStatement();
051.
052.
String sql =
"SELECT * FROM customer ORDER BY CustomerID ASC"
;
053.
054.
ResultSet rec = s.executeQuery(sql);
055.
int
row =
0
;
056.
while
((rec!=
null
) && (rec.next()))
057.
{
058.
model.addElement(rec.getString(
"CustomerID"
) +
" - "
+ rec.getString(
"Name"
));
059.
}
060.
061.
rec.close();
062.
063.
}
catch
(Exception e) {
064.
065.
JOptionPane.showMessageDialog(
null
, e.getMessage());
066.
e.printStackTrace();
067.
}
068.
069.
try
{
070.
if
(s !=
null
) {
071.
s.close();
072.
connect.close();
073.
}
074.
}
catch
(SQLException e) {
075.
076.
e.printStackTrace();
077.
}
078.
079.
080.
final
JLabel lblResult =
new
JLabel(
"Result"
);
081.
lblResult.setHorizontalAlignment(SwingConstants.CENTER);
082.
lblResult.setBounds(
62
,
154
,
272
,
14
);
083.
getContentPane().add(lblResult);
084.
085.
086.
JScrollPane scrollPane =
new
JScrollPane();
087.
088.
final
JList list =
new
JList(model);
089.
list.addMouseListener(
new
MouseAdapter() {
090.
public
void
mouseClicked(MouseEvent evt) {
091.
lblResult.setText(list.getSelectedValue().toString());
092.
}
093.
});
094.
095.
scrollPane.setViewportView(list);
096.
scrollPane.setBounds(
113
,
48
,
167
,
67
);
097.
getContentPane().add(scrollPane);
098.
099.
100.
}
101.
102.
103.
private
Connection ConnectDB() {
104.
try
{
105.
Class.forName(
"com.mysql.jdbc.Driver"
);
107.
"?user=root&password=root"
);
108.
}
catch
(ClassNotFoundException e) {
109.
110.
e.printStackTrace();
111.
}
catch
(SQLException e) {
112.
113.
e.printStackTrace();
114.
}
115.
return
null
;
116.
}
117.
118.
119.
120.
121.
}