cannot return Double Value in JTable - java

I am making a ui in which i read data from a text file and save it to another text file after the user edits in it.i want to return integer values for all columns except column 6 and 7.For column 6 and 7 i want to return double values.Everything in this program works fine only for column 6 and column 7 when user edit in it until they enter a integer value it shows red marks in the cells whereas i should be double values for column 6 and column 7.please help
Code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Read extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Read()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("test1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens() )
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null)
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
final JTable table = new JTable(new DefaultTableModel(data, columnNames){
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
return Integer.class;
}
});
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button1 = new JButton( "Save" );
buttonPanel.add( button1 );
button1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Object Value = table.getValueAt (i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("new.txt"));
fileWriter.write(con.toString());
fileWriter.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Read a = new Read();
a.setDefaultCloseOperation( EXIT_ON_CLOSE );
a.pack();
a.setVisible(true);
}
}
text file
1 2 3 4 5 6 7 8
78 12 12 45 4 0.0045 0.0078 45
45 45 69 56 7 0.0056 0.0023 21
45 89 76 42 1 0.0036 0.0023 36

TableModel#getColumnClass is used to determine which renderer AND which editor should be used by the JTable.
When you use Integer.class for the column class, the JTable sets up a JFormattedField configured to only allow whole numbers to be accepted. You need to modify the getColumnClass to return the correct data type of the given column, for example...
#Override
public Class getColumnClass(int column) {
return column == 5 || column == 6 ? Double.class : Integer.class;
}
You should also make sure that the data you are entering into the model is capable of meeting this contract, for example...
while (st2.hasMoreTokens()) {
Object num = null;
String value = st2.nextToken();
Number num = NumberFormat.getNumberInstance().parse(value);
row.addElement(num);
}

Related

How to sort JTable depending of JComboBox selected item

I Have java code like this:
private ArrayList<Room> loadRoom() {
ArrayList<Room> rooms = new ArrayList<Room>();
try {
File roomsFile = new File("src/txt/rooms");
BufferedReader br = new BufferedReader(new FileReader(roomsFile));
String line = null;
while ((line = br.readLine()) != null) {
String[] split = line.split("\\|");
int number = Integer.parseInt(split[0]);
String type = split[1];
String name = split[2];
int beds = Integer.parseInt(split[3]);
Boolean tv = Boolean.parseBoolean(split[4]);
Boolean miniBar = Boolean.parseBoolean(split[5]);
Boolean ocupied = Boolean.parseBoolean(split[6]);
Boolean deleted = Boolean.parseBoolean(split[7]);
Room newRoom = new Room(number, type, name, beds, tv, miniBar, ocupied, deleted);
rooms.add(newRoom);
}
} catch (Exception e) {
e.printStackTrace();
}
return rooms;
}
private void initGUI() {
tbToolBar = new JToolBar();
btnAdd = new JButton();
tbToolBar.add(btnAdd);
spScroll = new JScrollPane();
lblSort = new JLabel("Sort by ");
cbSort = new JComboBox();
btnSort = new JButton("Sort");
cbSort.addItem("Number");
cbSort.addItem("Type");
tbToolBar.add(lblSort);
tbToolBar.add(cbSort);
tbToolBar.add(btnSort);
ArrayList<Room> rooms = loadRoom();
String[] header = new String[] { "Number", "Type", "Name", "No. beds", "TV", "Mini bar", "Occupation" };
Object[][] show = new Object[rooms.size()][header.length];
for (int i = 0; i < rooms.size(); i++) {
Room r = rooms.get(i);
show[i][0] = r.getNumber();
show[i][1] = r.getType();
show[i][2] = r.getName();
show[i][3] = r.getBeds();
show[i][4] = r.getTv().toString();
show[i][5] = r.getMiniBar().toString();
show[i][6] = r.getOcupied().toString();
// show[i][7] = r.getDeleted();
}
DefaultTableModel tableModel = new DefaultTableModel(show, header);
tblRooms = new JTable(tableModel);
tblRooms.setRowSelectionAllowed(true);
tblRooms.setColumnSelectionAllowed(true);
tblRooms.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
tblRooms.setDefaultEditor(Object.class, null);
JScrollPane tableScroll = new JScrollPane(tblRooms);
add(spScroll);
add(tbToolBar, BorderLayout.NORTH);
add(tableScroll, BorderLayout.CENTER);
}
private void initAction() {
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
RoomAddWindow addRoom = new RoomAddWindow();
addRoom.setVisible(true);
}
});;
}
And text file like this:
13|family room|name apartman|4|true|true|empty|false
16|superior room|super room|2|true|false|empty|false
15|room|room for one|1|false|false|full|false
Text file is shown normaly in JTable in order like in text file. But I have JComboBox with two filters: Number (room Number - split[0] in text file) and Room Type split[2].
The question is:
What is the simplest way to sort JTable by one of theese parameters?
EDIT:
I would like to use tblRooms.setAutoCreateRowSorter(true);, but profesor said he want from us to do that on harder way and you sort only by these two parameters. :D
Also, Even when I tried it number is sorted only by first digit.
For example if I want to sort by descending numbers it will sort like this:
41
21
15
13
1234
123
12
0
Instead of:
1234
123
41
21
15
13
12
0

