Java Table Drag and Drop (no JTable) get Column - java

I have a program with two tables, no Jtables, an I want to add drag and drop.
it is nearly working with:
public void drop(DropTargetEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
DropTarget target = (DropTarget) event.widget;
TableItem item = (TableItem) event.item;
String data = (String) event.data;
int col=1;
item.setText(col,data);
System.out.println(" DROP: " + data);
}
}
With event.item I got the right row, but how did I get the right column for "int col" when I released the mouse button?

thx to greg-449, so it is working
public void drop(DropTargetEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
// Get the dropped data
DropTarget target = (DropTarget) event.widget;
Table table = (Table) target.getControl();
TableItem item = (TableItem) event.item;
String data = calc.KM_DEC_KM_V((String) event.data);
int col=1;
Control absolut = getParent().getDisplay().getFocusControl();
if (item != null){
col = getColumn(table,event.x + absolut.toControl(item.getBounds(0).x,item.getBounds(0).y).x);
if (col==1 || col==2) {
item.setText(col,data);
}
}
table.redraw();
System.out.println(" DROP: " + data);
}
}
with
private static int getColumn(Table table, int x)
{
int overallWidth = 0;
for(int i = 0; i < table.getColumnCount(); i++)
{
overallWidth += table.getColumn(i).getWidth();
System.out.println("overallWidth "+ overallWidth);
if(x < overallWidth)
{
return i;
}
}
return -1;
}

Related

How to add and subtract value of sum after adding/removing a row from JTable

I have the code for adding and removing a single row for my JTable but it causes problems like not providing accurate calculation of overall sum and subtraction after removing it from the JTable. The JTable serves as a "cart" for adding and removing items in the cart.
The add to cart button for adding a row to the cart:
if (e.getSource() == movebutton) {
TableModel model1 = productTable.getModel();
int index[] = productTable.getSelectedRows();
Object[] row = new Object[4];
DefaultTableModel model2 = (DefaultTableModel) cartTable.getModel();
for (int i = 0; i < index.length; i++) {
row[0] = model1.getValueAt(index[i], 0);
row[1] = model1.getValueAt(index[i], 1);
row[2] = model1.getValueAt(index[i], 2);
model2.addRow(row);
getSum();
}
The code where it adds the overall items:
public void getSum() { //column 02 is where the item's prices are listed
for (int i = 0; i < cartTable.getRowCount(); i++) {
total += Double.parseDouble(cartTable.getValueAt(i, 2).toString());
}
cartAmount.setText("Total: P " + Double.toString(total));
}
}
The remove an item from the cart button code:
try {
for (int i = 0; i < cartTable.getRowCount(); i++) {
total = total - Double.parseDouble(cartTable.getValueAt(i, 2).toString());
}
cartAmount.setText("Total: P " + Double.toString(total));
if (total <= 0.0) {
total = 0.0;
}
{
int getSelectedRowForDeletion = cartTable.getSelectedRow();
model2.removeRow(getSelectedRowForDeletion);
JOptionPane.showMessageDialog(null, "Item removed from cart");
}
} catch (NumberFormatException ex) {
ex.printStackTrace();
} catch (ArrayIndexOutOfBoundsException ex) {
}
}
Here are some pics when adding and remove an item:
How can I also make the remove button to not work when no row is selected? Like ask the user to select a row before deletion? Also remove the possibility of having negative sum calculations. Thank you
I solved it:
The add to cart button:
if (e.getSource() == movebutton) {
try {
int index[] = productTable.getSelectedRows();
Object[] row = new Object[4];
for (int i = 0; i < index.length; i++) {
row[0] = model.getValueAt(index[i], 0);
row[1] = model.getValueAt(index[i], 1);
row[2] = model.getValueAt(index[i], 2);
model2.addRow(row);
}
DefaultTableModel t = (DefaultTableModel) productTable.getModel();
int selectedRow = productTable.getSelectedRow();
{
total += Double.parseDouble(t.getValueAt(selectedRow, 2).toString());
}
cartAmount.setText("Total: P " + Double.toString(total));
}catch (ArrayIndexOutOfBoundsException a) {
}
}
The remove button:
if (e.getSource() == remove) {
try {
DefaultTableModel t = (DefaultTableModel) cartTable.getModel();
int getSelectedRowForDeletion = cartTable.getSelectedRow();
if (getSelectedRowForDeletion >= 0) {
int selectedRow = cartTable.getSelectedRow();
total -= Double.parseDouble(t.getValueAt(selectedRow, 2).toString());
cartAmount.setText("Total: P " + Double.toString(total));
model2.removeRow(getSelectedRowForDeletion);
JOptionPane.showMessageDialog(null, "Item removed from cart!");
} else {
JOptionPane.showMessageDialog(null, "Select an item to remove.");
}
} catch (ArrayIndexOutOfBoundsException a) {
}
}
I removed the for loop when adding the values as it will just add the next item in the productTable. Same goes for the remove button.

