자바 jTable 정렬하는법좀 도와주세여

조회수 2232회

이미지

...

import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import javax.swing.JOptionPane;

public class MainFrame extends javax.swing.JFrame {

public MainFrame() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    lblTitle = new javax.swing.JLabel();
    lblOrder = new javax.swing.JLabel();
    lblMovie = new javax.swing.JLabel();
    lblGallery = new javax.swing.JLabel();
    txtOrder = new javax.swing.JTextField();
    txtMovie = new javax.swing.JTextField();
    txtGallery = new javax.swing.JTextField();
    btnInsert = new javax.swing.JButton();
    btnUpdate = new javax.swing.JButton();
    btnDelete = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    btnSort = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    lblTitle.setText("Table 예제");

    lblOrder.setText("순         위");

    lblMovie.setText("영화 제목");

    lblGallery.setText("관객 동원");

    txtOrder.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtOrderActionPerformed(evt);
        }
    });

    btnInsert.setText("Insert");
    btnInsert.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnInsertActionPerformed(evt);
        }
    });

    btnUpdate.setText("Update");
    btnUpdate.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnUpdateActionPerformed(evt);
        }
    });

    btnDelete.setText("Delete");
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            { new Integer(1), "로마의 휴일", "1000000"},
            { new Integer(2), "타이타닉", "800000"},
            { new Integer(3), "죽은 시인의 사회", "600000"},
            { new Integer(4), "쉬리", "400000"},
            {null, null, null}
        },
        new String [] {
            "순위", "영화 제목", "관객 동원"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.Integer.class, java.lang.String.class, java.lang.String.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
    });
    jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTable1MouseClicked(evt);
        }
    });
    jScrollPane1.setViewportView(jTable1);

    btnSort.setText("Sorting");
    btnSort.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            btnSortMouseClicked(evt);
        }
    });
    btnSort.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnSortActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(lblGallery)
                        .addComponent(lblMovie, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblOrder))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(txtOrder)
                        .addComponent(txtMovie)
                        .addComponent(txtGallery)))
                .addGroup(layout.createSequentialGroup()
                    .addGap(170, 170, 170)
                    .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(64, 64, 64)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnInsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addComponent(btnSort))
            .addGap(9, 9, 9))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(62, 62, 62)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtMovie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblMovie))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtGallery, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblGallery)))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(44, 44, 44)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblOrder))))
                    .addGap(0, 18, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(btnInsert)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnUpdate)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnDelete)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnSort)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

private void txtOrderActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        

private void btnInsertActionPerformed(java.awt.event.ActionEvent evt) {                                          
    int iCntRow = 0;

    iCntRow = jTable1.getRowCount();
    for(int idx=0; idx < jTable1.getRowCount(); idx++){
        if(jTable1.getValueAt(idx,0)==null){
            iCntRow = idx;
            break;
        }
    }
    jTable1.setValueAt(txtOrder.getText(),iCntRow,0);
    jTable1.setValueAt(txtMovie.getText(),iCntRow,1);
    jTable1.setValueAt(txtGallery.getText(),iCntRow,2);
}                                         

private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                          
    int iCntRow = 0;
    iCntRow = jTable1.getSelectedRow();

    jTable1.setValueAt(txtOrder.getText(),iCntRow,0);
    jTable1.setValueAt(txtMovie.getText(),iCntRow,1);
    jTable1.setValueAt(txtGallery.getText(),iCntRow,2);
}                                         

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
    int iCntRow = 0;
    iCntRow = jTable1.getSelectedRow();         // 선택한 행 번호 변환

    for(int idx=0; idx < jTable1.getColumnCount(); idx++)
    jTable1.setValueAt(null,iCntRow,idx);  // 선택한 행의 열의 값 삭제

    txtOrder.setText(null);                 //txtOrder 초기화
    txtMovie.setText(null);                 //txtMovie 초기화
    txtGallery.setText(null);               //txtGallery 초기화
}                                         

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
    int iCntRow = 0;
    iCntRow = jTable1.getSelectedRow(); // 선택한 행 번호 반환

    txtOrder.setText(jTable1.getValueAt(iCntRow,0).toString());
    txtMovie.setText(jTable1.getValueAt(iCntRow,1).toString());
    txtGallery.setText(jTable1.getValueAt(iCntRow,2).toString());

}                                    

private void btnSortActionPerformed(java.awt.event.ActionEvent evt) {                                        
    //int row = jTable1.getSelectedRow();
    // 0: 순이 1:영화제목 2:관객동원

}                                       

private void btnSortMouseClicked(java.awt.event.MouseEvent evt) {                                     

}                                    

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnInsert;
private javax.swing.JButton btnSort;
private javax.swing.JButton btnUpdate;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JLabel lblGallery;
private javax.swing.JLabel lblMovie;
private javax.swing.JLabel lblOrder;
private javax.swing.JLabel lblTitle;
private javax.swing.JTextField txtGallery;
private javax.swing.JTextField txtMovie;
private javax.swing.JTextField txtOrder;
// End of variables declaration                   

}

...

제가만든 자바 jTable입니다.

관객동원수를 읽어들여 sort하고싶습니다.

2가지 방법을 생각해봤는데

  1. sorting 버튼을 누르면 관객동원의 열을 읽어들여 내림차순/오름차순을 한다.

  2. 관객동원 열 칼럼헤더를 누르면 그것을 기준으로 정렬한다.

이두 가지 방법을 생각해봤는데

1번 방법은 테이블안에 관객동원 값을 읽어들이는 방법을 모르겠고 2번 방법은 관객동원 헤더 클릭시 이벤트 발생시키는 법을 모르겠습니다.

둘중 하나라도 자세히 알려주시면 감사하겠습니다.

  • (•́ ✖ •̀)
    알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)