Here is my code and I am trying to get this cat to move with a, s, w, d and this box to move with the arrow keys. I was using switch case statements and the box works, but not the cat. I am new to programming and I really need help. Do I need to use key bindings instead?:
public class Other extends Applet implements ActionListener, KeyListener {
public static final int MOVE_STOP = 0;
public static final int MOVE_UP = 1;
public static final int MOVE_DOWN = 2;
public static final int MOVE_RIGHT = 3;
public static final int MOVE_LEFT = 4;
public static final int MOVE_W = 5;
public static final int MOVE_S = 6;
public static final int MOVE_D = 7;
public static final int MOVE_A = 8;
int CursorDirection = MOVE_STOP;
int cursordirection = MOVE_STOP;
private ArrayList<Integer> keysDown;
public void init()
{
this.addKeyListener(this);
keysDown = new ArrayList<Integer>();
rect = new Rectangle(1000, 715, 35, 35);
}
public void paint(Graphics g){
setSize(2000, 2000);
this.CalculateMappyPosition();
//i edited the background out
}
#Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode()))
keysDown.add(new Integer(e.getKeyCode()));
moveRect();
}
#Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
public void CalculateMappyPosition() {
switch (CursorDirection) {
case MOVE_UP:
rect.y-= 100;
break;
case MOVE_DOWN:
rect.y+= 100;
break;
case MOVE_LEFT:
rect.x-= 5;
break;
case MOVE_RIGHT:
rect.x+= 5;
break;
case MOVE_A:
cat.x1-= 5;
break;
case MOVE_S:
cat.y1+= 100;
break;
case MOVE_D:
cat.x1+= 5;
break;
case MOVE_W:
cat.y1-= 100;
break;
default:
break;
}
}
public void moveRect()
{
repaint();
if(keysDown.contains(KeyEvent.VK_UP))
up();
}
if (keysDown.contains(KeyEvent.VK_DOWN))
down();
}
if(keysDown.contains(KeyEvent.VK_LEFT))
left();
}
if(keysDown.contains(KeyEvent.VK_RIGHT))
right();
}
if(keysDown.contains(KeyEvent.VK_A)){
a();
}
if(keysDown.contains(KeyEvent.VK_S)){
s();
}
if(keysDown.contains(KeyEvent.VK_D)){
}
if(keysDown.contains(KeyEvent.VK_W)){
w();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
public void up(){
CursorDirection = MOVE_UP;
}
public void down(){
CursorDirection = MOVE_DOWN;
}
public void left(){
CursorDirection = MOVE_LEFT;
}
public void right(){
CursorDirection = MOVE_RIGHT;
}
public void a(){
CursorDirection = MOVE_A;
}
public void s(){
CursorDirection = MOVE_S;
}
public void d(){
CursorDirection = MOVE_D;
}
public void w(){
CursorDirection = MOVE_W;
}
}
Related
I am trying to create a walking animation. It should alternate between playerLeft and playerLeftWalk. The code is shown below:
public class MyClass extends JPanel implements ActionListener, KeyListener{
protected Timer tm = new Timer(10, this);
protected Clip clip;
protected Image background, playerSprite, playerLeft, playerLeftWalk;
protected int mapdx = 0;
protected int mapdy = 0;
protected int mapX = 0;
protected int mapY = 0;
protected int playerX = 1060;
protected int playerY = 2800;
protected volatile boolean activeThread;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.background, this.mapX + this.mapdx, this.mapY - this.mapdy, this);
g.drawImage(this.playerSprite, this.playerX, this.playerY, this);
}
#Override
public void actionPerformed(ActionEvent e) {
mapX += mapdx;
mapY += mapdy;
this.repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
Thread playerControl=null;
if (!activeThread) {
this.activeThread=true;
playerControl = new Thread(new Runnable() {
#Override
public void run() {
switch (k) {
case KeyEvent.VK_LEFT:
mapdx = 1;
mapdy = 0;
System.out.println("Map X: " + mapX + " Map Y: " + mapY);
try {
playerSprite = playerLeftWalk;
Thread.sleep(250);
playerSprite = playerLeft;
} catch (InterruptedException e) {
}
break;
default:
break;
}
}
});
activeThread=false;
}
if(playerControl!=null)
playerControl.start();
}
#Override
public void keyReleased(KeyEvent e) {
int k = e.getKeyCode();
if(k == KeyEvent.VK_LEFT) {
mapdx = 0;
mapdy = 0;
playerSprite = playerLeft;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
What the code above does is work for the first "cycle" and then stutter thereafter. I assume that what is happening is that multiple threads are being created, making the image stutter.
In my main class I initialise a static object (lkw), which contains the public ObservableList (ladung). Now I want to manipulate the data in the list whith the methode ergebniss, which is located in the class Methoden. I call the methode ergebniss in my JavaFx Gui. It doesn't work. I don't get an error, but the X property is empty. Also removing an element (Main.lkw.ladung.remove(j)) doesn't work.
What I do wrong?
EDIT
Code
Class Main
public class Main extends Application{
public static Lkw lkw=new Lkw();
public static void main(String[] args) {
javafx.application.Application.launch(Gui.class);
}
#Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
}
Class Lkw
public class Lkw {
private String name="";
private int länge=0;
private int breite=0;
private int höhe=0;
public ObservableList<Ladung> ladung=FXCollections.observableArrayList();
public Lkw(String name, int länge, int breite, int höhe){
this.name=name;
this.länge=länge;
this.breite=breite;
this.höhe=höhe;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getLänge() {
return länge;
}
public void setLänge(int länge) {
this.länge = länge;
}
public int getBreite() {
return breite;
}
public void setBreite(int breite) {
this.breite = breite;
}
public int getHöhe() {
return höhe;
}
public void setHöhe(int höhe) {
this.höhe = höhe;
}
public ObservableList<Ladung> getLadung() {
return ladung;
}
public void setLadung(ObservableList<Ladung> ladung) {
this.ladung = ladung;
}
Class Ladung
public class Ladung {
private int nr;
private int länge = 0;
private int breite = 0;
private int höhe = 0;
private int x = 0;
private int y = 0;
private int z = 0;
private int raum = 0;
private Rectangle farbe = new Rectangle(100, 50);
public Ladung(int nr, int länge, int breite, int höhe) {
this.nr = nr;
this.länge = länge;
this.breite = breite;
this.höhe = höhe;
this.farbe.setFill(new Color(Math.random(), Math.random(), Math.random(), 1));
}
public Ladung(int nr, int länge, int breite, int höhe, int raum, int x, int y, int z, Rectangle farbe) {
this.nr = nr;
this.länge = länge;
this.breite = breite;
this.höhe = höhe;
this.raum = raum;
this.x = x;
this.y = y;
this.z = z;
this.farbe=farbe;
}
public int getLänge() {
return länge;
}
public void setLänge(int länge) {
this.länge = länge;
}
public int getBreite() {
return breite;
}
public void setBreite(int breite) {
this.breite = breite;
}
public int getHöhe() {
return höhe;
}
public void setHöhe(int höhe) {
this.höhe = höhe;
}
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;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public int getNr() {
return nr;
}
public void setNr(int nr) {
this.nr = nr;
}
public int getRaum() {
return raum;
}
public void setRaum(int raum) {
this.raum = raum;
}
public Rectangle getFarbe() {
return farbe;
}
public void setFarbe(Rectangle farbe) {
this.farbe = farbe;
}
This is the class with some static methods
public class Methoden {
public static int einlesen(String pfad) {
int ret=0;
String zeile = "";
String[] daten = null;
FileReader fr = null;
try {
fr = new FileReader(pfad);
BufferedReader br = new BufferedReader(fr);
zeile = br.readLine();
daten = zeile.split(" ");
Main.lkw.setLänge(Integer.valueOf(daten[1]));
Main.lkw.setBreite(Integer.valueOf(daten[2]));
Main.lkw.setHöhe(Integer.valueOf(daten[3]));
zeile = br.readLine();
int j=0;
while (zeile != null) {
daten = null;
daten = zeile.split(" ");
Main.lkw.ladung.get(j).setX(Integer.valueOf(daten[5]));
Main.lkw.ladung.get(j).setY(Integer.valueOf(daten[6]));
Main.lkw.ladung.get(j).setZ(Integer.valueOf(daten[7]));
Main.lkw.ladung.get(j).setRaum(Integer.valueOf(daten[4]));
zeile = br.readLine();
}
br.close();
fr.close();
if(Main.lkw.getLadung().size()==0){
ret=-1;
}
for(int i=0;i<Main.lkw.getLadung().size();i++){
System.out.println(Main.lkw.getLadung().get(i));
System.out.println(Main.lkw.getLadung().get(i).getRaum());
if(Main.lkw.getLadung().get(i).getRaum()!=1){
ret=-1;
System.out.println("achtung!!!!");
}
}
} catch (IOException e) {
System.err.println(e.getMessage() + " " + e.getClass());
}
return ret;
}
I call the methode ergebniss from a JavaFx Gui class.
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>
So I have this test class, I'm very clearly setting the constraints in my Deck object, but it ends up being null. Why is it doing this? I can't figure it out
import javax.swing.JFrame;
import java.awt.*;
class DeckTester
{
public DeckTester()
{
JFrame fr = new JFrame();
fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE);
fr.setSize(640,480);
fr.setLocation(300,200);
CardTable table = new CardTable();
table.setLayout(new FlowLayout());
Stack faceupPile = new Stack(0,-.25,true);
faceupPile.setStackRules(Stack.GRAB_FROM_TOP|Stack.FACEUP);
table.add(faceupPile);
StackRuleConstraints src = new StackRuleConstraints();
src.dropPile = faceupPile;
Deck deck = new Deck();
deck.setStackRules(deck.getStackRules(),src);
table.add(new Deck());
fr.add(table);
fr.setVisible(true);
}
public static void main(String[]args)
{
new DeckTester();
}
}
Here are the Deck, Stack, and StackRuleConstraints classes. I have
System.out.println("constraints are "+(ruleConstraints!=null?"not null":"null"));
included in the mouseReleased method of variable ml and setStackRules method.
...
import java.awt.Color;
public class Deck extends Stack
{
public Deck()
{
this(false);
}
public Deck(boolean includeJokers)
{
super(0,-.25,true);
for(int rank = Card.ACE; rank <= Card.KING; rank++)
{
for(int i = 0; i < 4; i++)
{
int suit = (int)Math.pow(2,i);
add(new Card(rank,suit));
}
}
if(includeJokers)
{
add(new Card(Card.JOKER,Card.RED));
add(new Card(Card.JOKER,Card.BLACK));
}
setStackRules(GRAB_FROM_TOP|DRAW_PILE);
shuffle();
}
}
...
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Collections;
import java.util.ArrayList;
import java.awt.Container;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.RenderingHints;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
public class Stack extends Container
{
public static final int GRAB_FROM_TOP = 1;
public static final int GRAB_BY_GROUP = 2;
public static final int ASCENDING = 4;
public static final int DESCENDING = 8;
public static final int SAME_SUITS = 16;
public static final int ALTERNATING_COLORS = 32;
public static final int DRAW_PILE = 64;
public static final int RECEPTACLE = 128;
public static final int FACEDOWN = 256;
public static final int FACEUP = 512;
private int rules = 0;
protected ArrayList<Card> cards = new ArrayList<Card>();
protected boolean accessible;
private double xOffset;
private double yOffset;
private Color outlineColor;
protected static Card selectedCard = null; //BOOKMARK we have to grab cards by the group, thus this will probably need to be a Card array
protected static Card[] groupedCards = null;
private Point clickLoc;
protected static int xOrigin;
protected static int yOrigin;
protected static int mouseX;
protected static int mouseY;
protected static Point cardOrigin;
protected static boolean dragging = false;
protected static double draggedCardXOffset;
protected static double draggedCardYOffset;
private ArrayList<Card> cardsToRemove = new ArrayList<Card>();
protected StackRuleConstraints ruleConstraints = null;
private MouseAdapter ml = new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
if((rules&RECEPTACLE)>0)return;
xOrigin = e.getXOnScreen();
yOrigin = e.getYOnScreen();
for(int i = 0; i < cards.size(); i++)
{
if(cards.get(i).getLocationOnScreen().x<xOrigin
&&xOrigin<cards.get(i).getLocationOnScreen().x+50
&&cards.get(i).getLocationOnScreen().y<yOrigin
&&yOrigin<cards.get(i).getLocationOnScreen().y+70)
{
cardsToRemove.clear();
groupedCards = null;
if(i!=cards.size()-1)
{
if((rules&GRAB_FROM_TOP)>0)continue;
if((rules&GRAB_BY_GROUP)>0&&i!=cards.size()-1)
{
groupedCards = new Card[cards.size()-1-i];
for(int j = i+1; j < cards.size(); j++)
{
groupedCards[j-i-1] = cards.get(j);
cardsToRemove.add(cards.get(j));
}
}
}
if((rules&DRAW_PILE)==0&&!cards.get(i).isSelected())//if the card you clicked is facedown
{
if(i!=cards.size()-1)return; //if it's not the top card, return
else //otherwise flip it faceup
{
cards.get(i).setSelected(true);
repaint();
return;
}
}
cardOrigin = cards.get(i).getLocationOnScreen();
selectedCard = cards.get(i);
draggedCardXOffset = xOffset;
draggedCardYOffset = yOffset;
}
}
}
public void mouseDragged(MouseEvent e)
{
if(!dragging&&selectedCard!=null)
{
remove(selectedCard);
for(Card c: cardsToRemove)System.out.println("moving "+c.toString());
if(cardsToRemove.size()>0)for(int i = 0; i < cardsToRemove.size(); i++){remove(cardsToRemove.get(i));}
dragging = true;
}
mouseX = e.getXOnScreen();
mouseY = e.getYOnScreen();
getParent().repaint();
}
public void mouseReleased(MouseEvent e)
{
System.out.println("constraints are "+(ruleConstraints!=null?"not null":"null"));
if(dragging)ADDING_CARD_TO_STACK:
{
for(Component c: getParent().getComponents())
{
if(c instanceof Stack
&&e.getXOnScreen()>c.getLocationOnScreen().x
&&e.getXOnScreen()<c.getLocationOnScreen().x+c.getWidth()
&&e.getYOnScreen()>c.getLocationOnScreen().y
&&e.getYOnScreen()<c.getLocationOnScreen().y+c.getHeight()
&&selectedCard!=null
&&(((Stack)c).rules&DRAW_PILE)==0)
{
((Stack)c).add(selectedCard);
if(groupedCards!=null)for(Card card: groupedCards)((Stack)c).add(card);
break ADDING_CARD_TO_STACK;
}
}
if(dragging&&selectedCard!=null){add(selectedCard);if(groupedCards!=null)for(Card card: groupedCards)add(card);}
}
else {if((rules&DRAW_PILE)>0&&ruleConstraints!=null){System.out.println("criteria met");if(ruleConstraints.dropPile!=null){remove(selectedCard);ruleConstraints.dropPile.add(selectedCard);}}}
selectedCard = null;
groupedCards = null;
cardsToRemove.clear();
dragging = false;
getParent().repaint();
}
};
public Stack()
{
this(true);
}
public Stack(boolean accessible)
{
this(0,0,accessible);
}
public Stack(double xOffset, double yOffset, boolean accessible)
{
this(new Color(5,250,10),xOffset,yOffset,accessible);
}
public Stack(Color outlineColor, double xOffset, double yOffset, boolean accessible)
{
super();
this.xOffset = xOffset;
this.yOffset = yOffset;
this.accessible = accessible;
this.outlineColor = outlineColor;
setPreferredSize(new Dimension((int)(50+Math.max(2,Math.abs(getXOffset())*cards.size())),(int)(70+Math.max(2,.25*54)+(getYOffset()<0?0:getYOffset()*cards.size()))));
addMouseListener(ml);
addMouseMotionListener(ml);
}
public void setStackRules(int rules)
{
this.rules = rules;
}
public void setStackRules(int rules, StackRuleConstraints constraints)
{
this.rules = rules;
ruleConstraints = constraints;
System.out.println("constraints are "+(ruleConstraints!=null?"not null":"null"));
}
public int getStackRules()
{
return rules;
}
public Color getOutlineColor()
{
return outlineColor;
}
public void setOutlineColor(Color c)
{
outlineColor = c;
repaint();
}
public void setXOffset(double xOffset)
{
this.xOffset = xOffset;
}
public void setYOffset(double yOffset)
{
this.yOffset = yOffset;
}
public double getXOffset()
{
return xOffset;
}
public double getYOffset()
{
return yOffset;
}
public void shuffle()
{
Collections.shuffle(cards);
super.removeAll();
for(int i = 0; i < cards.size();i++)super.add(cards.get(i));
}
public void remove(Card c)
{
cards.remove(c);
super.remove(c);
setPreferredSize(new Dimension((int)(50+Math.max(2,Math.abs(getXOffset())*cards.size())),(int)(70+Math.max(2,.25*54)+(getYOffset()<0?0:getYOffset()*cards.size()))));
setSize(getPreferredSize());
repaint();
}
// public Card drawCard()
// {
// if(cards.size()>0)
// {
// Card c = cards.get(cards.size()-1);
// remove(c);
// cards.remove(cards.size()-1);
// return c;
// }
// else return null;
// }
public void add(Card c)
{
cards.add(c);
super.add(c);
if((rules&FACEUP)>0)c.setSelected(true);
if((rules&FACEDOWN)>0)c.setSelected(false);
setPreferredSize(new Dimension((int)(50+Math.max(2,Math.abs(getXOffset())*cards.size())),(int)(70+Math.max(2,.25*54)+(getYOffset()<0?0:getYOffset()*cards.size()))));
setSize(getPreferredSize());
repaint();
}
#Override
public void paint(Graphics gi)
{
Graphics2D g = (Graphics2D)gi;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(outlineColor);
g.fillRoundRect(0,(int)(.25*54)-2,52,72,10,10);
g.setColor(getParent().getBackground());
g.fillRoundRect(2,(int)(.25*54),48,68,5,5);
double x = 1;
double y = .25*54-1;
for(int i = 0; i < cards.size(); i++)
{
cards.get(i).setLocation((int)x,(int)y);
g.drawImage(cards.get(i).getCurrentImage(),(int)x,(int)y,null);
x+=xOffset;
y+=yOffset;
}
super.paint(g);
}
}
...
public class StackRuleConstraints
{
public Stack dropPile = null;
public StackRuleConstraints()
{
}
}
The output is
constraints are not null
constraints are null
You are creating a deck, but then adding a new one to the table:
Deck deck = new Deck();
deck.setStackRules(deck.getStackRules(),src);
table.add(new Deck());
It should be
table.add(deck);
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?