reading desired data from file but saving the whole file data

I have made a GUI using swing, i read data from a text file to the jtable,
the text file has 6 columns and 5 rows,the 3 row has values 0,0.0,0,0,0,0.so i want to display
values in the JTable till it encounters 0.but to save the full text file while saving which means values of 5 rows.here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Bb extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Bb()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens())
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null )
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button2 = new JButton( "SAVE TABLE" );
buttonPanel.add( button2 );
button2.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuffer Con = new StringBuffer();
for (int i = 0; i < table.getRowCount(); i++)
{
for (int j = 0; j < table.getColumnCount(); j++)
{
Object Value = table.getValueAt(i, j);
Con.append(" ");
Con.append(Value);
}
Con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("cc.txt"));
fileWriter.write(Con.toString());
fileWriter.flush();
fileWriter.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Bb frame = new Bb();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
and the text file:
1 2 6 0.002 0.00 2
2 5 5 0.005 0.02 4
0 0 0 0.000 0.00 0
4 8 9 0.089 0.88 7
5 5 4 0.654 0.87 9
I was able to understand what you want
For first part that you just wanted to show your data in your JTable till you encounter 0
code:
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0")) {
break;
}
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
Explanation: when you read each line, split it, so if the first element of each splitted line is zero, you come out of the loop and do not show any other values inside the loop.
For saving all your data from first file to second file, you should copy them from first file to second file because your JTable will not have enough info to help your purpose in this matter.
Note: I do not understand why you want to do this but you can accomplish that in following way
Code:
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
String st = "";
FileInputStream fin = new FileInputStream("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
Scanner input = new Scanner(fin).useDelimiter("\\A");
while (input.hasNext()) {
st = input.next();
System.out.println("st is " + st);
}
FileWriter fileWriter = new FileWriter(new File("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"));
fileWriter.write(st);
fileWriter.flush();
fileWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Explanation: you read the whole file with Scanner trick and write it down into a second file.
Source: https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html
Based on what the OP requested
Code:
public Bb() {
String aLine;
Vector columnNames = new Vector();
Vector data = new Vector();
boolean found = false;
StringBuilder temp = new StringBuilder();
/*Using try catch block with resources Java 7
Read about it
*/
try (FileInputStream fin = new FileInputStream("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
//the first line of the txt file fill colum names
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
columnNames.addElement(s);
}
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0") && !found) {
found = true;
} else if (found) {
temp.append(aLine).append("\r\n");
} else if (!sp[0].equals("0") && !found) {
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
}
} catch (IOException e) {
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton button2 = new JButton("SAVE TABLE");
buttonPanel.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
Object Value = table.getValueAt(i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
try (FileWriter fileWriter = new FileWriter(new File("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"))) {
fileWriter.write(con.append(temp).toString());
fileWriter.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
My code just works if you have row includes zeros. if you want to make it better to cover up all conditions, I am sure you can follow my plan.
Sample to get rid of all zeros like
1 1 1
0 0 0
0 0 0
1 1 1
Code:
String s = "xxxooooooxxx";
String[] sp = s.split("");
boolean xFlag = false;
for (int i = 0; i < sp.length; i++) {
if (sp[i].equals("x") && !xFlag) {
System.out.print("x");
} else if (sp[i].equals("o")) {
xFlag = true;
} else if (sp[i].equals("x") && xFlag) {
System.out.print("X");
}
}
output:
xxxXXX

Fill some JTable columns with data from array

I have a csv file (5 columns, with | as delimiter) and I want to fill 2 JTable columns with two data columns from csv file.
public class jTable extends JFrame {
public static int rowNumber() {
int num = 0;
try {
File files = new File("C:\\BorsaItalia2.csv");
BufferedReader bf = new BufferedReader(new FileReader(files));
String lines = "";
while ((lines = bf.readLine()) != null) {
num++;
}
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
JTable table;
public jTable() {
setLayout(new FlowLayout());
String[] columnNames = {"a", "b", "c", "d", "e"};
Object[][] data = new Object[rowNumber()][5];
table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(600, 950));
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
add(scroll);
}
public static void main(String[] args) {
try {
int row = 0;
int col = 0;
Object[][] imported = new Object[rowNumber()][5];
File file = new File("C:\\BorsaItalia2.csv");
BufferedReader bfr = new BufferedReader(new FileReader(file));
String line = "";
while ((line = bfr.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, "|");
col = 0;
while (st.hasMoreTokens()) {
imported[row][col] = st.nextToken();
System.out.println("number["+ row + "]["
+ col + "]:" + imported[row][col]);
col++;
}
row++;
}
bfr.close();
Object[] description = new Object[imported.length];
Object[] symbol = new Object[imported.length];
for (int i = 0; i < imported.length; i++) {
description[i] = imported[i][2];
symbol[i] = imported[i][0];
}
for (int i = 1; i < imported.length; i++) {
System.out.println("Description is " + description[i]
+ " and symbol is: " + symbol[i]);
}
System.out.println("");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("error " + e);
}
jTable gui = new jTable();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(650, 950);
gui.setVisible(true);
gui.setTitle("Project Table");
}
}
I would like to fill table column a with Object[] symbol and column c with Object[] description.
Any coding help really appreciated.
Thanks all.
Instead of using the DefaultTableModel implied by your JTable constructor, create your own implementation of AbstractTableModel, as shown in How to Use Tables: Creating a Table Model. Arrange for your getValueAt() to return the data from the arrays you've read. There's a related example here.

Scroll a JScrollPane to a specific row on a JTable [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JTable Scrolling to a specified row index
I have a JTable and I programmatically need to select a row by using this code:
myTable.setRowSelectionInterval(i, j);
(where i and j are valid row and column numbers respectively).
The problem is, when you jump to a row, the JScrollPane does not move.
In this case, the table is quite long, and often the "selected row" is not visible on the screen, so the user has to stay scrolling up/down manually to find it. I would like to know how I can make the JScrollPane automatically jump to the specific location of the row.
Edit: Found this one liner which can do it:
table.scrollRectToVisible(table.getCellRect(row,0, true));
just extends post by #Eng.Fouad +1, no works as I exactly expected (with kind help by StanislavL from another Java Swing forum)
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class TableSelectionGood implements ListSelectionListener {
private JTable[] tables;
private boolean ignore = false;
public TableSelectionGood() {
Object[][] data1 = new Object[100][5];
Object[][] data2 = new Object[50][5];
Object[][] data3 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
for (int i = 0; i < data2.length; i++) {
data2[i][0] = "Company # " + ((i * 2) + 1);
for (int j = 1; j < data2[i].length; j++) {
data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
}
}
for (int i = 0; i < data3.length; i++) {
data3[i][0] = "Company # " + (i * 2);
for (int j = 1; j < data3[i].length; j++) {
data3[i][j] = "" + (i * 2) + ", " + j;
}
}
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
DefaultTableModel model2 = new DefaultTableModel(data2, headers);
DefaultTableModel model3 = new DefaultTableModel(data3, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 200));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model2);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 200));
sp2.setViewportView(jTable2);
final JTable jTable3 = new JTable(model3);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 200));
sp3.setViewportView(jTable3);
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2, jTable3);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TableSelectionGood(JTable... tables) {
for (JTable table : tables) {
table.getSelectionModel().addListSelectionListener(this);
}
this.tables = tables;
}
private JTable getTable(Object model) {
for (JTable table : tables) {
if (table.getSelectionModel() == model) {
return table;
}
}
return null;
}
private void changeSelection(JTable table, String rowKey) {
int col = table.convertColumnIndexToView(0);
for (int row = table.getRowCount(); --row >= 0;) {
if (rowKey.equals(table.getValueAt(row, col))) {
table.changeSelection(row, col, false, false);
return;
}
}
table.clearSelection();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || ignore) {
return;
}
ignore = true;
try {
JTable table = getTable(e.getSource());
int row = table.getSelectedRow();
String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
for (JTable t : tables) {
if (t == table) {
continue;
}
changeSelection(t, rowKey);
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
Rectangle r2 = viewport.getVisibleRect();
t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
}
} finally {
ignore = false;
}
}
public static void main(String[] args) {
TableSelectionGood tableSelection = new TableSelectionGood();
}
}
I used this in my old project:
public static void scrollToVisible(JTable table, int rowIndex, int vColIndex)
{
if (!(table.getParent() instanceof JViewport)) return;
JViewport viewport = (JViewport)table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Point pt = viewport.getViewPosition();
rect.setLocation(rect.x-pt.x, rect.y-pt.y);
viewport.scrollRectToVisible(rect);
}
Reference: http://www.exampledepot.com/egs/javax.swing.table/Vis.html