How to process large DefaultStyledDocument and catch a cancel event?

I have a JTextPane with an extended DefaultStyledDocument. Updating the document takes about 2 minutes. Currently I am breaking it up into steps and updating on the swing thread with InvokeAndWait for each step. I have a progress bar and a cancel button. The cancel button only triggers when there is a break between steps. Each step takes about 10 seconds so I need to wait up to 10 seconds to stop the processing of the document. Is there anyway to make this more responsive? I am displaying a JFrame with the JTextPane in a JScrollPane when it is done. When it is finally rendered the scroll is very responsive and I can view the whole document. I do not want to display the JFrame until the document is updated yet I want to continue to show the progress of the update. Any ideas on how to update the document and have Swing and/or the cancel button more responsive?
====== Edit in response to comments ======
In styled document using the append(text) method - setting styles for each line before appending.
public void append(String text)
{
append(text, textStyle, paragraphStyle);
}
public void append(String text, Style ts, Style ps)
{
try
{
int start = this.getLength();
int end = this.getLength()+text.length();
this.insertString(start, text, ts);
this.setParagraphAttributes(start, end, ps, true);
}
catch (BadLocationException e)
{
LOG.log(Level.SEVERE, "Bad location in append", e);
}
}
======== Edit ========
This is what my document update method looks like.
public void writeTextOutsideOfSwing(StatusDialog status, float statusPercentage)
{
final StringBuilder letter = new StringBuilder();
final ArrayList<IndexTextEntry>list = new ArrayList<>();
LOG.log(Level.INFO, "Updating document: {0}", entries.length);
setText("");
int step = (int)((status.getMaximum() * statusPercentage) / (double)entries.length);
for(int j = 0; j < entries.length; j++)
{
if(status.cancel) break;
final int index = j;
list.add(entries[j]);
if(list.size() == 100 || index == entries.length -1)
{
int first = index - list.size() + 2;
int last = index + 1;
status.setStatusBarText("Writing Concordance: Processing " + first + " - " + last + " of " + entries.length);
try
{
SwingUtilities.invokeAndWait(()->
{
for(int k = 0; k < list.size(); k++)
{
int i = index-list.size() + k;
if(!letter.toString().equals(list.get(k).getSortLetter()))
{
letter.setLength(0);
letter.append(list.get(k).getSortLetter());
String title = list.get(k).getSortLetterTitle(letter.toString());
appendLetter(title, i == 0);
}
else if(i > 0)
{
if(cf.getLineBetweenEntries())
{
clearTextAreaStyles();
setFontSize(cf.getLineBetweenEntriesFontSize());
append(" \n");
}
}
float indent = appendEntry(0, list.get(k));
appendSubEntries(indent, list.get(k));
}
});
}
catch(InterruptedException | InvocationTargetException ex)
{ LOG.log(Level.SEVERE, "Writing Concorder Interrupted", ex); }
list.clear();
}
status.increment(step);
}
LOG.info("Done updating docuemnt");
}
And these methods go with the write method:
private void appendSubEntries(float indent, IndexTextEntry entry)
{
for (IndexTextEntry subEntry : entry.getSubEntries())
{
float ind = appendEntry(indent, subEntry);
appendSubEntries(ind, subEntry);
}
}
private float appendEntry(float indent, IndexTextEntry entry)
{
setFontFamily(cf.getWordFormat().getFontFamily());
setFontSize(cf.getWordFormat().getFontSize());
setFontBold(cf.getWordFormat().getBold());
setFontItalic(cf.getWordFormat().getItalic());
switch (cf.getWordFormat().getAlignment())
{
case TextFormat.ALIGN_CENTER:
setFontAlignment(EnhancedTextArea.ALIGN_CENTER);
break;
case TextFormat.ALIGN_RIGHT:
setFontAlignment(EnhancedTextArea.ALIGN_RIGHT);
break;
default:
setFontAlignment(EnhancedTextArea.ALIGN_LEFT);
break;
}
float wi = indent + cf.getWordFormat().getIndentJAVA();
setLeftIndent(wi);
setFontColor(cf.getWordFormat().getColor());
append(entry.getConcordance().getTitle());
append("\n");
float li = 0;
for(ConcordanceLine line : entry.getConcordance().getLines())
li = appendLine(wi, line);
return li;
}
private float appendLine(float indent, ConcordanceLine line)
{
setFontFamily(cf.getLineFormat().getFontFamily());
setFontSize(cf.getLineFormat().getFontSize());
switch (cf.getLineFormat().getAlignment())
{
case TextFormat.ALIGN_CENTER:
setFontAlignment(EnhancedTextArea.ALIGN_CENTER);
break;
case TextFormat.ALIGN_RIGHT:
setFontAlignment(EnhancedTextArea.ALIGN_RIGHT);
break;
default:
setFontAlignment(EnhancedTextArea.ALIGN_LEFT);
break;
}
float li = indent + cf.getLineFormat().getIndentJAVA();
setLeftIndent(li);
setFontColor(cf.getLineFormat().getColor());
setFontBold(cf.getPageBold());
setFontItalic(cf.getPageItalic());
append(line.page + " ");
setFontBold(cf.getLineBold());
setFontItalic(cf.getLineItalic());
append(line.lead);
setFontBold(cf.getWordBold());
setFontItalic(cf.getWordItalic());
append(line.word);
setFontBold(cf.getLineBold());
setFontItalic(cf.getLineItalic());
append(line.trail);
append("\n");
return li;
}
ALL VARIABLES are resolved before get methods

