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.JOptionPane;
010.
import
javax.swing.JFrame;
011.
import
javax.swing.JTable;
012.
import
javax.swing.JScrollPane;
013.
import
javax.swing.table.DefaultTableModel;
014.
015.
public
class
MyForm
extends
JFrame {
016.
017.
018.
019.
020.
public
static
void
main(String[] args) {
021.
EventQueue.invokeLater(
new
Runnable() {
022.
public
void
run() {
023.
MyForm frame =
new
MyForm();
024.
frame.setVisible(
true
);
025.
}
026.
});
027.
}
028.
029.
030.
031.
032.
public
MyForm() {
033.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
034.
setBounds(
100
,
100
,
580
,
242
);
035.
setTitle(
"ThaiCreate.Com Java GUI Tutorial"
);
036.
getContentPane().setLayout(
null
);
037.
038.
039.
JScrollPane scrollPane =
new
JScrollPane();
040.
scrollPane.setBounds(
64
,
44
,
440
,
89
);
041.
getContentPane().add(scrollPane);
042.
043.
044.
JTable table =
new
JTable();
045.
scrollPane.setViewportView(table);
046.
047.
048.
DefaultTableModel model = (DefaultTableModel)table.getModel();
049.
model.addColumn(
"CustomerID"
);
050.
model.addColumn(
"Name"
);
051.
model.addColumn(
"Email"
);
052.
model.addColumn(
"CountryCode"
);
053.
model.addColumn(
"Budget"
);
054.
model.addColumn(
"Used"
);
055.
056.
Connection connect =
null
;
057.
Statement s =
null
;
058.
059.
try
{
060.
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver"
);
061.
connect = DriverManager.getConnection(
""
+
063.
"database=thaicreate-db;"
+
064.
"user=thaicreate_user@bc6hela9fr;password=password@123;"
+
065.
"encrypt=true;hostNameInCertificate=*.database.windows.net;"
+
066.
"loginTimeout=30;"
);
067.
068.
s = connect.createStatement();
069.
070.
String sql =
"SELECT * FROM customer ORDER BY CustomerID ASC"
;
071.
072.
ResultSet rec = s.executeQuery(sql);
073.
int
row =
0
;
074.
while
((rec!=
null
) && (rec.next()))
075.
{
076.
model.addRow(
new
Object[
0
]);
077.
model.setValueAt(rec.getString(
"CustomerID"
), row,
0
);
078.
model.setValueAt(rec.getString(
"Name"
), row,
1
);
079.
model.setValueAt(rec.getString(
"Email"
), row,
2
);
080.
model.setValueAt(rec.getString(
"CountryCode"
), row,
3
);
081.
model.setValueAt(rec.getFloat(
"Budget"
), row,
4
);
082.
model.setValueAt(rec.getFloat(
"Used"
), row,
5
);
083.
row++;
084.
}
085.
086.
rec.close();
087.
088.
}
catch
(Exception e) {
089.
090.
JOptionPane.showMessageDialog(
null
, e.getMessage());
091.
e.printStackTrace();
092.
}
093.
094.
try
{
095.
if
(s !=
null
) {
096.
s.close();
097.
connect.close();
098.
}
099.
}
catch
(SQLException e) {
100.
101.
e.printStackTrace();
102.
}
103.
104.
105.
}
106.
}