當(dāng)前位置: 首頁(yè)IT技術(shù) → 將JTable作為文本輸入框

將JTable作為文本輸入框

更多

下面的例子將JTable做為一個(gè)輸入數(shù)據(jù)的文本框,當(dāng)雙擊擊每行第一個(gè)格子時(shí),自動(dòng)添加一個(gè)空白行

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class NewJFrame extends javax.swing.JFrame {

        private JScrollPane scrollPane;

private JTable table;
private Vector<String> currentRow;
private Vector<String> currentRow1;
private Vector<Vector<String>> rows;
private Vector<String> colHeader;

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
NewJFrame inst = new NewJFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public NewJFrame() {
scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
scrollPane.setPreferredSize(new java.awt.Dimension(392, 109));
String colName[] = {"c1","c2","c4","c5"};
    colHeader = new Vector<String>();
rows = new Vector<Vector<String>>();
currentRow = new Vector<String>();
for(int i = 0;i< 4;i++){
colHeader.add(colName[i]);
currentRow.add("");
}
rows.addElement(currentRow);
TableModel tableModel = new DefaultTableModel(rows, colHeader);
table = new JTable(tableModel);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
if(table.getSelectedColumn() == 0)
addRow();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
scrollPane.setViewportView(table);
setSize(400, 300);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public void addRow(){
currentRow1 = new Vector<String> ();
for(int i = 0;i< 4;i++){
currentRow1.add("");
}
rows.addElement(currentRow1);
}
}

 

效果圖

 

熱門評(píng)論
最新評(píng)論
發(fā)表評(píng)論 查看所有評(píng)論(0)
昵稱:
表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
字?jǐn)?shù): 0/500 (您的評(píng)論需要經(jīng)過審核才能顯示)