How to get the checkbox value selected from excel sheet

I am working on a task related to reading an excel which contains radio buttons and checkbox using Java, I have tried a lot but can't move further on this, when I am trying to read the data of cell containing Checkbox it is returning a null value.
Can someone please help with this.
Controls are not contained in the cells but hovers in the drawing layer over the sheet as shapes and only are anchored to the cells. So the cell may be null (because of no content in it) although a shape hovers over it and is anchored to it.
Moreover there are two different kinds of controls possible. There are form controls and ActiveX controls. The states of ActiveX controls are stored in binary code parts activeX1.bin and thus getting the state of them is very hard.
In earlier Excel versions (2007 for example) the anchor informations of all controls are stored in /xl/drawings/vmlDrawing1.vml only. Later versions are storing them in default drawing and within
<controls>
<mc:AlternateContent>
...
</mc:AlternateContent>
</controls>
parts in the sheet XML too. Fortunately there is also /xl/drawings/vmlDrawing1.vml for backwards compatibility.
The following code does parsing the /xl/drawings/vmlDrawing1.vml to get the control which is possible anchored to a cell. If found, it gets this control and if this control is a form control and not a ActiveX control, then it also can get it's state. For ActiveX controls it gets only the information, that a "Pict" is anchored to this cell.
Excel:
Code:
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.util.Units;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import javax.xml.namespace.QName;
class ReadExcelXSSFControls {
public ReadExcelXSSFControls() throws Exception {
XSSFWorkbook wb = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelWithControls.xlsx"));
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (int c = 0; c < 2; c++) {
Cell cell = row.getCell(c);
if (row.getRowNum() == 0) {
System.out.print(cell + "\t");
} else {
if (c == 0) {
System.out.print(cell + "\t");
} else if (c == 1) {
if (cell == null) cell = row.createCell(c);
Control contol = getControlAt((XSSFCell)cell);
System.out.print(contol);
}
}
}
System.out.println();
}
wb.close();
}
private Control getControlAt(XSSFCell cell) throws Exception {
XSSFSheet sheet = cell.getSheet();
Row row = cell.getRow();
int r = row.getRowNum();
int c = cell.getColumnIndex();
int drheight = (int)Math.round(sheet.getDefaultRowHeightInPoints() * Units.PIXEL_DPI / Units.POINT_DPI);
int rheight = (int)Math.round(row.getHeightInPoints() * Units.PIXEL_DPI / Units.POINT_DPI);
row = null;
if(r > 0) row = sheet.getRow(r-1);
int rheightbefore = (row!=null)?(int)Math.round(row.getHeightInPoints() * Units.PIXEL_DPI / Units.POINT_DPI):drheight;
row = sheet.getRow(r+1);
int rheightafter = (row!=null)?(int)Math.round(row.getHeightInPoints() * Units.PIXEL_DPI / Units.POINT_DPI):drheight;
String name = null;
String objectType = null;
String checked = null;
XmlCursor xmlcursor = null;
if (sheet.getCTWorksheet().getLegacyDrawing() != null) {
String legacyDrawingId = sheet.getCTWorksheet().getLegacyDrawing().getId();
POIXMLDocumentPart part = sheet.getRelationById(legacyDrawingId);
XmlObject xmlDrawing = XmlObject.Factory.parse(part.getPackagePart().getInputStream());
xmlcursor = xmlDrawing.newCursor();
QName qnameClientData = new QName("urn:schemas-microsoft-com:office:excel", "ClientData", "x");
QName qnameAnchor = new QName("urn:schemas-microsoft-com:office:excel", "Anchor", "x");
boolean controlFound = false;
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameClientData.equals(xmlcursor.getName())) {
controlFound = true;
XmlObject clientdata = xmlcursor.getObject();
XmlObject[] xmlchecked = clientdata.selectPath("declare namespace x='urn:schemas-microsoft-com:office:excel' x:Checked");
if (xmlchecked.length > 0) {
checked = "Checked";
} else {
checked = "Not checked";
}
while (xmlcursor.hasNextToken()) {
tokentype = xmlcursor.toNextToken();
if (tokentype.isAttr()) {
if (new QName("ObjectType").equals(xmlcursor.getName())) {
objectType = xmlcursor.getTextValue();
name = objectType + " in row " + (r+1);
}
} else {
break;
}
}
} else if (qnameAnchor.equals(xmlcursor.getName()) && controlFound) {
controlFound = false;
String anchorContent = xmlcursor.getTextValue().trim();
String[] anchorparts = anchorContent.split(",");
int fromCol = Integer.parseInt(anchorparts[0].trim());
int fromColDx = Integer.parseInt(anchorparts[1].trim());
int fromRow = Integer.parseInt(anchorparts[2].trim());
int fromRowDy = Integer.parseInt(anchorparts[3].trim());
int toCol = Integer.parseInt(anchorparts[4].trim());
int toColDx = Integer.parseInt(anchorparts[5].trim());
int toRow = Integer.parseInt(anchorparts[6].trim());
int toRowDy = Integer.parseInt(anchorparts[7].trim());
if (fromCol == c /*needs only starting into the column*/
&& (fromRow == r || (fromRow == r-1 && fromRowDy > rheightbefore/2f))
&& (toRow == r || (toRow == r+1 && toRowDy < rheightafter/2f))) {
//System.out.print(fromCol + ":" +fromColDx + ":" + fromRow + ":" + fromRowDy + ":" + toCol + ":" + toColDx + ":" + toRow + ":" + toRowDy);
break;
}
}
}
}
}
if (xmlcursor!=null && xmlcursor.hasNextToken())
return new Control(name, objectType, checked, r, c);
return new Control("Not found", "unknown", "undefined", r, c);
}
public static void main(String[] args) throws Exception {
ReadExcelXSSFControls o = new ReadExcelXSSFControls();
}
private class Control {
private String name;
private String objectType;
private String checked;
private int row;
private int col;
public Control(String name, String objectType, String checked, int row, int col) {
this.name = name;
this.objectType = objectType;
this.checked = checked;
this.row = row;
this.col= col;
}
public String getName() {
return this.name;
}
public String getObjectType() {
return this.objectType;
}
public String getChecked() {
return this.checked;
}
public int getRow() {
return this.row;
}
public int getCol() {
return this.col;
}
public String toString() {
return this.name + ":r/c:" +row+ "/" + col + ":" + this.checked;
}
}
}
Result:
axel#arichter:~/Dokumente/JAVA/poi/poi-3.17$ java -cp .:./*:./lib/*:./ooxml-lib/* ReadExcelXSSFControls
Product Status
a Checkbox in row 2:r/c:1/1:Checked
b Not found:r/c:2/1:undefined
c Checkbox in row 4:r/c:3/1:Not checked
d Checkbox in row 5:r/c:4/1:Checked
e Radio in row 6:r/c:5/1:Checked
f Not found:r/c:6/1:undefined
g Not found:r/c:7/1:undefined
e Checkbox in row 9:r/c:8/1:Checked
f Not found:r/c:9/1:undefined
h Radio in row 11:r/c:10/1:Not checked
ActiveX Pict in row 14:r/c:13/1:Not checked

