I am creating a battleship type game using swing. i draw images in one panel and it shows up fine, but when i draw more images in a different panel it either deletes most if not all of the images in the first panel and keeps the images in the second panel intact. How would I go about keeping the images from disappearing after drawn in the panel.
I have been searching for an answer online for about a week or so and have come up with nothing...
public class GameBoard extends JPanel{
Graphics g0;
public void paintComponent(Graphics g1) {
g0 = this.getGraphics();
// fill with the color you want
int wide = 275;
int tall = 275;
// go into Graphics2D for all the fine art, more options
// optional, here I just get variable Stroke sizes
Graphics2D g2 = (Graphics2D) g1;
g2.setColor(Color.black);
g2.setStroke(new BasicStroke(1));
Graphics2D g3 = (Graphics2D) g0;
g3.setColor(Color.black);
g3.setStroke(new BasicStroke(1));
// the verticals
for (int i = 0; i < 12*25; i+=25) {
g2.drawLine(i, 0, i, tall);
g3.drawLine(i, 0, i, tall);
}
// the horizontal
for (int i = 0; i < 12*25; i+=25) {
g2.drawLine(0, i, wide, i);
g3.drawLine(0, i, wide, i);
}
g0 = this.getGraphics();
}
public void paintComponent(Image i, int x, int y) {
g0.drawImage(i, x, y, null);
}
}
the above are my panels that are created the first function draws the grid and the second is to draw and image at the inserted cooridnates (x,y)
public class Game {
static JFrame main = new JFrame();
static GameBoard panel = new GameBoard(), panel1 = new GameBoard();
static Container c = main.getContentPane();
static JLabel title = new JLabel("BattleShip!");
static int count = 0, x, y, j;
static String b;
static BufferedImage pB = null, aC = null, bS = null, deS = null, suB = null;
static BattleShips[] player = new BattleShips[5];
static BattleShips[] computer = new BattleShips[5];
static Graphics g;
public static void setup(){
player[0] = new BattleShips();
player[1] = new BattleShips();
player[2] = new BattleShips();
player[3] = new BattleShips();
player[4] = new BattleShips();
computer[0] = new BattleShips();
computer[1] = new BattleShips();
computer[2] = new BattleShips();
computer[3] = new BattleShips();
computer[4] = new BattleShips();
c.add(title);
c.add(panel);
c.add(panel1);
panel.setAlignmentY(Component.CENTER_ALIGNMENT);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setSize(276, 276);
panel1.setAlignmentY(Component.CENTER_ALIGNMENT);
panel1.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.setSize(276, 276);
title.setAlignmentY(Component.CENTER_ALIGNMENT);
title.setAlignmentX(Component.CENTER_ALIGNMENT);
main.setVisible(true);
main.setSize(new Dimension(291,630));
main.setResizable(true);
main.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
main.setLocation(400, 15);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics g = panel.getGraphics(), g1 = panel1.getGraphics();
panel.paintComponent(g);
panel1.paintComponent(g1);
panel.setBorder(new EmptyBorder(0,0,25,0));
panel1.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
String d = "H";
switch(count){
case 0:
player[0].Name = "patrolBoat";
player[0].x[0] = e.getX()-(e.getX()%25);
player[0].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[0].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities,
"ham");
try {pB = ImageIO.read(new File("src/resources/"+player[0].Name+d+".png"));} catch (IOException e1) {}
panel1.paintComponent(pB,player[0].x[0],player[0].y[0]);
count++;
break;
case 1:
player[1].Name = "battleship";
player[1].x[0] = e.getX()-(e.getX()%25);
player[1].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities1 = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[1].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities1,
"ham");
try {bS = ImageIO.read(new File("src/resources/"+player[1].Name+d+".png"));} catch (IOException e1) {}
panel1.paintComponent(bS,player[1].x[0],player[1].y[0]);
count++;
break;
case 2:
player[2].Name = "aircraftCarrier";
player[2].x[0] = e.getX()-(e.getX()%25);
player[2].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities11 = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[2].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities11,
"ham");
try {aC = ImageIO.read(new File("src/resources/"+player[2].Name+d+".png"));} catch (IOException e3) {}
panel1.paintComponent(aC,player[2].x[0],player[2].y[0]);
count++;
break;
case 3:
player[3].Name = "destroyer";
player[3].x[0] = e.getX()-(e.getX()%25);
player[3].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities111 = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[3].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities111,
"ham");
try {deS = ImageIO.read(new File("src/resources/"+player[3].Name+d+".png"));} catch (IOException e2) {}
panel1.paintComponent(deS,player[3].x[0],player[3].y[0]);
count++;
break;
case 4:
player[4].Name = "submarine";
player[4].x[0] = e.getX()-(e.getX()%25);
player[4].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities1111 = {"H", "V"};
d = (String)JOptionPane.showInputDialog( main, "Place " + player[4].Name + " vertically or horizontally?", "Customized Dialog",JOptionPane.PLAIN_MESSAGE,null, possibilities1111, "ham");
try {suB = ImageIO.read(new File("src/resources/"+player[4].Name+d+".png"));} catch (IOException e1) {}
panel1.paintComponent(suB,player[4].x[0],player[4].y[0]);
count = 5;
break;
case 5:
try {setupComp();
count++;} catch (IOException e1) {}
}
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
});
}
static void setupComp() throws IOException{
b = "H";
g = panel.getGraphics();
////////DESTROYER
j = (int) (Math.random()*1);
computer[1].Name = "destroyer";
if(j == 0){
b = "H";
deS = ImageIO.read(new File("src/resources/"+computer[1].Name+b+".png"));}
else if(j == 1){
b = "V";
deS = ImageIO.read(new File("src/resources/"+computer[1].Name+b+".png"));}
computer[1].x[0] = ((int)(Math.random()*150));
computer[1].x[0] = computer[1].x[0]-computer[1].x[0]%25;
computer[1].y[0] = ((int)(Math.random()*150));
computer[1].y[0] = computer[1].y[0]-computer[1].y[0]%25;
///////END DESTROYER
//////PATROL BOAT
j = (int) (Math.random()*1);
computer[2].Name = "patrolBoat";
switch(j){
case 0:
b = "H";
pB = ImageIO.read(new File("src/resources/"+computer[2].Name+b+".png"));
case 1:
b = "V";
pB = ImageIO.read(new File("src/resources/"+computer[2].Name+b+".png"));
}
computer[2].x[0] = ((int)(Math.random()*225));
computer[2].x[0] = computer[2].x[0]-computer[2].x[0]%25;
computer[2].y[0] = ((int)(Math.random()*225));
computer[2].y[0] = computer[2].y[0]-computer[2].y[0]%25;
///////END PATROL BOAT
///////AIRCRAFT CARRIER
j = (int) (Math.random()*1);
computer[3].Name = "aircraftCarrier";
switch(j){
case 1:b = "H";
aC = ImageIO.read(new File("src/resources/"+computer[3].Name+b+".png"));
case 0:
b = "V";
aC = ImageIO.read(new File("src/resources/"+computer[3].Name+b+".png"));
}
computer[3].x[0] = ((int)(Math.random()*125));
computer[3].x[0] =computer[3].x[0]-computer[3].x[0]%25;
computer[3].y[0] = ((int)(Math.random()*125));
computer[3].y[0] = computer[3].y[0]-computer[3].y[0]%25;
///////END AIRCRAFT CARRIER
///////SUBMARINE
j = (int) (Math.random()*1);
computer[4].Name = "submarine";
switch(j){
case 0:b = "H";
suB = ImageIO.read(new File("src/resources/"+computer[4].Name+b+".png"));
case 1:
b = "V";
suB = ImageIO.read(new File("src/resources/"+computer[4].Name+b+".png"));
}
computer[4].x[0] = ((int)(Math.random()*200));
computer[4].x[0] = computer[4].x[0]-computer[4].x[0]%25;
computer[4].y[0] = ((int)(Math.random()*200));
computer[4].y[0] = computer[4].y[0]-computer[4].y[0]%25;
//END SUBMARINE
///////BATTLESHIP
j = (int) (Math.random()*1);
computer[0].Name = "battleship";
switch(j){
case 1:b = "H";
bS = ImageIO.read(new File("src/resources/"+computer[0].Name+b+".png"));
case 0:
b = "V";
bS = ImageIO.read(new File("src/resources/"+computer[0].Name+b+".png"));
}
computer[0].x[0] = ((int)(Math.random()*200));
computer[0].x[0] = computer[0].x[0]-computer[0].x[0]%25;
computer[0].x[0] = ((int)(Math.random()*200));
computer[0].x[0] = computer[0].y[0]-computer[0].y[0]%25;
///////END BATTLESHIP
System.out.println(computer[0].x[0]+","+computer[0].y[0]);
System.out.println(computer[1].x[0]+","+computer[1].y[0]);
System.out.println(computer[2].x[0]+","+computer[2].y[0]);
System.out.println(computer[3].x[0]+","+computer[3].y[0]);
System.out.println(computer[4].x[0]+","+computer[4].y[0]);
g.drawImage(bS, computer[0].x[0], computer[0].x[0], null);
g.drawImage(aC, computer[1].x[0], computer[1].x[0], null);
g.drawImage(pB, computer[2].x[0], computer[2].x[0], null);
g.drawImage(suB, computer[3].x[0], computer[3].x[0], null);
g.drawImage(deS, computer[4].x[0], computer[4].x[0], null); }}
Don't use getGraphics() to obtain the Graphics object of a Component, and never call paintComponent(...) directly yourself. The Graphics object obtained via getGraphics() is only temporary and will not persist whenever a repainting occurs.
Do all your painting either directly in the paintComponent method (or method called by it), or indirectly in a BufferedImage that is then displayed in paintComponent. Then call repaint() on the component that needs to display a changed image. This will tell the JVM that it should call paintComponent(...) and pass in a valid Graphics object.
Above all, read the graphics tutorials to see how to do it right. It's all there for you to see and learn from -- your "1 week or so" of searching should have found these as they'll be at the top of any Google search on the subject.
Edit
Having said all this, something tells me that you will do better by not messing with any of this drawing business at all, but instead create ImageIcons from your images and then displaying them in JLabels. This is the easiest way to show images using Java Swing.
Related
Basically, I am developing a multiplayer kart racing game in Java using TCP as the transport protocol.
Below are my codes, may I know why the gameframe is not showing up after the IP Address has been typed? Instead, currently it will only be shown after the server has closed down. I am using multi-threading to support sending and receiving.
Main (Client):-
public static void main(String[] args) throws IOException
{
String ipAddress = JOptionPane.showInputDialog(null, "Enter the address: ");
if (!ipAddress.isEmpty())
{
// Main program to declare GameFrame object
Socket socket = new Socket(ipAddress, 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
Thread thread = new Thread(new GameFrame(socket, reader, writer));
thread.start();
}
}
GameFrame:-
public class GameFrame extends JFrame implements Runnable
{
// Exit message
private final String message = "Are you sure you want to exit the game?";
// Exit message popup title
private final String title = "Exiting Game";
// Declare RacingTrack object
private RacingTrack racingTrack;
// Declare JFrame object
private JFrame mainGameFrame;
public GameFrame(Socket socket, BufferedReader reader, DataOutputStream writer)
{
racingTrack = new RacingTrack(socket, reader, writer);
mainGameFrame = new JFrame();
mainGameFrame.setBounds(0, 0, 900, 700);
mainGameFrame.setLocationRelativeTo(null);
mainGameFrame.setVisible(true);
mainGameFrame.add(racingTrack);
mainGameFrame.addKeyListener(racingTrack);
mainGameFrame.setResizable(false);
mainGameFrame.setTitle("Karts Racing Game");
mainGameFrame.setFocusable(true);
mainGameFrame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
mainGameFrame.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION)
mainGameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else if (result == JOptionPane.NO_OPTION)
mainGameFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
});
}
#Override
public void run()
{
System.out.println("Game Frame Thread running.");
mainGameFrame.setVisible(true);
}
Server:-
public class Server
{
public static void main( String args[] )
{
int connectedClient = 0;
ServerSocket service = null;
Socket server = null;
BufferedReader inputStream;
DataOutputStream outputStream;
try
{
service = new ServerSocket(8888);
System.out.println("Server has started.");
}
catch (IOException e)
{
System.out.println(e);
}
try
{
while (connectedClient < 2)
{
server = service.accept();
connectedClient++;
ClientThread clientThread = new ClientThread(server, connectedClient);
System.out.println("Player " + connectedClient + " connected. IP Address: " + server.getInetAddress());
Thread thread = new Thread(clientThread);
thread.start();
System.out.println("Player: " + connectedClient + " thread running.");
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
ClientThread:-
public class ClientThread implements Runnable
{
Socket socket;
int playerNum;
boolean keepRunning = true;
int kartNumIndex;
int x;
int y;
int speed;
BufferedReader reader;
DataOutputStream writer;
ArrayList<ClientThread> clients = new ArrayList<>();
public ClientThread(Socket socket, int player)
{
this.socket = socket;
this.playerNum = player;
}
#Override
public void run()
{
try
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new DataOutputStream(socket.getOutputStream());
writer.writeByte(playerNum);
writer.flush();
while (keepRunning == true)
{
playerNum = reader.read();
kartNumIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
broadcastToAllClients(playerNum, kartNumIndex, x, y, speed);
}
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
public void broadcastToAllClients(int playerNum, int kartNumIndex, int x, int y, int speed)
{
try
{
for (ClientThread client : clients)
{
client.writer.write(playerNum);
client.writer.write(kartNumIndex);
client.writer.write(x);
client.writer.write(y);
client.writer.write(speed);
client.writer.flush();
}
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
}
RacingTrack Constructor (partial):-
public class RacingTrack extends JPanel implements KeyListener
{
Socket clientSocket;
BufferedReader reader;
DataOutputStream writer;
int playerNum;
int kartNum;
int kartImageIndex;
int x;
int y;
int speed;
private Kart kart1;
private Kart kart2;
private SoundEffect soundEffect;
private Timer animationTimer;
private final int delay = 0;
private Set<Integer> pressedKeys;
boolean isKart1Lose;
boolean isKart2Lose;
private ElapseCounter kart1T;
private ElapseCounter kart2T;
/* Coordinates, Width, and Height of the value given and modified */
/* Racing Track 1 */
// Grass
private final int GRASS_X_COOR = 150;
private final int GRASS_Y_COOR = 200;
private final int GRASS_WIDTH = 550;
private final int GRASS_HEIGHT = 320;
// Outer Edge
private final int OUTER_EDGE_X_COOR = 50;
private final int OUTER_EDGE_Y_COOR = 100;
private final int OUTER_EDGE_WIDTH = 750;
private final int OUTER_EDGE_HEIGHT = 520;
// Inner Edge
private final int INNER_EDGE_X_COOR = 150;
private final int INNER_EDGE_Y_COOR = 200;
private final int INNER_EDGE_WIDTH = 550;
private final int INNER_EDGE_HEIGHT = 320;
// Mid Lane
private final int MID_LANE_X_COOR = 100;
private final int MID_LANE_Y_COOR = 150;
private final int MID_LANE_WIDTH = 650;
private final int MID_LANE_HEIGHT = 420;
// Start Line
private final int START_LINE_X1_COOR = 425;
private final int START_LINE_Y1_COOR = 520;
private final int START_LINE_X2_COOR = 425;
private final int START_LINE_Y2_COOR = 620;
/* Racing Track 2 */
// Grass
private final int GRASS_TOP_X_COOR = 450;
private final int GRASS_TOP_Y_COOR = 240;
private final int GRASS_LEFT_X_COOR = 260;
private final int GRASS_LEFT_Y_COOR = 520;
private final int GRASS_RIGHT_X_COOR = 640;
private final int GRASS_RIGHT_Y_COOR = 520;
// Outer Lane
private final int OUTER_LANE_TOP_X_COOR = 450;
private final int OUTER_LANE_TOP_Y_COOR = 110;
private final int OUTER_LANE_LEFT_X_COOR = 50;
private final int OUTER_LANE_LEFT_Y_COOR = 622;
private final int OUTER_LANE_RIGHT_X_COOR = 850;
private final int OUTER_LANE_RIGHT_Y_COOR = 622;
// Mid Lane
private final int MID_LANE_TOP_X_COOR = 450;
private final int MID_LANE_TOP_Y_COOR = 170;
private final int MID_LANE_LEFT_X_COOR = 140;
private final int MID_LANE_LEFT_Y_COOR = 570;
private final int MID_LANE_RIGHT_X_COOR = 760;
private final int MID_LANE_RIGHT_Y_COOR = 570;
// Obtain car shape bounds
private Rectangle kart1Shape;
private Rectangle kart2Shape;
// Obtain outer edges bound
private Rectangle outerEdgeLeft = new Rectangle(OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR, 1, OUTER_EDGE_HEIGHT);
private Rectangle outerEdgeTop = new Rectangle(OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR, OUTER_EDGE_WIDTH, 1);
private Rectangle outerEdgeRight = new Rectangle(OUTER_EDGE_X_COOR + OUTER_EDGE_WIDTH, OUTER_EDGE_Y_COOR, 1, OUTER_EDGE_HEIGHT);
private Rectangle outerEdgeBottom = new Rectangle(OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR + OUTER_EDGE_HEIGHT, OUTER_EDGE_WIDTH, 1);
private Line2D outerEdgeTop2 = new Line2D.Double(OUTER_LANE_TOP_X_COOR, OUTER_LANE_TOP_Y_COOR, OUTER_LANE_LEFT_X_COOR, OUTER_LANE_LEFT_Y_COOR);
private Line2D outerEdgeLeft2 = new Line2D.Double(OUTER_LANE_LEFT_X_COOR, OUTER_LANE_LEFT_Y_COOR, OUTER_LANE_RIGHT_X_COOR, OUTER_LANE_RIGHT_Y_COOR);
private Line2D outerEdgeRight2 = new Line2D.Double(OUTER_LANE_RIGHT_X_COOR, OUTER_LANE_RIGHT_Y_COOR, OUTER_LANE_TOP_X_COOR, OUTER_LANE_TOP_Y_COOR);
private Rectangle innerEdgeLeft = new Rectangle(GRASS_X_COOR, GRASS_Y_COOR, 1, GRASS_HEIGHT);
private Rectangle innerEdgeTop = new Rectangle(GRASS_X_COOR, GRASS_Y_COOR, GRASS_WIDTH, 1);
private Rectangle innerEdgeRight = new Rectangle(GRASS_X_COOR + GRASS_WIDTH, GRASS_Y_COOR, 1, GRASS_HEIGHT);
private Rectangle innerEdgeBottom = new Rectangle(GRASS_X_COOR, GRASS_Y_COOR + GRASS_HEIGHT, GRASS_WIDTH, 1);
private Line2D innerEdgeTop2 = new Line2D.Double(GRASS_TOP_X_COOR, GRASS_TOP_Y_COOR, GRASS_LEFT_X_COOR, GRASS_LEFT_Y_COOR);
private Line2D innerEdgeLeft2 = new Line2D.Double(GRASS_LEFT_X_COOR, GRASS_LEFT_Y_COOR, GRASS_RIGHT_X_COOR, GRASS_RIGHT_Y_COOR);
private Line2D innerEdgeRight2 = new Line2D.Double(GRASS_RIGHT_X_COOR, GRASS_RIGHT_Y_COOR, GRASS_TOP_X_COOR, GRASS_TOP_Y_COOR);
// Obtain goal line bound
private Rectangle goalLineBound = new Rectangle(START_LINE_X1_COOR, START_LINE_Y1_COOR, 1, START_LINE_Y2_COOR - START_LINE_Y1_COOR);
// Constructor
public RacingTrack(Socket socket, BufferedReader reader, DataOutputStream writer)
{
this.reader = reader;
this.writer = writer;
try
{
playerNum = reader.read();
System.out.println("I am Player Number " + playerNum);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
// Set this JPanel to allow overlay layout
// so that the kart icons can be printed above it
this.setLayout(new OverlayLayout(this));
// Create kart objects
// Specify the kart number, x-coordinates and y-coordinates
// kart1 = new Kart(1, 430, 521);
// kart2 = new Kart(2, 430, 570);
if (playerNum == 1)
{
kart1 = new Kart(1, 430, 521);
try
{
writer.write(kart1.getKartNum());
writer.write(kart1.getKartImageIndex());
writer.write(kart1.getXCoordinate());
writer.write(kart1.getYCoordinate());
writer.write(kart1.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart2 = new Kart(kartNum, x, y);
kart2.setKartImageIndex(kartImageIndex);
kart2.setSpeed(speed);
}
else if (playerNum == 2)
{
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart1 = new Kart(kartNum, x, y);
kart1.setKartImageIndex(kartImageIndex);
kart1.setSpeed(speed);
kart2 = new Kart(1, 430, 570);
try
{
writer.write(kart2.getKartNum());
writer.write(kart2.getKartImageIndex());
writer.write(kart2.getXCoordinate());
writer.write(kart2.getYCoordinate());
writer.write(kart2.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
if (playerNum == 1)
kart1.start();
else if (playerNum == 2)
kart2.start();
isKart1Lose = false;
isKart2Lose = false;
kart1T = new ElapseCounter();
kart2T = new ElapseCounter();
pressedKeys = new HashSet<>();
animationTimer = new Timer(delay, new TimeHandler());
animationTimer.start();
}
private class TimeHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
speedLabel.setText("<html>Kart 1 Speed: " + kart1.getSpeed() + " <br> Kart 2 Speed: " + kart2.getSpeed() + "</html>");
kart1Shape = kart1.getKartShape();
kart2Shape = kart2.getKartShape();
if (playerNum == 1)
{
if (isKart1Lose == false)
{
if (kart1Shape.intersects(outerEdgeLeft))
setKart1Lose();
else if (kart1Shape.intersects(outerEdgeTop))
setKart1Lose();
else if (kart1Shape.intersects(outerEdgeRight))
setKart1Lose();
else if (kart1Shape.intersects(outerEdgeBottom))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeLeft))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeTop))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeRight))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeBottom))
setKart1Lose();
else if (kart1Shape.intersects(goalLineBound))
winnerFound(1);
}
}
else if (playerNum == 2)
{
if (isKart2Lose == false)
{
if (kart2Shape.intersects(outerEdgeLeft))
setKart2Lose();
else if (kart2Shape.intersects(outerEdgeTop))
setKart2Lose();
else if (kart2Shape.intersects(outerEdgeRight))
setKart2Lose();
else if (kart2Shape.intersects(outerEdgeBottom))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeLeft))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeTop))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeRight))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeBottom))
setKart2Lose();
else if (kart2Shape.intersects(goalLineBound))
winnerFound(2);
}
}
if (kart1Shape.intersects(kart2Shape))
{
if (playerNum == 1)
isKart1Lose = true;
else
isKart2Lose = true;
if (playerNum == 1)
kart1T.setStop();
else
kart2T.setStop();
animationTimer.stop();
if (playerNum == 1)
kart1.stop();
else
kart2.stop();
}
if (isKart1Lose == true && isKart2Lose == true)
bothKartsCrashed();
repaint();
}
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
super.setBackground(Color.gray);
Color c1 = Color.green;
Color c2 = Color.black;
Color c3 = Color.white;
g.setColor( c1 );
// x-coordinate, y-coordinate, width, height
g.fillRect( GRASS_X_COOR, GRASS_Y_COOR, GRASS_WIDTH, GRASS_HEIGHT ); // grass
g.setColor( c2 );
g.drawRect( OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR, OUTER_EDGE_WIDTH, OUTER_EDGE_HEIGHT ); // outer edge
g.drawRect( INNER_EDGE_X_COOR, INNER_EDGE_Y_COOR, INNER_EDGE_WIDTH, INNER_EDGE_HEIGHT ); // inner edge
g.setColor( c3 );
Graphics2D g2d = (Graphics2D)g.create();
Stroke dashed = new BasicStroke(2, BasicStroke.JOIN_BEVEL, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
g2d.setStroke(dashed);
g2d.drawRect( MID_LANE_X_COOR, MID_LANE_Y_COOR, MID_LANE_WIDTH, MID_LANE_HEIGHT ); // mid-lane marker
g2d.dispose();
g.drawLine( START_LINE_X1_COOR, START_LINE_Y1_COOR, START_LINE_X2_COOR, START_LINE_Y2_COOR ); // start line
if (playerNum == 1)
{
try
{
writer.write(kart1.getKartNum());
writer.write(kart1.getKartImageIndex());
writer.write(kart1.getXCoordinate());
writer.write(kart1.getYCoordinate());
writer.write(kart1.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart1.draw(g, this);
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
kart2.draw(g, this, x, y);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
else if (kartNum == 2)
{
try
{
writer.write(kart2.getKartNum());
writer.write(kart2.getKartImageIndex());
writer.write(kart2.getXCoordinate());
writer.write(kart2.getYCoordinate());
writer.write(kart2.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart2.draw(g, this);
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
kart1.draw(g, this, x, y);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
}
#Override
public void keyTyped(KeyEvent e) { }
#Override
public synchronized void keyPressed(KeyEvent e)
{
int speed;
int carImageIndex;
// Add keypresses
pressedKeys.add(e.getKeyCode());
for (Iterator<Integer> it = pressedKeys.iterator(); it.hasNext();)
{
switch (it.next())
{
/* kart blue */
// Increase speed
// Each key press increases speed by 10
case KeyEvent.VK_UP:
if (isKart1Lose == false)
{
// get kart's speed
speed = kart1.getSpeed();
// increase the initial speed by 10
kart1.setSpeed(speed + 10);
// check if speed is more than 100
// if yes, set to 100 (maximum)
if (kart1.getSpeed() > 100)
kart1.setSpeed(100);
// drive the kart forward with the speed
moveForwardKart1(kart1.getSpeed());
}
break;
// Decrease speed
// Each key press decreases speed by 10
case KeyEvent.VK_DOWN:
if (isKart1Lose == false)
{
// get kart's speed
speed = kart1.getSpeed();
// decrease the initial speed by 10
kart1.setSpeed(speed - 10);
// check if speed is less than 0
// if yes, set to -1, then kart will reverse
// minimum is -1
if (kart1.getSpeed() < 0)
{
kart1.setSpeed(-1);
moveBackwardKart1();
}
// check if speed is 0
// if no, then drive the kart forward with the set speed
if (kart1.getSpeed() > 0)
moveForwardKart1(kart1.getSpeed());
}
break;
// Turn the kart to the left
case KeyEvent.VK_LEFT:
if (isKart1Lose == false)
{
// get kart's image index
carImageIndex = kart1.getKartImageIndex();
// set the kart's new image index
kart1.setKartImageIndex(carImageIndex - 1);
// if kart's image index is less than 0
// set it to 15
if (carImageIndex - 1 < 0)
kart1.setKartImageIndex(15);
}
break;
// Turn the kart to the right
case KeyEvent.VK_RIGHT:
if (isKart1Lose == false)
{
// get kart's image index
carImageIndex = kart1.getKartImageIndex();
// set the kart's new image index
kart1.setKartImageIndex(carImageIndex + 1);
// if kart's image index is more than 15
// set it to 0
if (carImageIndex + 1 > 15)
kart1.setKartImageIndex(0);
}
break;
}
}
}
#Override
public void keyReleased(KeyEvent e)
{
pressedKeys.remove(e.getKeyCode());
}
// For KART1
// Method that drive the kart forward with appropriate speed
// speed will affect the pixel displacement
// (speed / 10) to get the first digit so that the kart can move accordingly
// if speed is 1, the kart moves by 1 pixel; ie: x + 1 or y + 1 depends on direction
// if speed is 5, the kart moves by 5 pixel; ie: x + 5 or y + 5 depends on direction
// this is done by increasing or decreasing the x and/or y coordinates
private void moveForwardKart1(int speed)
{
switch (kart1.getKartImageIndex())
{
case 0:
kart1.setYCoordinate(kart1.getYCoordinate() - (speed / 10));
break;
case 1:
case 2:
case 3:
kart1.setXCoordinate(kart1.getXCoordinate() + (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() - (speed / 10));
break;
case 4:
kart1.setXCoordinate(kart1.getXCoordinate() + (speed / 10));
break;
case 5:
case 6:
case 7:
kart1.setXCoordinate(kart1.getXCoordinate() + (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() + (speed / 10));
break;
case 8:
kart1.setYCoordinate(kart1.getYCoordinate() + (speed / 10));
break;
case 9:
case 10:
case 11:
kart1.setXCoordinate(kart1.getXCoordinate() - (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() + (speed / 10));
break;
case 12:
kart1.setXCoordinate(kart1.getXCoordinate() - (speed / 10));
break;
case 13:
case 14:
case 15:
kart1.setXCoordinate(kart1.getXCoordinate() - (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() - (speed / 10));
break;
}
}
// For KART1
// Method that drive the kart backward (reverse)
// the coordinate(s) will only be increased or decreased by 1 pixel
// this is done by increasing or decreasing the x and/or y coordinates
private void moveBackwardKart1()
{
switch (kart1.getKartImageIndex())
{
case 0:
kart1.setYCoordinate(kart1.getYCoordinate() + 1);
break;
case 1:
case 2:
case 3:
kart1.setXCoordinate(kart1.getXCoordinate() - 1);
kart1.setYCoordinate(kart1.getYCoordinate() + 1);
break;
case 4:
kart1.setXCoordinate(kart1.getXCoordinate() - 1);
break;
case 5:
case 6:
case 7:
kart1.setXCoordinate(kart1.getXCoordinate() - 1);
kart1.setYCoordinate(kart1.getYCoordinate() - 1);
break;
case 8:
kart1.setYCoordinate(kart1.getYCoordinate() - 1);
break;
case 9:
case 10:
case 11:
kart1.setXCoordinate(kart1.getXCoordinate() + 1);
kart1.setYCoordinate(kart1.getYCoordinate() - 1);
break;
case 12:
kart1.setXCoordinate(kart1.getXCoordinate() + 1);
break;
case 13:
case 14:
case 15:
kart1.setXCoordinate(kart1.getXCoordinate() + 1);
kart1.setYCoordinate(kart1.getYCoordinate() + 1);
break;
}
}
}
Your code opens the socket, then raises a new thread to start the game.
The socket, reader and writer are passed into that thread until they arrive at the RacingTrack. The RacingTrack constructor immediately tries to send/receive data, and be aware reading data is a blocking call. It waits until the data has been read.
So unless you close the server and thus the TCP connection is cut, the client still hopes to receive some data and therefore waits patiently.
I am trying to combign tiff image and shapefile and want show it. For this, I am using GeoTiff and I am stuck that my tiff file is now being displayed. Shapefile is showing properly but tiff image, which is having only 1 band and grey scale index, is not being shown because of some reason. I am getting one warning message as below.
2016-08-04T12:43:06.456+0530 WARNING Possible use of "Transverse_Mercator" projection outside its valid area.
Latitude 180°00.0'S is out of range (±90°).
How can I remove this message?
My code is as below
private void displayLayers() throws Exception {
AbstractGridFormat format = GridFormatFinder.findFormat(this.getBlueMarble());
this.setGridCoverageReader(format.getReader(this.getBlueMarble()));
Style rgbStyle = this.createRGBStyle();
// connect to the shapefile
FileDataStore dataStore = FileDataStoreFinder.getDataStore(this.getBorderShape());
SimpleFeatureSource shapefileSource = dataStore.getFeatureSource();
Style shpStyle = SLD.createPolygonStyle(Color.BLUE, null, 0.0f);
MapContent map = new MapContent();
map.getViewport().setCoordinateReferenceSystem(
DefaultGeographicCRS.WGS84);
map.setTitle("Illegal Mining");
Layer rasterLayer = new GridReaderLayer(this.getGridCoverageReader(), rgbStyle);
map.addLayer(rasterLayer);
Layer shpLayer = new FeatureLayer(shapefileSource, shpStyle);
map.addLayer(shpLayer);
System.out.println("Trying to show on map...");
JMapPane mapPane = new JMapPane();
mapPane.setMapContent(map);
mapPane.setDisplayArea(shapefileSource.getBounds());
//mapPane.setDisplayArea(this.getGridCoverageReader().getOriginalEnvelope());
this.add(mapPane, BorderLayout.CENTER);
}
private Style createRGBStyle() {
GridCoverage2DReader reader = this.getGridCoverageReader();
StyleFactory sf = this.getStyleFactory();
GridCoverage2D cov = null;
try {
cov = reader.read(null);
} catch (IOException giveUp) {
throw new RuntimeException(giveUp);
}
// We need at least three bands to create an RGB style
int numBands = cov.getNumSampleDimensions();
System.out.println("numBands:"+numBands);
if (numBands < 3) {
System.out.println("Bands are less than 3");
//return null;
}
// Get the names of the bands
String[] sampleDimensionNames = new String[numBands];
for (int i = 0; i < numBands; i++) {
GridSampleDimension dim = cov.getSampleDimension(i);
sampleDimensionNames[i] = dim.getDescription().toString();
}
final int RED = 0, GREEN = 1, BLUE = 2;
int[] channelNum = { -1, -1, -1 };
Boolean greyflag=false;
// We examine the band names looking for "red...", "green...",
// "blue...".
// Note that the channel numbers we record are indexed from 1, not 0.
for (int i = 0; i < numBands; i++) {
String name = sampleDimensionNames[i].toLowerCase();
System.out.println("name :"+name);
if (name != null) {
if (name.matches("red.*")) {
channelNum[RED] = i + 1;
} else if (name.matches("green.*")) {
channelNum[GREEN] = i + 1;
} else if (name.matches("blue.*")) {
channelNum[BLUE] = i + 1;
}else if(name.matches("gray.*")){
System.out.println("What to do here");
channelNum[RED] = 1;
channelNum[GREEN] = 2;
channelNum[BLUE] = 3;
greyflag=true;
}
}
}
// If we didn't find named bands "red...", "green...", "blue..."
// we fall back to using the first three bands in order
if(greyflag==false){
if (channelNum[RED] < 0 || channelNum[GREEN] < 0
|| channelNum[BLUE] < 0) {
channelNum[RED] = 1;
channelNum[GREEN] = 2;
channelNum[BLUE] = 3;
}
}
// Now we create a RasterSymbolizer using the selected channels
SelectedChannelType[] sct = new SelectedChannelType[cov
.getNumSampleDimensions()];
ContrastEnhancement ce = sf.contrastEnhancement(this.ff.literal(1.0),
ContrastMethod.NORMALIZE);
for (int i = 0; i < numBands; i++) {
sct[i] = sf.createSelectedChannelType(
String.valueOf(channelNum[i]), ce);
System.out.println(String.valueOf(channelNum[i]));
}
RasterSymbolizer sym = sf.getDefaultRasterSymbolizer();
ChannelSelection sel =sf.channelSelection(sct[RED]);
if(numBands>1){
sel = sf.channelSelection(sct[RED], sct[GREEN],
sct[BLUE]);
}
sym.setChannelSelection(sel);
return SLD.wrapSymbolizers(sym);
}
I just pass two files as below code
public MapImagePanel() {
this.setLayout(new BorderLayout(0, 0));
this.setBackground(Color.BLUE);
this.setPreferredSize(new Dimension(720, 360));
this.setBlueMarble(new File("E:/tifffilename.TIFF"));
this.setBorderShape(new File("E:/shapefilename.shp"));
try {
this.displayLayers();
} catch (Exception e) {
e.printStackTrace();
}
}
This is how i use this class in main class
//see output in main method
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MapImagePanel panel = new MapImagePanel();
panel.setPreferredSize(new Dimension(1024,768));
panel.setVisible(true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.show();
TLDR; add the following line to your program start up:
System.setProperty("org.geotools.referencing.forceXY", "true");
From GeoTools FAQ as computer programmers they knew that coordinates would be expressed as longitude,latitude pairs so they could use existing graphics code easily by treating them as a simple (x,y) pair. but for sequence like (x,y) or (y,x) they confused that is why this error is coming.
I'm using LIBSVM. In the download package is a svm_toy.java file. I could not find out how it works. Here is the source code:
import libsvm.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
/**
* SVM package
* #author unknown
*
*/
public class svm_toy extends Applet {
static final String DEFAULT_PARAM="-t 2 -c 100";
int XLEN;
int YLEN;
// off-screen buffer
Image buffer;
Graphics buffer_gc;
// pre-allocated colors
final static Color colors[] =
{
new Color(0,0,0),
new Color(0,120,120),
new Color(120,120,0),
new Color(120,0,120),
new Color(0,200,200),
new Color(200,200,0),
new Color(200,0,200)
};
class point {
point(double x, double y, byte value)
{
this.x = x;
this.y = y;
this.value = value;
}
double x, y;
byte value;
}
Vector<point> point_list = new Vector<point>();
byte current_value = 1;
public void init()
{
setSize(getSize());
final Button button_change = new Button("Change");
Button button_run = new Button("Run");
Button button_clear = new Button("Clear");
Button button_save = new Button("Save");
Button button_load = new Button("Load");
final TextField input_line = new TextField(DEFAULT_PARAM);
BorderLayout layout = new BorderLayout();
this.setLayout(layout);
Panel p = new Panel();
GridBagLayout gridbag = new GridBagLayout();
p.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridwidth = 1;
gridbag.setConstraints(button_change,c);
gridbag.setConstraints(button_run,c);
gridbag.setConstraints(button_clear,c);
gridbag.setConstraints(button_save,c);
gridbag.setConstraints(button_load,c);
c.weightx = 5;
c.gridwidth = 5;
gridbag.setConstraints(input_line,c);
button_change.setBackground(colors[current_value]);
p.add(button_change);
p.add(button_run);
p.add(button_clear);
p.add(button_save);
p.add(button_load);
p.add(input_line);
this.add(p,BorderLayout.SOUTH);
button_change.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_change_clicked(); button_change.setBackground(colors[current_value]); }});
button_run.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
button_clear.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_clear_clicked(); }});
button_save.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_save_clicked(input_line.getText()); }});
button_load.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_load_clicked(); }});
input_line.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
this.enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
void draw_point(point p)
{
Color c = colors[p.value+3];
Graphics window_gc = getGraphics();
buffer_gc.setColor(c);
buffer_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
window_gc.setColor(c);
window_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
}
void clear_all()
{
point_list.removeAllElements();
if(buffer != null)
{
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
repaint();
}
void draw_all_points()
{
int n = point_list.size();
for(int i=0;i<n;i++)
draw_point(point_list.elementAt(i));
}
void button_change_clicked()
{
++current_value;
if(current_value > 3) current_value = 1;
}
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
void button_run_clicked(String args)
{
// guard
if(point_list.isEmpty()) return;
svm_parameter param = new svm_parameter();
// default values
param.svm_type = svm_parameter.C_SVC;
param.kernel_type = svm_parameter.RBF;
param.degree = 3;
param.gamma = 0;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 40;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = new int[0];
param.weight = new double[0];
// parse options
StringTokenizer st = new StringTokenizer(args);
String[] argv = new String[st.countTokens()];
for(int i=0;i<argv.length;i++)
argv[i] = st.nextToken();
for(int i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
if(++i>=argv.length)
{
System.err.print("unknown option\n");
break;
}
switch(argv[i-1].charAt(1))
{
case 's':
param.svm_type = atoi(argv[i]);
break;
case 't':
param.kernel_type = atoi(argv[i]);
break;
case 'd':
param.degree = atoi(argv[i]);
break;
case 'g':
param.gamma = atof(argv[i]);
break;
case 'r':
param.coef0 = atof(argv[i]);
break;
case 'n':
param.nu = atof(argv[i]);
break;
case 'm':
param.cache_size = atof(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'p':
param.p = atof(argv[i]);
break;
case 'h':
param.shrinking = atoi(argv[i]);
break;
case 'b':
param.probability = atoi(argv[i]);
break;
case 'w':
++param.nr_weight;
{
int[] old = param.weight_label;
param.weight_label = new int[param.nr_weight];
System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);
}
{
double[] old = param.weight;
param.weight = new double[param.nr_weight];
System.arraycopy(old,0,param.weight,0,param.nr_weight-1);
}
param.weight_label[param.nr_weight-1] = atoi(argv[i-1].substring(2));
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
default:
System.err.print("unknown option\n");
}
}
// build problem
svm_problem prob = new svm_problem();
prob.l = point_list.size();
prob.y = new double[prob.l];
if(param.kernel_type == svm_parameter.PRECOMPUTED)
{
}
else if(param.svm_type == svm_parameter.EPSILON_SVR ||
param.svm_type == svm_parameter.NU_SVR)
{
if(param.gamma == 0) param.gamma = 1;
prob.x = new svm_node[prob.l][1];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.y[i] = p.y;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[1];
x[0] = new svm_node();
x[0].index = 1;
int[] j = new int[XLEN];
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
{
x[0].value = (double) i / XLEN;
j[i] = (int)(YLEN*svm.svm_predict(model, x));
}
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(0,0,0,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(0,0,0,YLEN-1);
int p = (int)(param.p * YLEN);
for(int i=1;i<XLEN;i++)
{
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(i,0,i,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(i,0,i,YLEN-1);
buffer_gc.setColor(colors[5]);
window_gc.setColor(colors[5]);
buffer_gc.drawLine(i-1,j[i-1],i,j[i]);
window_gc.drawLine(i-1,j[i-1],i,j[i]);
if(param.svm_type == svm_parameter.EPSILON_SVR)
{
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
window_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
window_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
}
}
}
else
{
if(param.gamma == 0) param.gamma = 0.5;
prob.x = new svm_node [prob.l][2];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.x[i][1] = new svm_node();
prob.x[i][1].index = 2;
prob.x[i][1].value = p.y;
prob.y[i] = p.value;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[2];
x[0] = new svm_node();
x[1] = new svm_node();
x[0].index = 1;
x[1].index = 2;
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
for (int j = 0; j < YLEN ; j++) {
x[0].value = (double) i / XLEN;
x[1].value = (double) j / YLEN;
double d = svm.svm_predict(model, x);
if (param.svm_type == svm_parameter.ONE_CLASS && d<0) d=2;
buffer_gc.setColor(colors[(int)d]);
window_gc.setColor(colors[(int)d]);
buffer_gc.drawLine(i,j,i,j);
window_gc.drawLine(i,j,i,j);
}
}
draw_all_points();
}
void button_clear_clicked()
{
clear_all();
}
void button_save_clicked(String args)
{
FileDialog dialog = new FileDialog(new Frame(),"Save",FileDialog.SAVE);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
try {
DataOutputStream fp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
int svm_type = svm_parameter.C_SVC;
int svm_type_idx = args.indexOf("-s ");
if(svm_type_idx != -1)
{
StringTokenizer svm_str_st = new StringTokenizer(args.substring(svm_type_idx+2).trim());
svm_type = atoi(svm_str_st.nextToken());
}
int n = point_list.size();
if(svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.y+" 1:"+p.x+"\n");
}
}
else
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.value+" 1:"+p.x+" 2:"+p.y+"\n");
}
}
fp.close();
} catch (IOException e) { System.err.print(e); }
}
void button_load_clicked()
{
FileDialog dialog = new FileDialog(new Frame(),"Load",FileDialog.LOAD);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
clear_all();
try {
BufferedReader fp = new BufferedReader(new FileReader(filename));
String line;
while((line = fp.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
if(st.countTokens() == 5)
{
byte value = (byte)atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x,y,value));
}
else if(st.countTokens() == 3)
{
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x,y,current_value));
}else
break;
}
fp.close();
} catch (IOException e) { System.err.print(e); }
draw_all_points();
}
protected void processMouseEvent(MouseEvent e)
{
if(e.getID() == MouseEvent.MOUSE_PRESSED)
{
if(e.getX() >= XLEN || e.getY() >= YLEN) return;
point p = new point((double)e.getX()/XLEN,
(double)e.getY()/YLEN,
current_value);
point_list.addElement(p);
draw_point(p);
}
}
public void paint(Graphics g)
{
// create buffer first time
if(buffer == null) {
buffer = this.createImage(XLEN,YLEN);
buffer_gc = buffer.getGraphics();
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
g.drawImage(buffer,0,0,this);
}
public Dimension getPreferredSize() { return new Dimension(XLEN,YLEN+50); }
public void setSize(Dimension d) { setSize(d.width,d.height); }
public void setSize(int w,int h) {
super.setSize(w,h);
XLEN = w;
YLEN = h-50;
clear_all();
}
public static void main(String[] argv)
{
new AppletFrame("svm_toy",new svm_toy(),500,500+50);
}
}
class AppletFrame extends Frame {
AppletFrame(String title, Applet applet, int width, int height)
{
super(title);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
applet.init();
applet.setSize(width,height);
applet.start();
this.add(applet);
this.pack();
this.setVisible(true);
}
}
Could someone give me an example or explanation? I also would like to scale my training data. Where is the right place to scale?
Thanks
SVM-Toy
SVM Toy is - as the name suggests - a simple toy build by the LIBSVM dev team and is not recommended for "productive" visualization of the SVM's decision boundary.
Moreover looking into the source-code of svm_toy it becomes clear, that this tool only supports 2D vectors.
Relevant code fragment is taken from the button_load_clicked() Method:
while ((line = fp.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
if (st.countTokens() == 5) {
byte value = (byte) atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x, y, value));
} else if (st.countTokens() == 3) {
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x, y, current_value));
} else {
break;
}
}
As you can see, the svm_toy implementation can only handle 2D vectors, which means it only supports vectors, which were constructed out of two features.
That means, you can only read and display files which are build from only two features like for example the fourclass dataset provided by the LIBSVM authors. However it seems, that this feature is not supported within this implementation.
I think, that the tool is designed for interactive visualization. You are able to change the color and click on the black application screen. After you set some points (each color representing an own class), you can click "run" and the decision boundary is displayed.
Displaying the desicion boundary in an high dimensional vector space is even nearly impossible. I would recommend to not use this tool implementation for any productive / scientific purpose.
Scaling
Scaling of your training data should be done after you transformed it into it's numeric representation and before you are going forward to train your SVM with this data.
In short that means, you have to do the following steps before using svm_train
Construct the numeric representation for each data point (with the help of feature selection, ...)
Analyse the resulting numeric representation for each data point
Scale your data for example to [-1,1]
Go ahead and train your SVM model. Note well, that you have to repeat 1-3 for predicting unknown data points. The only difference is, that you already know the necessary features, so there is no need for feature selection.
I want only images at their respective positions as in the pdf with its exact layout but I don't want text to render in it Is there any way to do it currently I am working in this way but text also coming in this way so is there any way to meet that requirement
File sourceFile=new File(pdfFile);
String fileName = sourceFile.getName().replace(".pdf", "");
int pageNumber = 1;
for (PDPage page : li)
{
BufferedImage image = page.convertToImage();
File outputfile = new File(imgDes + fileName +"_"+ pageNumber +".png");
System.out.println("Image Created -> "+ outputfile.getName());
ImageIO.write(image, "png", outputfile);
pageNumber++;
}
Derive a class from PageDrawer and override all methods that don't deal with images with empty, and then call drawPage(). I just overrode processTextPosition(), and didn't bother about lines, shapes etc but I think it is clear what I mean.
public class MyPageDrawer extends PageDrawer
{
public MyPageDrawer() throws IOException
{
}
#Override
protected void processTextPosition(TextPosition text)
{
}
// taken from PDPage.convertToImage, with extra parameter and one modification
static BufferedImage convertToImage(PDPage page, int imageType, int resolution) throws IOException
{
final Color TRANSPARENT_WHITE = new Color(255, 255, 255, 0);
final int DEFAULT_USER_SPACE_UNIT_DPI = 72;
PDRectangle cropBox = page.findCropBox();
float widthPt = cropBox.getWidth();
float heightPt = cropBox.getHeight();
float scaling = resolution / (float) DEFAULT_USER_SPACE_UNIT_DPI;
int widthPx = Math.round(widthPt * scaling);
int heightPx = Math.round(heightPt * scaling);
Dimension pageDimension = new Dimension((int) widthPt, (int) heightPt);
int rotationAngle = page.findRotation();
// normalize the rotation angle
if (rotationAngle < 0)
{
rotationAngle += 360;
}
else if (rotationAngle >= 360)
{
rotationAngle -= 360;
}
// swap width and height
BufferedImage retval;
if (rotationAngle == 90 || rotationAngle == 270)
{
retval = new BufferedImage(heightPx, widthPx, imageType);
}
else
{
retval = new BufferedImage(widthPx, heightPx, imageType);
}
Graphics2D graphics = (Graphics2D) retval.getGraphics();
graphics.setBackground(TRANSPARENT_WHITE);
graphics.clearRect(0, 0, retval.getWidth(), retval.getHeight());
if (rotationAngle != 0)
{
int translateX = 0;
int translateY = 0;
switch (rotationAngle)
{
case 90:
translateX = retval.getWidth();
break;
case 270:
translateY = retval.getHeight();
break;
case 180:
translateX = retval.getWidth();
translateY = retval.getHeight();
break;
default:
break;
}
graphics.translate(translateX, translateY);
graphics.rotate((float) Math.toRadians(rotationAngle));
}
graphics.scale(scaling, scaling);
PageDrawer drawer = new MyPageDrawer(); // MyPageDrawer instead of PageDrawer
drawer.drawPage(graphics, page, pageDimension);
drawer.dispose();
graphics.dispose();
return retval;
}
public static void main(String[] args) throws IOException
{
String filename = "......./blah.pdf";
// open the document
PDDocument doc = PDDocument.loadNonSeq(new File(filename), null);
List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
for (int p = 0; p < pages.size(); ++p)
{
PDPage page = pages.get(p);
BufferedImage bim = convertToImage(page, BufferedImage.TYPE_INT_RGB, 300);
boolean b = ImageIOUtil.writeImage(bim, "page-" + (p + 1) + ".png", 300);
if (!b)
{
// error handling
}
}
doc.close();
}
}
I have this string: "This is my very long String that wont fit on one line"
And I need to split it into multiple lines so it'll fit where I need it.
Lets say theres only room for about 15 letters per line, then it should look like this:
"This is my very"
"long String"
"that wont fit"
"on one line"
I would like to split it into a List<String> so I can do
for(String s : lines) draw(s,x,y);
Any help on how to do this would be appriciated!
The way I'm rendering the text is with Graphics.drawString()
This is what I've tried so far (horrible, I know)
String diaText = "This is my very long String that wont fit on one line";
String[] txt = diaText.trim().split(" ");
int max = 23;
List<String> lines = new ArrayList<String>();
String s1 = "";
if (!(diaText.length() > max)) {
lines.add(diaText);
} else {
for (int i = 0; i < txt.length; i++) {
String ns = s1 += txt[i] + " ";
if (ns.length() < 23) {
lines.add(s1);
s1 = "";
} else {
s1 += txt[i] + "";
}
}
}
int yo = 0;
for (String s : lines) {
Font.draw(s, screen, 70, 15 + yo, Color.get(-1, 555, 555,555));
yo += 10;
}
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class LabelRenderTest {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
String title = "<html><body style='width: 200px; padding: 5px;'>"
+ "<h1>Do U C Me?</h1>"
+ "Here is a long string that will wrap. "
+ "The effect we want is a multi-line label.";
JFrame f = new JFrame("Label Render Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage image = new BufferedImage(
400,
300,
BufferedImage.TYPE_INT_RGB);
Graphics2D imageGraphics = image.createGraphics();
GradientPaint gp = new GradientPaint(
20f,
20f,
Color.red,
380f,
280f,
Color.orange);
imageGraphics.setPaint(gp);
imageGraphics.fillRect(0, 0, 400, 300);
JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());
Dimension d = textLabel.getPreferredSize();
BufferedImage bi = new BufferedImage(
d.width,
d.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 128));
g.fillRoundRect(
0,
0,
bi.getWidth(f),
bi.getHeight(f),
15,
10);
g.setColor(Color.black);
textLabel.paint(g);
Graphics g2 = image.getGraphics();
g2.drawImage(bi, 20, 20, f);
ImageIcon ii = new ImageIcon(image);
JLabel imageLabel = new JLabel(ii);
f.getContentPane().add(imageLabel);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
You could consider using LineBreakMeasurer which is intended for this sort of thing in a graphics environment. Please check out the JavaDocs here, which contain a couple of detailed examples on how to use it.