我将JTextField用作JTable的所有列的DefaultCellEditor。
当我编辑单元格并按Enter时,焦点将移至下一个单元格。但是,当我在此单元格中写入内容时,会将值插入到前一个单元格中。但是我希望将此值输入到焦点单元格中,如何操作才能看到快照
这是代码
package abc;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.MatteBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.text.MaskFormatter;
public class VoucherDialog extends JDialog {
JPanel contentPane;
JLabel jl1,jl2,jl3;
private JTable table;
private JScrollPane scrollPane;
DefaultTableModel model;
String[] column_headers= {"SN","REF","DATE","PARTICULARS","AMOUNT",};
String[][] items= {};
Connection con=null;
PreparedStatement pst=null;
TableModel tm;
ResultSet rs=null;
String c1,c2;
int rowz,col;
JTextField snField,dateField,particularField,refField;
JFormattedTextField amountField;
JComboBox<String> ref_Cb;
JPopupMenu popup;
NumberFormat amountFormat;
private double amount = 100000;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
VoucherDialog dialog = new VoucherDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws ParseException
*/
public VoucherDialog() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException,NumberFormatException, ParseException
{
contentPane=new JPanel();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
contentPane.setBackground(Color.WHITE);
//setBounds(100, 100, 571, 322);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
try {
ActionListener a=new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
dispose();
}
};
this.getRootPane().registerKeyboardAction(a,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_IN_FOCUSED_WINDOW);
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel();
panel.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(0, 0, 0)));
contentPane.add(panel, BorderLayout.NORTH);
panel.setLayout(new GridLayout(6, 1, 0, 0));
jl1=new JLabel();
jl1.setHorizontalAlignment(SwingConstants.CENTER);
jl1.setFont(new Font("Lucida Console", Font.BOLD, 16));
jl1.setText(c1);
panel.add(jl1);
jl2=new JLabel();
jl2.setHorizontalAlignment(SwingConstants.CENTER);
jl2.setFont(new Font("Lucida Console", Font.PLAIN, 14));
jl2.setText(c2);
panel.add(jl2);
jl3=new JLabel();
jl3.setHorizontalAlignment(SwingConstants.CENTER);
jl3.setFont(new Font("Lucida Console", Font.PLAIN, 16));
jl3.setText("**Product Master** ");
panel.add(jl3);
model=new DefaultTableModel(items,column_headers)
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
if(column == 0 )
return false;
else
return true;
}
};
table = new JTable(model){
// private boolean inLayout;
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
if (isRowSelected(row)) {
c.setBackground(Color.WHITE);
c.setForeground(Color.BLACK);
} else {
c.setBackground(Color.white);
c.setForeground(Color.BLACK);
}
return c;
}
};
table.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_ENTER)
{
// Select the current cell
rowz = table.getSelectedRow();
col = table.getSelectedColumn();
int totalrows=table.getRowCount();
if((rowz+1)==totalrows)
{
model.addRow(new Object[] {"","","","",""});
}
//table.repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_INSERT)
{
int row=table.getSelectedRow();
model.insertRow(row,new Object[] {"1","","","",""} );
}
}
@Override
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_ENTER)
{
// Select the current cell
rowz = table.getSelectedRow();
col = table.getSelectedColumn();
int totalrows=table.getRowCount();
if((rowz+1)==totalrows)
{
for(int i=0;i<table.getColumnCount();i++)
{
int x=0;
if(table.getSelectedRow()>0)
{
x=Integer.valueOf(table.getValueAt(table.getSelectedRow()-1,0).toString());
x=x+1;
}
else
x=0;
}
}
}
}
});
//to make the Border at selected cell
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus,int row,int column)
{
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
//setBorder(noFocusBorder);
if (hasFocus)
{
setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(0, 0, 0)));
// to scrolling JTable automatically to the Bottom
scrollToVisible(table,table.getSelectedRow(),table.getSelectedColumn());
}
return this;
}
});
table.setBackground(Color.WHITE);
table.setShowVerticalLines(true);
table.setShowHorizontalLines(false);
// to work the enter key like the tab
InputMap im = table.getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Action.NextCell");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "Action.NextCell");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "Action.NextCell");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Action.PreviousCell");
ActionMap am = table.getActionMap();
am.put("Action.NextCell", new NextCellActioin(table));
am.put("Action.PreviousCell", new PreviousCellAction(table));
//to remove the vertical lines of the Table Header
for(int i = 0; i <column_headers.length; i++)
{
TableColumn column = table.getColumnModel().getColumn(i);
column.setHeaderRenderer(new HeaderRenderer());
}
table.setRowHeight(25);
//table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
table.setFont(new Font("Lucida Console", Font.PLAIN, 18));
table.getTableHeader().setFont(new Font("Lucida Console", Font.BOLD, 16));
table.getColumnModel().getColumn(0).setMinWidth(50);
table.getColumnModel().getColumn(0).setMaxWidth(50);
table.getColumnModel().getColumn(1).setMinWidth(50);
table.getColumnModel().getColumn(1).setMaxWidth(50);
table.getColumnModel().getColumn(2).setMinWidth(130);
table.getColumnModel().getColumn(2).setMaxWidth(130);
table.getColumnModel().getColumn(3).setMinWidth(250);
table.getColumnModel().getColumn(3).setMaxWidth(250);
table.getColumnModel().getColumn(4).setMinWidth(250);
table.getColumnModel().getColumn(4).setMaxWidth(250);
TableColumn snColumn = table.getColumnModel().getColumn(0);
snField=new JTextField();
snField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0)));
snField.setFont(new Font("Lucida Console", Font.PLAIN, 18));
snColumn.setCellEditor(new DefaultCellEditor(snField));
TableColumn refColumn = table.getColumnModel().getColumn(1);
refField=new JFormattedTextField();
refField.setFont(new Font("Lucida Console", Font.PLAIN, 18));
refField.setEditable(true);
refField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0)));
refColumn.setCellEditor(new DefaultCellEditor(refField));
TableColumn dateColumn = table.getColumnModel().getColumn(2);
JFormattedTextField dateTextField = new JFormattedTextField(new MaskFormatter("##/##/####"));
dateTextField.setFont(new Font("Lucida Console", Font.PLAIN, 18));
dateTextField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0)));
dateColumn.setCellEditor(new DefaultCellEditor(dateTextField));
TableColumn particularColumn = table.getColumnModel().getColumn(3);
particularField=new JTextField();
particularField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0)));
particularField.setFont(new Font("Lucida Console", Font.PLAIN, 18));
particularColumn.setCellEditor(new DefaultCellEditor(particularField));
TableColumn amountColumn = table.getColumnModel().getColumn(4);
//amountField=new JFormattedTextField(createAmountFormatter());
amountField=new JFormattedTextField(amountFormat);
amountField.setValue(amount);
//amountField.addFocusListener(l);
amountField.setFont(new Font("Lucida Console", Font.PLAIN, 18));
amountField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0)));
//amountField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
amountColumn.setCellEditor(new DefaultCellEditor(amountField));
scrollPane=new JScrollPane();
scrollPane.setViewportBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(255, 0, 0)));
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants. HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants. VERTICAL_SCROLLBAR_ALWAYS );
scrollPane.setViewportView(table);
scrollPane.setForeground(Color.WHITE);
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
for(int i=0;i<=20;i++)
{
model.addRow(new Object[] {"1","","","",""});
table.setValueAt(i+1, i,0);
}
contentPane.add(scrollPane, BorderLayout.CENTER);
}
// to scrolling JTable automatically to the Bottom
public static void scrollToVisible(final JTable table, final int rowIndex, final int vColIndex) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, false));
}
});
}
class NextCellActioin extends AbstractAction {
private JTable table;
public NextCellActioin(JTable table) {
this.table = table;
}
public void actionPerformed(ActionEvent e) {
int col = table.getSelectedColumn();
int row = table.getSelectedRow();
int colCount = table.getColumnCount();
int rowCount = table.getRowCount();
int x;
System.out.println("NExt");
do
{
col++;
if (col >= colCount) {
col = 0;
row++;
}
if (row >= rowCount) {
row = 0;
}
TableColumn column = table.getColumnModel().getColumn(col);
x=column.getWidth();
if(x!=0)
col--;
//else if(x==0)
//setDefaultValue(col);
}while(x==0);
col++;
if (col >= colCount) {
col = 0;
row++;
}
if (row >= rowCount) {
row = 0;
}
table.getSelectionModel().setSelectionInterval(row, row);
table.getColumnModel().getSelectionModel().setSelectionInterval(col, col);
}
}
class PreviousCellAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTable table;
public PreviousCellAction(JTable table) {
this.table = table;
}
public void actionPerformed(ActionEvent e) {
int col = table.getSelectedColumn();
int row = table.getSelectedRow();
int colCount = table.getColumnCount();
int rowCount = table.getRowCount();
System.out.println("Previous");
int x;
do
{
col--;
System.out.println("3"+col);
if (col<0)
{
col =colCount-1;
row--;
System.out.println("1"+col);
}
if (row<0)
{
row =rowCount-1;
}
x = table.getColumnModel().getColumn(col).getWidth();
//x=column.getWidth();
if(x!=0)
col++;
//else if(x==0)
System.out.println("2"+x);
//setDefaultValue(col);
}while(x==0);
col--;
if (col<0)
{
/*if (row==0)
{
row =rowCount;
}
else*/
System.out.println("2"+col);
col =colCount-1;
row--;
System.out.println("3"+col);
}
if (row<0)
{
row =rowCount-1;
}
table.getSelectionModel().setSelectionInterval(row, row);
table.getColumnModel().getSelectionModel().setSelectionInterval(col, col);
}
}
}
//this class used to hide the tableHeader
class HeaderRenderer extends JLabel implements TableCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean hasFocus,
boolean isSelected,
int row,
int col)
{
setText(value.toString());
setFont(new Font("Lucida Console", Font.PLAIN, 18));
setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
return this;
}
}