当前位置: 首页IT技术 → 将JTable作为文本输入框

将JTable作为文本输入框

更多

下面的例子将JTable做为一个输入数据的文本框,当双击击每行第一个格子时,自动添加一个空白行

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);
}
}

 

效果图

 

热门评论
最新评论
昵称:
表情: 高兴 可 汗 我不要 害羞 好 下下下 送花 屎 亲亲
字数: 0/500 (您的评论需要经过审核才能显示)