In this code I want to create a 3x3 board game, but nothing appears on the screen..(code compiles correctly but doesn't show output)
I think the problem is in the main method... Can't figure it out... Please help!
package games;
import games.board.*;
public class BoardGameTester {
/**
* #param args
*/
private static Board gb;
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
}
}
Here is a board.java:
package games.board;
public class Board {
private Cell[][] cells;
public Board(int rows, int columns) {
cells = new Cell[rows][columns];
for( int r = 0; r < cells[0].length; r++ ) {
for (int c = 0; c < cells[1].length; c++) {
cells[r][c] = new Cell(r,c);
}
}
}
public void setCell(Mark mark, int row, int column) throws
IllegalArgumentException {
if (cells[row][column].getContent() == Mark.EMPTY)
cells[row][column].setContent(mark);
else throw new IllegalArgumentException("Player already there!");
}
public Cell getCell(int row, int column) {
return cells[row][column];
}
public String toString() {
StringBuilder str = new StringBuilder();
for( int r = 0; r < cells.length; r++ ) {
str.append("|");
for (int c = 0; c < cells[r].length; c++) {
switch(cells[r][c].getContent()) {
case NOUGHT:
str.append("O");
break;
case CROSS:
str.append("X");
break;
case YELLOW:
str.append("Y");
break;
case RED:
str.append("R");
break;
case BLUE:
str.append("B");
break;
case GREEN:
str.append("G");
break;
case MAGENTA:
str.append("M");
break;
case ORANGE:
str.append("M");
break;
default: //Empty
str.append("");
}
str.append("|");
}
str.append("\n");
}
return str.toString();
}
}
Here is a cell.java
package games.board;
public class Cell {
private Mark content;
private int row, column;
public Cell(int row, int column) {
this.row = row;
this.column = column;
content = Mark.EMPTY;
}
public Mark getContent() { return content; }
public void setContent(Mark content) { this.content = content; }
public int getRow() { return row; }
public int getColumn() { return column; }
}
Here is mark.java
package games.board;
public enum Mark {
EMPTY, NOUGHT, CROSS, YELLOW, RED, BLUE, GREEN, MAGENTA, ORANGE
}
Here is outcome.java
package games.board;
public enum Outcome {
PLAYER1_WIN, PLAYER2_WIN, CONTINUE, TIE
}
here is player.java
package games.board;
public enum Player {
FIRST,SECOND
}
you are not genereting any output
to print the board to the console try:
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
System.out.println(gb);
}
it will invoke the gb.toString() methode
ps: it's maybe easier to read if you use str.append("\n") instead of str.append("|")
Try this :
public static void main(String[] args) {
// TODO Auto-generated method stub
gb = new Board(3, 3);
System.out.println(gb.toString());
}
Related
I am trying to make a snake JavaFX game. The scene is a board that consists of 25x25 images. For now, I just want to make the snake go to the right before I add userInput. The first scene is loading from Controller.java and then in Main.java, I am calling run_game() method (inside controller.java) which changes the scene every second. The issue is that the first scene shows up but the scene does not get updated. There is no error, the program just keeps running till I stop it.
Here are the classes:-
Main.java
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Timer;
import java.util.TimerTask;
public class Main extends Application {
public Controller game;
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Snake Game");
game = new Controller();
primaryStage.setScene(game.scene);
primaryStage.show();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
try {
game.run_game();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},0,1000);
}
public static void main(String[] args) { launch(args); }
}
Controller.java
import javafx.animation.AnimationTimer;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import java.util.TimerTask;
public class Controller {
public Snake snake;
public Board board;
public Food food;
public Movement move;
public static GridPane grid_pane;
public Scene scene;
// Creating all the necessary instances of snake game
public Controller() throws InterruptedException {
food = new Food();
grid_pane = new GridPane();
//assigning a random food position to the food apple
assign_random_position_to_food();
snake = new Snake(food);
board = new Board();
move = new Movement(snake);
board.generateBoard(food.row, food.col, snake);
Parent root = grid_pane;
scene = new Scene(root, Board.BOARDHEIGHT,Board.BOARDWIDTH);
}
public void run_game() throws InterruptedException {
snake = move.move_RIGHT();
scene.setRoot( grid_pane);
}
public void assign_board_to_grid(){
for ( int row = 0; row < board.board.length; ++row)
for( int col = 0; col < board.board[row].length; ++col )
grid_pane.add(board.board[row][col], row, col, 1, 1);
}
public void assign_random_position_to_food(){
food.RandomPosition();
}
}
Board.java
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
public class Board {
public static int BOARDHEIGHT = 500;
public static int BOARDWIDTH = 500;
public static int BLOCKHEIGHT = 20;
public static int BLOCKWIDTH = 20;
public static int TOTAL_BLOCKS_ROW = BOARDHEIGHT/ BLOCKHEIGHT;
public static int TOTAL_BLOCKS_COL = BOARDWIDTH/ BLOCKWIDTH;
public ImageView[][] board;
public Image black_square;
public Image apple;
public Image snake_dot;
public GridPane gridPane = new GridPane();
public void assign_images(){
try{
apple = new Image("images/apple.png");
snake_dot = new Image("images/dot.png");
black_square = new Image("images/black_square.png");
}catch(Exception e){
System.out.println("Error: related to the address of images");
}
}
public Board(){
assign_images();
//initializing the board
board = new ImageView[TOTAL_BLOCKS_ROW][TOTAL_BLOCKS_COL];
}
public void generateBoard(int food_x, int food_y, Snake snake_body) {
for(int row=0; row< TOTAL_BLOCKS_ROW; row++){
for(int col=0; col< TOTAL_BLOCKS_COL; col++){
if(row == food_x && col == food_y)// && check if it is not on snake body)
board[row][col] = new ImageView(apple);
else if( snake_body.is_snake_present(row,col) && col != 0)
board[row][col] = new ImageView(snake_dot);
else
board[row][col] = new ImageView(black_square);
// Setting the size of each block on the scene
board[row][col].setFitHeight(BLOCKHEIGHT);
board[row][col].setFitWidth(BLOCKWIDTH);
Controller.grid_pane.add(board[row][col], row, col, 1 ,1);
}
}
}
}
Movement.java
public class Movement {
public Snake snake;
public static int new_y_position;
public static int new_x_position;
public Movement(Snake snake){
this.snake = snake;
}
public Snake move_RIGHT(){
new_x_position = snake.getHead_x() + 1;
new_y_position = snake.getHead_y();
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//System.out.println(new_x_position);
snake.setHead_x(new_x_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setX(b.getX() + 1);
snake.snake.set(i,b);
}
// System.out.println(snake);
return snake;
}
public Snake move_LEFT(){
new_x_position = snake.getHead_x() - 1;
new_y_position = snake.getHead_y();
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//snake is inbounds update position
snake.setHead_x(new_x_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setX(b.getX() - 1);
snake.snake.set(i,b);
}
System.out.println(snake);
return snake;
}
public Snake move_UP(){
new_x_position = snake.getHead_x();
new_y_position = snake.getHead_y() + 1;
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//snake is inbounds update position
snake.setHead_y(new_y_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setY(b.getY() + 1);
snake.snake.set(i,b);
}
System.out.println(snake);
return snake;
}
public Snake move_DOWN(){
new_x_position = snake.getHead_x();
new_y_position = snake.getHead_y() - 1;
if(!check_if_snake_is_in_bounds(new_x_position, new_y_position))
return null;
//snake is inbounds update position
snake.setHead_y(new_y_position);
Block b;
for (int i = snake.snake.size() - 1; i >= 0; --i){
b = snake.snake.get(i);
b.setY(b.getY() - 1);
snake.snake.set(i,b);
}
System.out.println(snake);
return snake;
}
public boolean check_if_snake_is_in_bounds(int x, int y){
return x >= 0 && x <= Board.TOTAL_BLOCKS_COL && y >= 0 && y <= Board.TOTAL_BLOCKS_ROW;
}
}
Snake.java
import java.util.ArrayList;
public class Snake {
public ArrayList<Block> snake = new ArrayList<>();
public int snake_size = snake.size();
int head_x, head_y;
public Snake(Food food){
// initializes a snake head location on board and stores it in a list.
do{
head_x = (int) (Math.random()*Board.TOTAL_BLOCKS_COL);
head_y = (int) (Math.random()*Board.TOTAL_BLOCKS_ROW);
}while(food.getRow() == head_x || food.getCol() == head_y);
//inserting head and a block in snake arraylist
snake.add(new Block(head_x, head_y));
snake.add(new Block(head_x - 1, head_y));
}
// Adds new body part when snake eats an apple.
public void add_snake_body() {
snake.add( retrieve_new_block_position() );
}
// gets new snake body part position.
public Block retrieve_new_block_position(){
int last_block_x = snake.get(snake_size - 1).getX();
int last_block_y = snake.get(snake_size - 1).getY();
int second_last_block_x = snake.get(snake_size - 2).getX();
int second_last_block_y = snake.get(snake_size - 2).getY();
int new_block_x;
int new_block_y;
if(second_last_block_x == last_block_x){
new_block_x = last_block_x;
new_block_y = last_block_y - 1;
}
else{
new_block_x = last_block_x - 1;
new_block_y = last_block_y;
}
return new Block(new_block_x, new_block_y);
}
//checks if a position is occupied by a snake body part.
public boolean is_snake_present(int row, int col){
int index = 0;
int snake_curr_block_x;
int snake_curr_block_y;
while(index < snake.size()){
snake_curr_block_x = snake.get(index).getX();
snake_curr_block_y = snake.get(index).getY();
if( snake_curr_block_x == row && snake_curr_block_y == col)
return true;
index++;
}
return false;
}
//GETTER & SETTER METHODS
public ArrayList<Block> getSnake() {
return snake;
}
public int getHead_x() {
return head_x;
}
public void setHead_x(int head_x) {
this.head_x = head_x;
}
public int getHead_y() {
return head_y;
}
public void setHead_y(int head_y) {
this.head_y = head_y;
}
}
Food.java
import java.util.Random;
public class Food {
int row;
int col;
public Food(){
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
public void RandomPosition(){
this.row = (int) (Math.random() * Board.TOTAL_BLOCKS_ROW);
this.col = (int) (Math.random() * Board.TOTAL_BLOCKS_COL);
System.out.println(this.row+" -food- "+ this.col);
//need to check if it clashes with the snake body................
}
}
Block.java
public class Block {
private int x;
private int y;
public Block(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
I am attempting to create a Java applet, and yes, I know, deprecated, blah blah blah, I have my reasons. I cannot seem to get the file to load for any reason via either placing it on my website or by using an HTML file to load it locally. Any help in this matter would be most appreciated, as this is frustrating me to no end.
<html>
<head>
<title>
Applet
</title>
</head>
<body>
<h2>Applet</h2>
<embed
archive="eloRating.jar"
code="eloRatingSystem"
width=550 height=300>
This means you done goofed
</applet>
</body>
</html>
.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.ArrayList;
#SuppressWarnings("serial")
public class eloRatingSystem extends JApplet /*implements Runnable*/{
/*****************************************************************************/
private static final int BUTTON_HEIGHT = 50;
private static final int BUTTON_WIDTH = 150;
/*****************************************************************************/
private Button newPlayer, editPlayer, editTeams, commitMatch, downloadBook;
private JButton editPopUp;
/*****************************************************************************/
private JComponent[] inputs;
private JComponent[] tables;
/*****************************************************************************/
private int testRow;
private int playerCounter;
/*****************************************************************************/
private ArrayList<Player> pList;
/*****************************************************************************/
private String[] titles;
/*****************************************************************************/
private ListenForAction lForAction;
/*****************************************************************************/
private modifyExcel book;
/*****************************************************************************/
private JPanel panel;
/*****************************************************************************/
private JTable playerTable;
/*****************************************************************************/
private TableRowSorter<?> sorter;
/*****************************************************************************/
Dimension d;
/*****************************************************************************/
/*****************************Initialization**********************************/
public void init() {
inputs = new JComponent[]{
new JLabel("Enter The Player's Name"),
};
testRow = 10000;
playerCounter = 0;
lForAction = new ListenForAction();
book = new modifyExcel();
book.openExcel();
titles = new String[6];
panel = new JPanel();
pList = new ArrayList<Player>();
d = new Dimension(500,140);
titles = book.setTitles();
/*DEBUG
JOptionPane.showMessageDialog(null, titles[0] + titles[1] + titles[2] + titles[3] + titles[4] + titles[5], "Work", JOptionPane.PLAIN_MESSAGE);
*/
editPopUp = new JButton("Edit Player");
newPlayer = new Button("Add Player");
editPlayer = new Button("Edit Player");
editTeams = new Button("Edit Teams");
commitMatch = new Button("Commit Match");
downloadBook = new Button("Download Excel File");
setLayout(null);
//editPopUp.setBounds(0,0,BUTTON_WIDTH,BUTTON_HEIGHT);
newPlayer.setBounds(75, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
editPlayer.setBounds(235, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
editTeams.setBounds(395, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
commitMatch.setBounds(555, 180, BUTTON_WIDTH, BUTTON_HEIGHT);
panel.add(editPopUp);
newPlayer.addActionListener(lForAction);
editPlayer.addActionListener(lForAction);
editPopUp.addActionListener(lForAction);
initPlayers(book.getRows());
//System.out.println(pList[4].getName());
tables = new JComponent[]{
new JScrollPane(playerTable = new JTable(new MyTableModel(pList))),
panel
};
playerTable.setAutoCreateRowSorter(true);
createSorter();
add(newPlayer);
add(editPlayer);
add(editTeams);
add(commitMatch);
this.setBackground(Color.BLACK);
this.setVisible(true);
}
public void start() {
}
public void destroy() {
}
public void stop() {
}
public void paint(Graphics g){
}
public void run() {
this.setVisible(true);
}
/*****************************Initialize Players*************************************
* This function calls for a read in of all players and data listed
* inside of an excel spreadsheet. The players are added to an Array
* List for easy access and dynamic storage capabilities. *
/************************************************************************************/
public void initPlayers(int i){
for(int x = 0; x < (i-1); x++){
//System.out.println("Made it Here");
pList.add(book.setPlayer((x+1)));
/*DEBUG
JOptionPane.showMessageDialog(null, pList[x].getName());
*/
}
playerCounter = (book.getRows()-1);
}
/***************************************************************************************
* This function defines an Action Listener for defining button activity
* The buttons all refer to this listener to create their functionality
***************************************************************************************/
public class ListenForAction implements ActionListener{
String S;
int active = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newPlayer){
S = JOptionPane.showInputDialog(null, inputs, "Add New Player", JOptionPane.PLAIN_MESSAGE);
if (S != null){
addPlayer(S);
}
/*DEBUG
JOptionPane.showMessageDialog(null, pList[playerCounter - 1].getName());
pList[0].setElo(2300);
pList[0].calculateElo(6, "LOSE");
JOptionPane.showMessageDialog(null, pList[0].getElo());
*/
} else if (e.getSource() == editPlayer){
JOptionPane.showOptionDialog(null, tables, "Edit Player Info", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
} else if (e.getSource() == editPopUp){
if (active == 0) {
editPopUp.setText("Stop Editing");
testRow = playerTable.getSelectedRow();
active = 1;
} else {
editPopUp.setText("Edit Player");
testRow = 1000000;
active = 0;
}
}
}
}
/************************************************************************************
* Custom Table Model to allow for a list of editable size and data
* The players are stored read into this via the Array List and the
* Data is displayed in a list that can be sorted by column.
*************************************************************************************/
private class MyTableModel extends AbstractTableModel {
ArrayList<Player> list = null;
MyTableModel(ArrayList<Player> list) {
this.list = list;
}
public int getColumnCount() {
return titles.length;
}
public int getRowCount() {
return list.size();
}
public String getColumnName(int col) {
return titles[col];
}
public void setValueAt(Object value, int row, int col){
switch(col) {
case 0:
pList.get(row).setName((String)value);
break;
case 1:
pList.get(row).setElo((Integer)value);
break;
case 2:
pList.get(row).setAttendance((Integer)value);
break;
case 3:
pList.get(row).setMVP((Integer)value);
break;
case 4:
pList.get(row).setWins((Integer)value);
break;
case 5:
pList.get(row).setLose((Integer)value);
break;
}
System.out.println(pList.get(row).getName() + pList.get(row).getAttendance());
}
public boolean isCellEditable(int row, int column)
{
//System.out.println(Flag);
if(testRow == playerTable.getSelectedRow()){
return true;
} else {
return false;
}
}
public Object getValueAt(int row, int col) {
Player object = list.get(row);
switch (col) {
case 0:
return object.getName();
case 1:
return object.getElo();
case 2:
return object.getAttendance();
case 3:
return object.getMVP();
case 4:
return object.getWin();
case 5:
return object.getLose();
default:
return "unknown";
}
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
private void addPlayer(String S){
pList.add(new Player(S));
tables = new JComponent[]{
new JScrollPane(playerTable = new JTable(new MyTableModel(pList))),
panel
};
playerCounter++;
createSorter();
}
public void createSorter(){
playerTable.setPreferredScrollableViewportSize(d);
playerTable.setAutoResizeMode(getHeight());
playerTable.setAutoCreateRowSorter(true);
sorter = (TableRowSorter<?>)playerTable.getRowSorter();
sorter.setRowFilter(new RowFilter<TableModel, Integer>(){
#Override
public boolean include(RowFilter.Entry<? extends TableModel, ? extends Integer> entry){
boolean included = true;
Object cellValue = entry.getModel().getValueAt(entry.getIdentifier(), 0);
if(cellValue == null || cellValue.toString().trim().isEmpty()){
included = false;
}
return included;
}
});
}
}
.
public class Player {
private String Name;
private int Elo = 1600, Attendance = 0, MVP = 0, Win = 0, Lose = 0;
public Player(String n, int e, int a, int m, int w, int l){
Name = n;
Elo = e;
Attendance = a;
MVP = m;
Win = w;
Lose = l;
}
public Player(String n){
Name = n;
}
public Player() {
}
/***********************************************/
public void setName(String n){
Name = n;
}
public void setElo(int e){
Elo = e;
}
public void setAttendance(int a){
Attendance = a;
}
public void setMVP(int m){
MVP = m;
}
public void setWins(int w){
Win = w;
}
public void setLose(int l){
Lose = l;
}
/************************************************/
public void addAttendance(int e){
Attendance += e;
}
public void addElo(int e){
Elo += e;
}
public void addMVP(int e){
MVP += e;
}
public void addWins(int e){
Win += e;
}
public void addLose(int e){
Lose += e;
}
/************************************************/
public void calculateElo(int oE, String win){
double tRatingP; //holds the players transformed Elo Rating for calculation
double tRatingO; //holds the opponents transformed Elo Rating for calculation
double expectedP; //Players expected score
double pointP = 0;
int eloValue = 32; //default elo value
if (Elo > 2400){
eloValue = 24;
}
switch(win){
case "WIN": pointP = 1;
break;
case "DRAW": pointP = 0.5;
break;
case "LOSE": pointP = 0;
break;
}
tRatingP = 10^(Elo/400);
tRatingO = 10^(oE/400);
expectedP = tRatingP/(tRatingP+tRatingO);
this.setElo((int)Math.round(Elo + (eloValue*(pointP-expectedP))));
}
/************************************************/
public String getName(){
return Name;
}
public int getElo(){
return Elo;
}
public int getAttendance(){
return Attendance;
}
public int getMVP(){
return MVP;
}
public int getWin(){
return Win;
}
public int getLose(){
return Lose;
}
}
.
import java.io.File;
import java.util.Date;
import jxl.*;
import jxl.write.*;
public class modifyExcel {
private Player pHolder;
private String[] tHolder = new String[6];
private Workbook eloBook;
Sheet sheet;
public void openExcel(){
try {
eloBook = Workbook.getWorkbook(new File("./eloSpreadsheet.xls"));
} catch(Exception e){
throw new Error(e);
}
sheet = eloBook.getSheet(0);
}
public void appendExcel(Player p){
}
public String[] setTitles(){
for(int x = 0; x<=5; x++){
tHolder[x] = sheet.getCell(x, 0).getContents();
}
return(tHolder);
}
public Player setPlayer(int i){
//System.out.println("Made it Here " + i);
pHolder = new Player();
pHolder.setName(sheet.getCell(0, i).getContents());
pHolder.setElo(Integer.parseInt(sheet.getCell(1, i).getContents()));
pHolder.setAttendance(Integer.parseInt(sheet.getCell(2, i).getContents()));
pHolder.setMVP(Integer.parseInt(sheet.getCell(3, i).getContents()));
pHolder.setWins(Integer.parseInt(sheet.getCell(4, i).getContents()));
pHolder.setLose(Integer.parseInt(sheet.getCell(5, i).getContents()));
return(pHolder);
}
public int getRows(){
return(sheet.getRows());
}
}
For further information, I cannot even get the java console to appear which I assume means the applet is not loading at all.
You have incorrect ending of "embed" tag. It should be:
</embed>
instead:
</applet>
I have a JTable that is used to capture user input which later will be printed upon hitting the Print button. I have an image that I would want to be the header and another one to be a footer.an image showing this can be found here. I have followed the example that I found from oracle documents here. I want it exactly the way it is done in TablePrintdemo3 here.
Allow me to post the classes here.
Here is my first class:
public class Product {
String productDescription;
Double productPrice;
//dummy properties
Integer productQuantity;
Double productTotalAmount;
public Product() {
this.productDescription = "";
this.productPrice = 0.0;
this.productTotalAmount = 0.0;
this.productQuantity = 0;
}//getters and setters here
}
The second class is a custom model as shown here:
public class ProductTableModel extends AbstractTableModel {
private final List<String> columnNames;
private final List<Product> products;
public ProductTableModel() {
String[] header = new String[] {
"Quantity",
"Description",
"Unity Price",
"Total Price"
};
this.columnNames = Arrays.asList(header);
this.products = new ArrayList<>();
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0: return Integer.class;
case 1: return String.class;
case 2: return Double.class;
case 3: return Double.class;
default: throw new ArrayIndexOutOfBoundsException(columnIndex);
}
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Product product = this.getProduct(rowIndex);
switch (columnIndex) {
case 0: return product.getProductQuantity();
case 1: return product.getProductDescription();
case 2: return product.getProductPrice();
case 3: return product.getProductTotalAmount();
default: throw new ArrayIndexOutOfBoundsException(columnIndex);
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex < 0 || columnIndex >= getColumnCount()) {
throw new ArrayIndexOutOfBoundsException(columnIndex);
} else {
Product product = this.getProduct(rowIndex);
switch (columnIndex) {
case 0: product.setProductQuantity((Integer)aValue); break;
case 1: product.setProductDescription((String)aValue); break;
case 2: product.setProductPrice((Double)aValue); break;
case 3: product.setProductTotalAmount((Double)aValue); break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
}
#Override
public int getRowCount() {
return this.products.size();
}
#Override
public int getColumnCount() {
return this.columnNames.size();
}
#Override
public String getColumnName(int columnIndex) {
return this.columnNames.get(columnIndex);
}
public void setColumnNames(List<String> columnNames) {
if (columnNames != null) {
this.columnNames.clear();
this.columnNames.addAll(columnNames);
fireTableStructureChanged();
}
}
public List<String> getColumnNames() {
return Collections.unmodifiableList(this.columnNames);
}
public void addProducts(Product product) {
int rowIndex = this.products.size();
this.products.add(product);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void addProducts(List<Product> productList) {
if (!productList.isEmpty()) {
int firstRow = this.products.size();
this.products.addAll(productList);
int lastRow = this.products.size() - 1;
fireTableRowsInserted(firstRow, lastRow);
}
}
public void addEmptyRow(){
products.add(new Product());
this.fireTableRowsInserted(products.size()-1, products.size()-1);
}
public void insertProduct(Product product, int rowIndex) {
this.products.add(rowIndex, product);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void deleteProduct(int rowIndex) {
if (this.products.remove(this.products.get(rowIndex))) {
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
public Product getProduct(int rowIndex) {
return this.products.get(rowIndex);
}
public List<Product> getProducts() {
return Collections.unmodifiableList(this.products);
}
public void clearTableModelData() {
if (!this.products.isEmpty()) {
int lastRow = products.size() - 1;
this.products.clear();
fireTableRowsDeleted(0, lastRow);
}
}
}
The third class is my is as follows:
public class NiceTablePrinting extends MainClass{
#Override
protected JTable initializeTable(TableModel model) {
return new NicePrintingJTable(model);
}
private static class NicePrintingJTable extends JTable {
public NicePrintingJTable(TableModel model) {
super(model);
}
/**
* Overridden to return a fancier printable, that wraps the default.
* Ignores the given header and footer. Renders its own header.Always
* uses the page number as the footer.
*/
#Override
public Printable getPrintable(PrintMode printMode,
MessageFormat headerFormat,
MessageFormat footerFormat) {
MessageFormat pageNumber = new MessageFormat("- {0} -");
/* Fetch the default printable */
Printable delegate = per.getPrintable(printMode,null,pageNumber);
/* Return a fancy printable that wraps the default */
return new NicePrintable(delegate);
}
}
private static class NicePrintable implements Printable {
Printable delegate;
//
BufferedImage header;
BufferedImage footer;
//
boolean imagesLoaded;
{
try{
header=ImageIO.read(getClass().getResource("images/header.PNG"));
footer=ImageIO.read(getClass().getResource("images/footer.PNG"));
imagesLoaded=true;
}
catch(IOException ex)
{
ex.printStackTrace();
}
imagesLoaded=false;
}
public NicePrintable(Printable delegate) {
this.delegate = delegate;
}
#Override
public int print(Graphicsg,PageFormatpf,intpi)throwsPrinterException
{
if(!imagesLoaded){
return delegate.print(g, pf, pi);
}
//top origin
int x=(int)pf.getImageableX();
int y=(int)pf.getImageableY();
//
int iw=(int)pf.getImageableWidth();
int ih=(int)pf.getImageableHeight();
//image header
int hh= header.getHeight();
int hw=header.getWidth();
//image footer
int fh=footer.getHeight();
int fw=footer.getWidth();
int fY=ih-fh-10;
int fX=x;
//calculating the area to print the table
int tableX=10;
int tableY=hh +10;
int tableW=iw-20;
int tableH=ih-hh-10-fh-10;
/* create a new page format representing the shrunken area to print the table into */
PageFormat format = new PageFormat() {
#Override
public double getImageableX() {return tableX;}
#Override
public double getImageableY() {return tableY;}
#Override
public double getImageableWidth() {return tableW;}
#Override
public double getImageableHeight() {return tableH;}
};
/*
* We'll use a copy of the graphics to print the table to. This protects
* us against changes that the delegate printable could make to the graphics
* object.
*/
Graphics gCopy = g.create();
/* print the table into the shrunken area */
int retVal = delegate.print(gCopy, format, pi);
/* if there's no pages left, return */
if (retVal == NO_SUCH_PAGE) {
return retVal;
}
/* dispose of the graphics copy */
gCopy.dispose();
//draw the images
g.drawImage(header, x, y, hw, hh, null);
g.drawImage(footer, fX, fY, fw, fh, null);
return Printable.PAGE_EXISTS;
}
}
}
The fourth class is as follows:
public class MainClass {
private JTable table;
JFrame frame;
JButton print;
JScrollPane sp;
ProductTableModel model;
public MainClass(){
frame= new JFrame("Test Printing");
frame.setLayout(new java.awt.BorderLayout());
frame.setVisible(true);
///create table
model=new ProductTableModel();
table=this.initializeTable(model);
model.addEmptyRow();
table.setPreferredScrollableViewportSize(newjava.awt.Dimension(300,300));
sp= new javax.swing.JScrollPane(table);
frame.add(sp);
//button
print= new JButton("Print");
frame.add(print,BorderLayout.SOUTH);
frame.pack();
print.addActionListener((ActionEvent e) -> {
try {
printTable();
} catch (PrinterException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
protected JTable initializeTable(TableModel model) {
return new JTable(model);
}
public void printTable() throws PrinterException {
table.print(JTable.PrintMode.NORMAL, null, null, true, null, true);
}
public static void main(String [] args){
MainClass cl= new MainClass();
}
}
I would want to set my things the way it is done in TablePrintdemo3. Now I cannot see where I have gone wrong. Please assist.
The problem is it is printing only the table -no header and footer images.
I'm trying draw some objects in an opengl world . these objects have transparency so. and when I rotate them the transparency doesn't blend color .
How can I sort the draw order, so I can draw from more distant object to closest?
I've tryed with bounding box and get the more distance point .
then sort objects with a bubblesort. Then I give to Renderer the IndexArray sorted.
This is Bounding box.
public class BoundingBox extends java.lang.Object {
private UlVertexBuffer mVb=null;
private UlIndexBuffer mIb=null;
private UlTransform mTransform=null;
private UlVertexBuffer subsetVertexBuffer;
private UlMatrix4x4[] mM=new UlMatrix4x4[2];
private float array[][]=new float[2][16];
private float minX,minY,minZ,maxX,maxY,maxZ=0; // min and max value of the vector components
public BoundingBox (UlVertexBuffer vb, UlIndexBuffer ib)
{
FloatBuffer fb =(FloatBuffer) vb.getData(UlVertexBuffer.VERTEX_FIELD_POSITION).position(0);
float [] fa = new float [fb.capacity()];
fb.get(fa);
ShortBuffer sb = (ShortBuffer)ib.getData();
short [] sa = new short[sb.capacity()];
sb.get(sa);
calcBox(fa,sa);
mM[0]=new UlMatrix4x4(array[0]);
mM[1]=new UlMatrix4x4(array[1]);
}
public void calcBox(UlVertexBuffer vb, UlIndexBuffer ib)
{
FloatBuffer fb =(FloatBuffer) vb.getData(UlVertexBuffer.VERTEX_FIELD_POSITION).position(0);
float [] fa = new float [fb.capacity()];
fb.get(fa);
ShortBuffer sb = (ShortBuffer)ib.getData();
short [] sa = new short[sb.capacity()];
sb.get(sa);
calcBox(fa,sa);
}
public void calcBox(float[] vertexArray,short[] indexArray)
{
for(int j=0;j<indexArray.length ;j++)
{
short i=(short) (indexArray[j]*3);
if(vertexArray[i]>maxX)
{
maxX=vertexArray[i];
}
if(vertexArray[i]<minX)
{
minX=vertexArray[i];
}
if(vertexArray[i+1]>maxY)
{
maxY=vertexArray[i+1];
}
if(vertexArray[i]<minY)
{
minY=vertexArray[i+1];
}
if(vertexArray[i+2]>maxZ)
{
maxZ=vertexArray[i+2];
}
if(vertexArray[i+2]<minZ)
{
minZ=vertexArray[i+2];
}
}
array[0][0]=minX;
array[0][5]=minY;
array[0][10]=minZ;
array[0][15]=1;
array[1][0]=maxX;
array[1][5]=maxY;
array[1][10]=maxZ;
array[1][15]=1;
}
public float[][] getBoundingBox()
{
return array;
}
public UlMatrix4x4 matrixBox(int index)
{
if(mM[0]==null||mM[1]==null){
mM[0]= new UlMatrix4x4(array[0]);
mM[1]= new UlMatrix4x4(array[1]);
}
return mM[index];
}
public UlVector3 getVertex(int Index)
{
UlVector3 vertex=null;
switch (Index)
{
case 0:
vertex.set(array[0][0], array[0][1], array[0][2]);
break;
case 1:
vertex.set(array[1][0], array[0][1], array[0][2]);
break;
case 2:
vertex.set(array[1][0], array[0][1], array[1][2]);
break;
case 3:
vertex.set(array[0][0], array[0][1], array[1][2]);
break;
case 4:
vertex.set(array[0][0], array[1][1], array[0][2]);
break;
case 5:
vertex.set(array[1][0], array[1][1], array[0][2]);
break;
case 6:
vertex.set(array[1][0], array[1][1], array[1][2]);
break;
case 7:
vertex.set(array[0][0], array[1][1], array[1][2]);
break;
}
return vertex;
}
public float getMaxDistance(UlVector3 P1)
{float Mdistance=getDistance(P1, getVertex(0));
for(int i=1; i<8;i++)
{
if(Mdistance<getDistance(P1, getVertex(i)))
{
Mdistance=getDistance(P1, getVertex(i));
}
}
return Mdistance;
}
private float getDistance(UlVector3 P1,UlVector3 P2)
{
float distance =0;
float dx=P2.getX()-P1.getX();
float dy=P2.getY()-P1.getY();
float dz=P2.getZ()-P1.getZ();
return (float) Math.sqrt(dx*dx+dy*dy+dz*dz);
}
public void reverseMatrix()
{
array[0]=mM[0].toArray();
array[1]=mM[1].toArray();
}
}
this is the DrawUnscrambler
public class DrawUnscrambler {
private UlVector3 mCamPos=null;
private UlMesh mMesh= null;
private UlSubset mSubsets[]=null;
private int mIndex[]=null;
private boolean sorted=false;
public UlVector3 getmCamPos() {
return mCamPos;
}
public void setmCamPos(UlVector3 mCamPos) {
this.mCamPos = mCamPos;
}
public UlMesh getmMesh() {
return mMesh;
}
public void setmMesh(UlMesh mMesh) {
this.mMesh = mMesh;
}
public UlSubset[] getmSubsets() {
return mSubsets;
}
public void setmSubsets(UlSubset[] mSubsets) {
this.mSubsets = mSubsets;
}
public int[] getmIndex() {
return mIndex;
}
public void setmIndex(int[] mIndex) {
this.mIndex = mIndex;
}
public DrawUnscrambler(UlMesh mesh,UlVector3 CamPosition)
{
mMesh=mesh;
setmCamPos(CamPosition);
initIndex();
getSubset();
SubsetSort();
}
private void getSubset()
{mSubsets= new UlSubset[mMesh.subsetCount()];
for(int i =0 ; i <mMesh.subsetCount()-1;i++ )
{
mSubsets[i]=mMesh.getSubset(i);
}
}
private void initIndex()
{
mIndex= new int[mMesh.subsetCount()];
for(int i =0 ; i <=mMesh.subsetCount()-1;i++)
{
mIndex[i]=i;
}
}
private void SubsetSort()
{
for(int i =0; i <mMesh.subsetCount()-1;i++)
{
for(int j=0;j<mMesh.subsetCount()-2-i;j++)
{// controlla qui
if(mSubsets[mIndex[j]].getmBoundingBox().getMaxDistance(mCamPos)<mSubsets[mIndex[j+1]].getmBoundingBox().getMaxDistance(mCamPos))
{
int t=mIndex[j];
mIndex[j]=mIndex[j+1];
mIndex[j+1]=t;
}
}
}
sorted=true;
}
public int getSubsetIndex(int i)
{
if(sorted)
{
return mIndex[i];
}
else
{
if(mMesh!=null)
{
initIndex();
getSubset();
SubsetSort();
}
}
return mIndex[i];
}
}
The indexArray is the array sorted that is passed to Renderer in draw function
but it's don't change draw order. How can I do it?
What I am trying to do is solving the 8 queen problem to produce 1 solution. I am trying to do this using BFS. Below is what I have done so far. I think all my functions/methods are all correct apart from the final method() which I can't get to work. If I compile and run the following code, I get a NullPointerException. Wondering how I can overcome this problem and get it to work.
public class Queens
{
//Number of rows or columns
public int[][] board; // creating a two dimentional array
public int Queen = 1;
//Indicate an empty square
public boolean Conflict(int row, int col)
{
int[ ][ ]board = new int[8][8];
int row1;
int col1;
boolean flg = false;
row1 = row;
col1 = col;
// check right
while(row1<8)
{
if(board[row1][col1]==1)
{
row1++;
}
}
//check left
while(row1>=0)
{
if(board[row1][col1]==1)
{
row1--;
}
}
// check down
while(col1<8)
{
if(board[row1][col1]==1)
{
col1++;
}
}
// check up
while(col1>1)
{
if (board[row1][col1]==1)
{
col1--;
}
}
//dia-down-right
while(row1<8 && col1<8){
if(board[row1][col1]==1)
{
row1++;
col1++;
}
}
//dia-down-left
while(row1>=0 && col1<8){
if(board[row1][col1]==1)
row1--;
col1++;
}
//dia-up-left
while(row1>=0 && col1>=0){
if(board[row1][col1]==1)
row1--;
col1--;
}
//dia-up-right
while(row1<8 && col1>=0){
if(board[row1][col1]==1)
row1++;
col1--;
}
return flg;
}
public void disp()
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
System.out.println(board[j][i]);
}
//System.out.println(board[j][i]);
}
}
public void init()
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
board[i][j] = 0;
}
}
}
public void placeQueen(int x,int y)
{
board[x][y]= Queen;
Queen++;
}
public void method()
{
int x,y;
int initx=0;
int inity=0;
Queen=0;
init();
placeQueen(initx,inity);
y=0;
while(y<8)
{
x=0;
while(x<8)
{
if(!Conflict(x,y))
{
placeQueen(x,y);
x++;
}
}
y++;
}
if(Queen<8){
if(initx+1<8)
{
initx++;
disp();
}
else
{
initx=0;
if(inity+1<8)
{
inity++;
}
else{
disp();
}
}
}
}
public static void main(String[] args)
{
Queens Main = new Queens();
Main.method();
}
}
You need to initialize the board on line 5, otherwise when called in init board:
board[i][j] = 0;
board[i][j] is null
public class Queens
{
//Number of rows or columns
public int[][] board = new int[8][8]; // creating a two dimentional array
public int Queen = 1;