JTable & JTextField used for input. JTable is updateable. DocumentListener used for JTextField. Event doesn't fire. How to get event?

import java.awt.*;
import java.awt.Component;
import java.lang.*;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.event.*;
import javax.swing.text.Document;
import javax.swing.text.*;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.*;
import java.util.*;
public class Test1 extends JApplet
{
Object dummya [][] = new Object [9][9]; // Setup 2-Dimensional Arrays
int inputa [][] = new int [9][9];
int possiblea [][] = new int [81][9];
int solveda [][] = new int [9][9];
String ic = "B";
String nl = "\n";
String col_h [] = {"G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"};
Font f = new Font ("Courier", Font.BOLD, 10);
Font h = new Font ("Times Roman", Font.BOLD, 14);
JTextField uc = new JTextField (1);
JTextField st = new JTextField (75);
int gs = 55;
int wl = 1;
int ts = col_h.length;
DefaultTableModel dm = new DefaultTableModel(dummya, col_h) { // Setup the Table Model
public String getColumnName (int col) {return col_h[col];}
public int getColumnCount() {return 9;} // Setup a 9x9 Table with headers
public int getRowCount() {return 9;}
public void setValueAt (Object foundValue, int row, int col) {
// st.setText ("At setValueAt.");
// inputa[row][col] = (Integer) foundValue;
fireTableCellUpdated (row, col);
}
};
JTable table = new JTable (dm); // Create the Table
public void init () {
Container c = getContentPane (); // Get a Container for User View
Color lc = new Color (240, 128, 128); // Set Light Coral Color
c.setBackground (lc);
c.setFont (f);
table.getTableHeader().setResizingAllowed (false); // Setup all the Table rules
table.getTableHeader().setReorderingAllowed (false);
table.setSelectionMode (javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
for (int i = 0; i < ts; i++) { // Resize Columns & Rows to 40 pixels
TableColumn column = table.getColumnModel().getColumn(i);
column.setMinWidth (40);
column.setMaxWidth (40);
column.setPreferredWidth (40);
table.setRowHeight (i, 40);
}
table.getModel().addTableModelListener (
new TableModelListener() {
public void tableChanged(TableModelEvent e) {
tableDataChanged (e);
}
});
c.setLayout (new FlowLayout (FlowLayout.CENTER, 340, 0)); // Setup a Layout & add Components
c.add (new JLabel (" "));
c.add (new JLabel ("Challenge", SwingConstants.CENTER));
c.add (new JLabel (" "));
c.add (new JLabel ("By Author X", SwingConstants.CENTER));
c.add (new JLabel (" ")); // Add a pad line
c.setFont (h);
table.setGridColor (Color.red); // Setup Table View
c.add (table.getTableHeader()); // Add Column Headers
c.add (table); // Show the Table
c.add (new JLabel (" "));
uc.setBackground (lc);
c.add (new JLabel (" Enter Command (C,F,H,L,I,P,S): ", SwingConstants.CENTER));
c.add (uc); // Add a User Command Field
uc.setEditable (true); // Allow Input in Command Field
uc.requestFocusInWindow();
c.add (new JLabel (" "));
st.setBackground (lc);
c.add (st); // Add a Status area
st.setEditable (false);
uc.getDocument().addDocumentListener (new DocumentListener() { // Listen for JTextField command
public void changedUpdate(DocumentEvent e) {
editInput();
}
public void insertUpdate(DocumentEvent e) {
editInput();
}
public void removeUpdate(DocumentEvent e) {}
});
}
// The following section is driven by a user command.
public void run () { // To keep the Applet running, just loop
int loopcnt = 0;
while (wl != -1) {
loopcnt++;
if (loopcnt == 100) {
try { Thread.sleep (10000); } // Sleep for 10 seconds to allow solve
catch (InterruptedException e) {} // thread to run.
loopcnt = 0;
}
}
}
private void editInput () { // Scan user command
try { ic = uc.getText (0, 1); } // Pick up user command
catch (BadLocationException be) { return; }
st.setText (" User Input is: " + ic);
if (ic == "C" || ic == "c") clearComponents ();
else if (ic == "E" || ic == "e") {
st.setText (" User Exit.");
wl = -1;
}
else if (ic == "H" || ic == "h") newFrame();
// else if (ic == "F" || ic == "f") getHintAtFirst(); // Get a hint where only 2 values possible
// else if (ic == "L" || ic == "l ") getHintAtLast();
// else if (ic == "I" || ic == "i") StartThread(); // Look into wait and Notify
// else if (ic == "P" || ic == "p") printGrid();
// else if (ic == "S" || ic == "s") solveAndShow();
// else st.setText (" Invalid Command, try again.");
}
public void clearComponents () { // Clear Arrarys and Table View
for (int i = 0; i < ts; i++) {
for (int j = 0; j < ts; j++) {
dummya[i][j] = null;
inputa[i][j] = 0;
possiblea[i][j] = 0;
solveda[i][j] = 0;
table.setValueAt (null, i, j);
}
}
st.setText (" Table Cleared.");
}
private void newFrame () { // Setup the Possibles frame
JFrame possibles = new JFrame ("Grid Possibilities");
possibles.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
possibles.setBounds (550, 0, 440, 580);
JTextArea ta = new JTextArea ();
JScrollPane sp = new JScrollPane ();
possibles.add (ta);
possibles.add (sp);
possibles.pack ();
possibles.validate ();
possibles.setVisible (true);
}
public void tableDataChanged (TableModelEvent e) { // Process & Edit user input
int row = e.getFirstRow();
int col = e.getColumn();
// TableModel model = (TableModel) e.getSource();
// String cn = model.getColumnName (col);
for (int i = row; i < ts; i++) { // Scan the input for values
for (int j = col; i < ts; j++) {
dummya [row][col] = table.getValueAt (i, j);
int newValue = (Integer) dummya [row][col];
int rc = integerEditor (1, 9, newValue); // Go check the user input
if (rc == 0) {
st.setText ("Input Value is " + newValue);
inputa [row][col] = (Integer) dummya [row][col]; // Store the grid value
}
else st.setText ("Input Value is invalid at " + row+1 + "," + col+1 + ".");
}
}
}
private int integerEditor (int va, int vb, int value) { // Edit user input
if (value < va || value > vb) return -1;
return 0;
}
}
DefaultCellEditor dce = (DefaultCellEditor)table.getDefaultEditor(Object.class);
JTextField editor = (JTextField)dce.getComponent();
editor.addDocumentListener(...);

Categories

Resources