java swing image path

The class is extracted from a game project. Everything works as it should, I can play the game, start a new game, etc. Only the .gif pics are not displayed. Where in my project do I have to store the .gif pics, so that the image path works? I hope the code is understandable.
class Field extends JPanel {
//fields in x direction
static final int max_x = 10;
//fields in y direction
static final int max_y = 10;
//array for field
JLabel[][] label = new JLabel [max_x][max_y];
//home-directory
String img_source = MainWindow.getDirectory();
//separator
String separator = MainWindow.getSeparator();
//stringarray for different viewing direction
String [] viewing_direction = {"player.gif", "player1.gif", "player2.gif", "player3.gif", "player4.gif", null, "player6.gif", "player7.gif", "player8.gif", "player9.gif", "loss.gif", "win.gif"};
//integer for last viewing direction
int viewing_direction_Player = 0;
Field() {
super();
this.setLayout(new GridLayout(max_x, max_y));
//set theme "game"
img_source = img_source + "image" + separator + "Game";
addJLabels();
}
//creates field with alternating background
private void addJLabels() {
for (int i = 0; i < max_y; i++) {
for (int k = 0; k < max_x; k++) {
label[i][k] = new JLabel();
if((i+k) % 2 == 0) { //modulo operation for alternating background
label[i][k].setBackground(Color.BLACK);
}
else {
label[i][k].setBackground(Color.WHITE);
}
label[i][k].setPreferredSize(new Dimension(50, 50));
label[i][k].setOpaque(true);
this.add(label[i][k]);
}
}
}
//method to get last viewing direction
public void setLastDirection(int lastDirection) {
viewing_direction_Player = lastDirection;
}
//method that draws all pawns
public void drawAllPawns(AbstractPawn[] pawns) {
for(int i = 0; i < (int) pawns.length; i++) {
if ((pawns[i].getX() < 0) || (pawns[i].getY() < 0)) {
} else if (pawns[i] instanceof Player) {
label[pawns[i].getY()][pawns[i].getX()].setIcon(new ImageIcon(img_source + separator + viewing_direction[viewing_direction_Player]));
} else if(pawns[i] instanceof Opponent) {
label[pawns[i].getY()][pawns[i].getX()].setIcon(new ImageIcon(img_source + separator + "opponent.gif"));
} else if(pawns[i] instanceof Vortex) {
label[pawns[i].getY()][pawns[i].getX()].setIcon(new ImageIcon(img_source + separator + "vortex.gif"));
} else if(pawns[i] instanceof Obstacle) {
label[pawns[i].getY()][pawns[i].getX()].setIcon(new ImageIcon(img_source + separator + "obstacle.gif"));
} else if(pawns[i] instanceof Destruction) {
label[pawns[i].getY()][pawns[i].getX()].setIcon(new ImageIcon(img_source + separator + "destruction.gif"));
} else if(pawns[i] instanceof Ammo) {
label[pawns[i].getY()][pawns[i].getX()].setIcon(new ImageIcon(img_source + separator + "ammo.gif"));
}
}
}
Here is the getDirectory from my mainwindow class
public static String getDirectory() {
String home = System.getProperty("user.dir");
return (home + getSeparator());
}
Simple way to use image
First drag and drop image in src folder
than type this code
ImageIcon ic = new ImageIcon(getResource().getClass("Example.jpg")); // image name instead of Example.jpg

accessing javascript from inside java

I know that there are lots of examples out there on this, but they all feel a little dated (even the sun docs) so I'm asking here to make sure what I'm doing is up to date. How would I go about talking to javascript from inside a java applet? Something simple like how to call alert() is all I'm looking for. Bonus points for a way to check if the browser has javascript enabled (this applet may be used in a school setting where having javascript turned off is a real possibility). All help is greatly appreciated, thanks in advance...
Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.JSObject;
public class TeamProject extends Applet implements ActionListener, MouseListener {
char[][] charValues = new char[10][10];
Table aTable;
boolean allowUserInput = false;
Button BtnStart;
Button randomChangeBtn;
boolean guessMode;
JSObject jso;
public void init() {
//setup buttons
BtnStart = new Button("add row/column");
BtnStart.addActionListener((ActionListener)this); //cast
randomChangeBtn = new Button("change one value");
randomChangeBtn.addActionListener((ActionListener)this);
//add button
this.add(BtnStart);
//add image to Image objects
Image imgO = getImage(getCodeBase(), "images/not.gif");
Image imgX= getImage(getCodeBase(), "images/cross.gif");
//setup table
aTable = new Table(100, 100, 75, 55, 5, 5, imgX, imgO);
//setBackground(Color.LIGHT_GRAY);
super.resize(700, 700);
//add mouse listener
addMouseListener(this);
//initially guessMode will be false
guessMode = false;
//to talk to javascript
jso = JSObject.getWindow(this);
}
public void paint(Graphics g) {
g.setColor(Color.black);
aTable.draw(g);
}
//Mouse listener methods
public void mousePressed (MouseEvent e) {
if(!guessMode){
if ((allowUserInput)) { //&&(aTable.isDrawable(e.getX(), e.getY())))
aTable.swapSquareValue(e.getX(), e.getY());
repaint();
}
} else {
System.out.println("guessed row = " + e.getY() + " guessed col = " + e.getX());
aTable.checkGuess(e.getX(), e.getY());
//repaint();
}
}
public void mouseClicked (MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseReleased (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
//Button action listener
public void actionPerformed(ActionEvent e) {
if (e.getSource() == BtnStart) {
aTable.addRow();
aTable.addColumn();
this.remove(BtnStart);
this.add(randomChangeBtn);
repaint();
} else if (e.getSource() == randomChangeBtn) {
//aTable.addRow();
aTable.randomChangeFunc();
repaint();
guessMode = true;
}
allowUserInput = true;
System.out.println(aTable.toString());
}
}
and my Table class:
import java.awt.*;
import java.util.Random;
public class Table {
private char[][]values = new char[10][10]; //probably better to use array of integer values(0 or 1)
Image imgO;
Image imgX;
private int Rows;
private int Columns;
private int BoxWidth ;
private int BoxHeight;
public Point Pos = new Point();
private int tableHeight;
private int tableWidth;
private int changedRow;
private int changedCol;
//constructor
public Table(int x, int y, int width, int height, int col, int rows, Image X, Image O) {
Rows = rows;
Columns = col;
BoxWidth = width;
BoxHeight = height;
Pos.x = x;
Pos.y = y;
imgX = X;
imgO = O;
tableHeight = Rows*BoxHeight;
tableWidth = Columns*BoxWidth;
this.setValues();
}
//draw table
public void draw(Graphics g) {
//draw vertical table lines
for (int i = 0 ; i <= Columns ; i++)
g.drawLine(i*BoxWidth + Pos.x, Pos.y, i*BoxWidth + Pos.x, tableHeight+Pos.y);
//draw horizontal table line
for(int i = 0 ; i <= Rows ; i++)
g.drawLine(Pos.x, i*BoxHeight + Pos.y, tableWidth+Pos.x, i*BoxHeight + Pos.y);
//draw values
drawValues(g);
}
public void swapSquareValue(int x, int y) {
if (this.isDrawable(x, y)) {
int col = this.getColumn(x)-1;
int row = this.getRow(y)-1;
if(values[row][col] == 'X')
values[row][col] = 'O';
else if(values[row][col] == 'O')
values[row][col] = 'X';
else
System.out.println("ERROR SWAPPING SQUARE VALUE");
} else
System.out.println("says not drawable");
}
public char getValue(int col, int row) {
return values[row][col];
}
//return true if (x,y) is a point in the table
public boolean isDrawable(int x, int y) {
if((this.getRow(y)!=-1)||(this.getColumn(x)!=-1))
return true;
else
return false;
}
public void addRow() {
Rows++;
tableHeight = (Rows*BoxHeight);
int numOfXs = 0;
for (int c=0; c < Columns; c++) {
numOfXs = 0;
for(int r = 0; r < Rows - 1; r++) {
if(values[r][c] == 'X'){
numOfXs++;
System.out.println("in column " + c + "new x found at " + r + " " + c + ", numOfXs = " + numOfXs);
}
if(numOfXs % 2 == 0) {
values[Rows - 1][c] = 'O';
} else{
values[Rows - 1][c] = 'X';
}
}//end inner for
System.out.println("end of column " + c);
}//end outer for
}// end function
public void addColumn() {
Columns++;
tableWidth = (Columns*BoxWidth);
int numOfXs = 0;
for (int r=0; r < Rows; r++) {
numOfXs = 0;
for(int c = 0; c < Columns - 1; c++) {
if(values[r][c] == 'X') {
numOfXs++;
System.out.println("in row " + r + "new x found at " + r + " " + c + ", numOfXs = " + numOfXs);
}
if(numOfXs % 2 == 0) {
values[r][Columns - 1] = 'O';
}
else {
values[r][Columns - 1] = 'X';
}
}//end inner for
System.out.println("end of row " + r);
}
}
//does not add or remove values
public void setColumn(int col) {
Columns = col;
tableWidth = (Columns*BoxWidth);
}
//does not add or remove values
public void setRows(int row) {
Rows = row;
tableHeight = (row*BoxHeight);
}
public String toString() {
String ValueString = "Displaying charValues[" + Rows + "][" + Columns + "]\n";
for (int r=0; r < Rows; r++) {
for (int c=0; c < Columns; c++) {
ValueString += (char)values[r][c];
}
ValueString += "\n"; //next line
}
return ValueString;
}
private void drawValues(Graphics g) {
Point drawPoint = new Point();
for (int r=0; r < Rows; r++)
for (int c=0; c < Columns; c++) {
drawPoint.x = Pos.x+BoxWidth*c;
drawPoint.y = Pos.y+BoxHeight*r;
//g.setColor(Color.white);
//g.fillRect(drawPoint.x+1, drawPoint.y+1, BoxWidth-1, BoxHeight-1);
if (values[r][c] == 'X') {
g.drawImage(imgX,drawPoint.x+1, drawPoint.y+1, BoxWidth-1, BoxHeight-1, null);
} else {
g.drawImage(imgO,drawPoint.x+1, drawPoint.y+1, BoxWidth-1, BoxHeight-1, null);
}
//System.out.print((char)values[r][c]);
}
g.setColor(Color.black);
}
//fills array with random values
private void setValues() {
for (int r=0; r < Rows; r++)
for (int c=0; c < Columns; c++) {
values[r][c] = this.randomChar();
}
}
//randomly return 'X' or 'O'
private char randomChar() {
char randomValue;
Random RandomGen = new Random();
if (RandomGen.nextInt(2)==0)
randomValue = 'O';
else
randomValue ='X';
return randomValue;
}
private int getColumn(int x) {
int offsetx=0;
for (int i = 0 ; i < Columns ; i++) {
offsetx = i*BoxWidth;
if((x>Pos.x+offsetx)&& (x<Pos.x+offsetx+BoxWidth))
return i+1;
}
return -1;
}
private int getRow(int y) {
int offsety=0;
for (int i = 0 ; i < Rows ; i++) {
offsety = i*BoxHeight;
if((y>Pos.y+offsety)&& (y<Pos.x+offsety+BoxHeight))
return i+1;
}
return -1;
}
public void randomChangeFunc() {
//get random row and column
Random rand=new Random();
int randRow = rand.nextInt(Rows);
int randCol = rand.nextInt(Columns);
System.out.println("randRow = " + randRow + " randCol = " + randCol);
/*THIS SHOULD BE HANDLED BY swapSquareValue(randCol,randRow)
/*BUT GETTING ERRORS (notDrawable). THE FOLLOWING CODE IS A WORK-AROUND
*/
if(values[randRow][randCol] == 'X')
values[randRow][randCol] = 'O';
else if(values[randRow][randCol] == 'O')
values[randRow][randCol] = 'X';
else
System.out.println("ERROR SWAPPING SQUARE VALUE");
//set globals
changedRow = randRow;
changedCol = randCol;
}
public void checkGuess(int guessCol, int guessRow){
int gCol = this.getColumn(guessCol)-1;
int gRow = this.getRow(guessRow)-1;
System.out.println("gCol = " + gCol + " gRow = " + gRow);
if(gCol == changedCol && gRow == changedRow) {
System.out.println("CORRECT!!!");
} else
System.out.println("incorrect :(");
}
}
Changing my javac command to:
javac -classpath /usr/lib/Java6u1/jre/lib/plugin.jar TeamProject.java
ignores my "Table" class and I get errors where I mention that. Any ideas?
Look at this article. If you try calling JS from applet on this page it definitely works, because there are js exception after update action from applet :)
import netscape.javascript.JSObject
public void init()
{
jso = JSObject.getWindow(this);
}
public void actionPerformed(ActionEvent e) {
if(jso != null )
try {
jso.call("updateWebPage", new String[] {txt.getText()});
}
catch (Exception ex) {
ex.printStackTrace();
}
}
EDIT:
For the classpath problem you need to add plugin.jar to your classpath which is located in %JAVA_HOME%\jre\lib\plugin.jar
EDIT2:
I think that your problem is that a class Table isn't compiled too:
try javac -classpath /usr/lib/Java6u1/jre/lib/plugin.jar TeamProject.java Table.java or use wildcards like *.java.
Maybe you should consider use IDE like Eclipse or Netbeans to compile and run project instead of struggling with command line tools.
As requested a sample which calls alert on the page it is embedded in (tested in Opera 10.01, FF 3.5.4, IE6).
Note the MAYSCRIPT in the applet tag, this MUST be present to enable java-javascript communication. As per default access to JSObject is disabled due to security reasons.
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<applet code="HelloWWW.class" width="300px" height="100px" MAYSCRIPT></applet>
</body>
</html>
Java (compile with javac -cp .;[pathtojre]/jre/lib/plugin.jar HelloWWW.java)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import netscape.javascript.*;
public class HelloWWW extends Applet implements ActionListener {
Button runButton;
public void init() {
runButton = new Button("Run: alert(\"Hello WWW\")");
add(runButton);
runButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == runButton) {
try {
//get JSOBject
JSObject jso = JSObject.getWindow(this);
//call alert with parameter passed as Object array
jso.call("alert", new Object[]{"Hello WWW"});
} catch (JSException e) {
e.printStackTrace();
}
runButton.setLabel("Did it!");
repaint();
}
}
}
Also check Java-to-Javascript Communication and Mozilla Dev: JSObject for further info.

Categories