Swing 라이브러리 인터페이스에 새로 고침 단추를 포함하려고하는데이 단추의 목적은 추가/삭제/업데이트 쿼리가 호출 된 후 JTable
의 내용을 새로 고치는 것입니다. 나는 약간의 연구를했고 클래스의 tableDataChanged()
을 보았습니다. 문제는 어디에서 호출해야할지 모르겠습니다. DefaultTableModel
을 사용하고 있으므로이 방법을 사용할 수도 있습니다.JButton을 사용하여 JTable 업데이트
/*This is where I create the query and add the JTable to a scrollPane, an ResultsPanel
object is then added to a JFrame object*/
public class SitePanel extends JPanel implements Constants {
ResultsPanel resultsPanel = new ResultsPanel();
JTable table;
DefaultTableModel model;
JPanel sitePanel = new JPanel();
JPanel results = new JPanel();
public SitePanel(){
addComponents();
}
public void addComponents(){
sitePanel.setLayout(new BorderLayout());
sitePanel.add(buttonPanel, BorderLayout.NORTH);
sitePanel.add(resultsPanel, BorderLayout.CENTER);
sitePanel.setVisible(true);
add(new JScrollPane(sitePanel));
}
class ButtonPanel extends JPanel{
JPanel buttons = new JPanel();
public ButtonPanel(){
buttons.setLayout(new FlowLayout());
buttons.add(refreshButton);
show();
buttons.setVisible(true);
add(buttons);
}
public void show(){
refreshButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
new ResultsPanel();
table.setModel(model);
}
}
);
}
public class ResultsPanel extends JPanel{
public ResultsPanel(){
execute();
results.add(scrollPane);
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
results.setBorder(greenB);
results.setToolTipText("Results");
results.setVisible(true);
add(results);
}
});
}
public void execute() {
Vector columnNames = new Vector();
Vector data = new Vector();
try{
Connection conn = Connect.getConnection();
String query = "Select Name from Location Order By Name";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i=1; i<=columns;i++){
columnNames.addElement(md.getColumnName(i));
}
while (rs.next()){
Vector row = new Vector(columns);
for(int i=1; i<=columns;i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stmt.close();
conn.close();
}
catch (Exception e){
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
model.addTableModelListener(table);
table = new JTable(model){
public boolean isCellEditable(int row, int col){
return false;
}
public Class getColumnClass(int column){
for (int row=0; row<getRowCount();row++){
Object o = getValueAt(row, column);
if(o!=null){
return o.getClass();
}
}
return Object.class;
}
};
scrollPane = new JScrollPane(table);
scrollPane.setBorder(border);
scrollPane.getVerticalScrollBar().setBackground(Color.LIGHT_GRAY);
}
}
}
주 메서드가있는 클래스입니다.
import java.net.URL;
import java.sql.*;
import javax.swing.*;
public class Connect extends JFrame{
public static String user = null;
public static String password = null;
static Connection conn = null;
public static void loginGUI() throws Exception{
JPasswordField passwordField = new JPasswordField();
JTextField userField = new JTextField();
passwordField.setEchoChar('*');
Object[] obj = {"Username:\n", userField, "Password:\n", passwordField};
Object stringArray[] = {"OK", "Cancel"};
if(JOptionPane.showOptionDialog(null, obj, "Login", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj)==JOptionPane.YES_OPTION);
password = new String (passwordField.getPassword());
user = userField.getText();
Conn.formConnection();
}
public static void main (String[] args) throws Exception{
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
try {
Connect.loginGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Static connection class can only be created once at any given time.
* @author Nosheen Mahate
*
*/
public static class Conn{
public static Connection formConnection() throws Exception{
try{
String driver = "net.sourceforge.jtds.jdbc.Driver";
String url = "jdbc:jtds:sqlserver://BHX4DT-4FPQ35J:1433/Forecast;instance=SQLEXPRESS" +
";user=" +user +";password="+ password +";ssl=request;Encrypt=true;TrustServerCertificate=true";
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
try{
password = null;
JFrame frame = new JFrame();
frame.add(new SitePanel());
frame.pack();
frame.setVisible(true);
}
catch (Exception e){
System.exit(1);
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
catch (Exception e){
if(password != null || user !=null){
JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
}
else{
System.exit(1);
}
System.out.println("No Connection");
}
return conn;
}
/**
* Used to check that the connection is still established
*/
}
public static Connection getConnection(){
return conn;
}
/**
* Close the connection to the server
* @throws SQLException
*/
public static void closeConnection() throws SQLException{
conn.close();
conn = null;
}
}
코드가 상당히 많다는 것을 알고 있습니다.하지만 필요한 정보가 너무 많습니다. 다시 실행하기 위해 JButton
을 클릭 한 후 JTable
을 업데이트하는 방법과 fireTableDataChanged()
메서드를 호출해야하는 위치 (필요한 경우)를 알고 싶었습니다.
* "거기에 꽤 많은 코드가 있다는 것을 알고 있지만 당신이 필요로하는 것이 무엇인지 너무 확신하지 못했습니다."* IMO는 '아주 조금'이 아닙니다. 나는 사람들이 하나의 [SSCCE] (http://sscce.org/)를 게시하는 2 개의 스 니펫 대신에 더 많은 LOC를 보길 (또는 최소한 컴파일하는) 것으로 기대한다. –
@AndrewThompson 그 점을 명확히 생각해 주셔서 감사합니다. – Nosheen
좋은 편집이지만 SSCCE는 [작은 예제] (http://stackoverflow.com/a/8958814/418556)처럼 화면에 던져 넣기 위해'main (String [])'이 필요합니다. . –