Java Minesweeper

this is my first swing app(i made it to help me better understand how this stuff works), and i have a few problems i need help fixing:
1: buttons are to large
2: a 3x3 field does not setup right
3: uses chn.util's Console IO for data input
4: want to be able to flag possilbe mines
i pretty much want my code looked through and if anyone sees anything pointless or something that might cause it to crash, let me know.
note: im still not entirely sure what main does... i just copied it from the tutorial page, if anyone can explain that ild apreciate that also
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
import chn.util.*;
import java.net.URL;
public class MineSweeper implements ActionListener
     int dimensions;
     JFrame MineSweeperFrame;
     JPanel MineSweeperPanel;
     JButton defaultBut;
     JButton[][] Buttons;
     JLabel[] labs;
     JLabel MineSweeperLabel;
     Location[][] Locations;
     ArrayList mineList;
     JFrame lossesFrame;
     JPanel lossesPanel;
     JLabel lossesLabel;
     static int lossCount;
     int numMines;
     public MineSweeper()
          ConsoleIO kb = new ConsoleIO();
          numMines=0;
          dimensions=0;
          while(dimensions<=0)
           System.out.println("How many columns/rows?");
           dimensions = kb.readInt();
          while(numMines>dimensions*dimensions -1 || numMines <= 0)
           System.out.println("How many Mines?");
           numMines = kb.readInt();
           if(numMines>dimensions*dimensions)
           System.out.println("Error: too many Mines.("+numMines+(numMines<dimensions*dimensions)+")");
           if(numMines<=0)
           System.out.println("Error: not enough Mines.("+numMines + (boolean)(numMines>=0) +")");
          setMines();
          MineSweeperLabel = new JLabel(" ");
          MineSweeperFrame = new JFrame("My Mine Sweeper");
          MineSweeperFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          MineSweeperFrame.setSize(new Dimension(250,200));
          MineSweeperPanel = new JPanel(new GridLayout(dimensions+1,dimensions));
          addWidgets();     
          MineSweeperFrame.getRootPane().setDefaultButton(defaultBut);
          MineSweeperFrame.getContentPane().add(MineSweeperPanel, BorderLayout.CENTER);
          MineSweeperFrame.pack();
          MineSweeperFrame.setVisible(true);
          lossesLabel = new JLabel("You Loose!");
          lossesFrame = new JFrame("Game Over");
          lossesFrame.setSize(new Dimension(300,500));
          lossesPanel = new JPanel(new GridLayout(1,2));
          lossesPanel.add(lossesLabel);
          lossesFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          lossesFrame.getContentPane().add(lossesPanel, BorderLayout.CENTER);     
          lossesFrame.pack();
     public void clearAllZeros(Location loc)//sets all buttons associated w/ a 0 to 0
          if(isNoConflict(loc))
               int x = loc.getX();
               int y = loc.getY();
               Buttons[x][y].setText("");
               Buttons[x][y].setEnabled(false);
               loc.setChecked(true);
               if(x<Locations.length-1 && !(Locations[x+1][y].isChecked()))
               clearAllZeros(Locations[x+1][y]);
               if(y<Locations.length-1 && !(Locations[x][y+1].isChecked()))
               clearAllZeros(Locations[x][y+1]);
               if(x>0 && !(Locations[x-1][y].isChecked()))
               clearAllZeros(Locations[x-1][y]);
               if(y>0 && !(Locations[x][y-1].isChecked()))
               clearAllZeros(Locations[x][y-1]);
               if(x<Locations.length-1 && y<Locations.length-1 && !(Locations[x+1][y+1].isChecked()))
               clearAllZeros(Locations[x+1][y+1]);
               if(x<Locations.length-1 && y>0 && !(Locations[x+1][y-1].isChecked()))
               clearAllZeros(Locations[x+1][y-1]);
               if(x>0 && y<Locations.length-1 && !(Locations[x-1][y+1].isChecked()))
               clearAllZeros(Locations[x-1][y+1]);
               if(x>0 && y>0 && !(Locations[x-1][y-1].isChecked()))
               clearAllZeros(Locations[x-1][y-1]);
               return;
          return;
     public boolean isNoConflict(Location loc)
          if(loc.nearMine() && !(loc.isMine()))
               Buttons[loc.getX()][loc.getY()].setText(""+loc.getTNum());
               Buttons[loc.getX()][loc.getY()].setMargin(new Insets(5, 5, 5, 5));
               Locations[loc.getX()][loc.getY()].setChecked(true);
               return false;
          else if(loc.isMine())
          return false;
          else return true;
     public void setMines()//randomly creates numMines mines(locations of mines are stored in mineList)
          mineList = new ArrayList();
          Locations = new Location[dimensions][dimensions];
          for(int i = 0; i < Locations.length;i++)
          for(int j = 0; j < Locations.length;j++)
          Locations[i][j] = new Location(i,j);
          Random r = new Random();
          int i = 0;
          int r1;
          int r2;
          while(i<numMines)
           r1=r.nextInt(dimensions);
           r2=r.nextInt(dimensions);
           if(!(Locations[r1][r2].isMine()))
                Locations[r1][r2].setMine();
                mineList.add(Locations[r1][r2]);
                i++;
          for(int j = 0; j<Locations.length;j++)
          for(int k=0; k<Locations.length;k++)
          setMineNeighbors(j,k);
     public void setMineNeighbors(int first, int second)
       int MineNeighbors = numMineNeighbors(first,second);
       for(int j = 0; j<MineNeighbors;j++)
       //if((isMine[((Location)nonMineNeighbors.get(j)).getX()][((Location)nonMineNeighbors.get(j)).getY()].isMine()))
        Locations[first][second].numPlusPlus();
        Locations[first][second].setNearMine();
     private class Location
          private boolean mine;
          private boolean locChecked;
          private boolean nearMine;
          private int myX;
          private int myY;
          private int myNum;
          public Location(int x, int y)
               nearMine=false;
               myNum =0;
               mine=false;
               locChecked = false;
               myX=x;
               myY=y;
          public boolean nearMine()
               return nearMine;
          public void setNearMine()
               nearMine=true;
          public void numPlusPlus()
               myNum++;
          public String getTNum()
               if(getNum()==1)
               return "<html><font color=blue>"+getNum()+"</font></html>";
               if(getNum()==2)
               return "<html><font color=green>"+getNum()+"</font></html>";
               if(getNum()==3)
               return "<html><font color=orange>"+getNum()+"</font></html>";
               if(getNum()==4)
               return "<html><font color=red>"+getNum()+"</font></html>";
               if(getNum()==5)
               return "<html><font color=purple>"+getNum()+"</font></html>";
               if(getNum()==6)
               return "<html><font color=brown>"+getNum()+"</font></html>";
               if(getNum()==7)
               return "<html><font color=black>"+getNum()+"</font></html>";
               if(getNum()==8)
               return "<html><font color=yellow>"+getNum()+"</font></html>";
               else
               return ""+getNum();
          public int getNum()
               return myNum;
          public int getX()
               return myX;
          public void setMine()
               mine =true;
          public boolean isMine()
               return mine;
          public int getY()
               return myY;
          public boolean isChecked()
               return locChecked;
          public void setChecked(boolean bol)
               locChecked = bol;
          public void resetStatus()
               for(int i = 0; i < Locations.length; i++)
               for(int j = 0; j < Locations.length; j++)
                Locations[i][j].setChecked(false);
                Buttons[i][j].setText("");
     public int numMineNeighbors(int firstNum, int secondNum)
          int num =0;
          if(firstNum < 0 || firstNum > Locations.length || secondNum < 0 || secondNum > Locations.length)
          return 0;
          if(!(firstNum+1 >= Locations.length))
          if(Locations[firstNum+1][secondNum].isMine())
          num++;
          if(!(secondNum+1 >= Locations.length))
          if(Locations[firstNum][secondNum+1].isMine())
          num++;
          if(!(secondNum-1 < 0))
          if(Locations[firstNum][secondNum-1].isMine())
          num++;
          if(!(firstNum-1 < 0))
          if(Locations[firstNum-1][secondNum].isMine())
          num++;
          if(!(firstNum+1 >= Locations.length || secondNum+1 >= Locations.length))
          if(Locations[firstNum+1][secondNum+1].isMine())
          num++;
          if(!(firstNum+1 >= Locations.length || secondNum-1 < 0))
          if(Locations[firstNum+1][secondNum-1].isMine())
          num++;
          if(!(firstNum-1 < 0 || secondNum+1 >= Locations.length))
          if(Locations[firstNum-1][secondNum+1].isMine())
          num++;
          if(!(firstNum-1 < 0 || secondNum-1 < 0))
          if(Locations[firstNum-1][secondNum-1].isMine())
          num++;
          return num;
     public static void createAndShowGUI()
          JFrame.setDefaultLookAndFeelDecorated(true);
          new MineSweeper();
     public void actionPerformed(ActionEvent a)
          String nums = a.getActionCommand();
          if(nums.equals("+")||nums.equals("-"))
               if(nums.equals("-"))
               defaultBut.setText("+");
               for(int b = 0; b<Buttons.length; b++)
               for(int c = 0; c<Buttons.length; c++)
                Buttons[b][c].setText("");
                Buttons[b][c].setEnabled(true);
                Locations[b][c].setChecked(false);
               setMines();
          String fnum="";
          String snum="";
          if(nums.length()>=3)
           int numf=0;
           int numss=0;
           fnum = nums.substring(0,nums.indexOf(" "));
           snum = nums.substring(nums.indexOf(" ")+1,nums.length());
           /*numf = nums.substring(0,nums.indexOf(" ")).length()-1;
           numss = nums.substring(nums.indexOf(" "),nums.length()-1).length()-1;
           for(int i =0; i < fnum.length(); i++)
           numf += ((((int)fnum.charAt(i))-48)*Math.pow(10,fnum.length()-i-1));
           for(int j =0; j < snum.length(); j++)
           numss += ((((int)snum.charAt(j))-48)*Math.pow(10,snum.length()-j-1));
          if(Locations[numf][numss].isMine())
               defaultBut.setText("-");
               for(int f =0; f<Buttons.length;f++)
              for(int g =0; g<Buttons.length;g++)
              Buttons[f][g].setEnabled(false);
               lossCount++;
               lossesLabel.setText("Losses: " +lossCount);
               lossesFrame.setVisible(true);
          if(numf >= 0 && numss >= 0 && numf <dimensions && numss < dimensions)
           Buttons[numf][numss].setText(Locations[numf][numss].getTNum() +"");
           Buttons[numf][numss].setMargin(new Insets(5, 5, 5, 5));
           Locations[numf][numss].setChecked(true);
           if(Locations[numf][numss].getNum()==0)
           clearAllZeros(Locations[numf][numss]);
           if(Locations[numf][numss].isMine())
           Buttons[numf][numss].setText("�");
          /*System.out.println((((int)fnum)-48) + "" + (((int)snum)-48));
          System.out.println(a.getActionCommand());*/     
          int count =0;
          for(int d =0; d<Locations.length;d++)
          for(int e =0; e<Locations.length;e++)
          if(!(Locations[d][e].isChecked()))
          count++;
          System.out.println("num unchecked "+(count-numMines));
          if(count==numMines)
               lossesLabel.setText("You Win!");
               lossesFrame.setVisible(true);
               System.out.println("You Win!");
     private void addWidgets()
          MineSweeperPanel.add(MineSweeperLabel);
          int ammount = dimensions-2;
          for(int i = 0; i<ammount/2-1; i++)
          MineSweeperPanel.add(new JLabel(""));
          defaultBut = new JButton("+");
          defaultBut.setMargin(new Insets(5, 5, 5, 5));
          defaultBut.addActionListener(this);
          MineSweeperPanel.add(defaultBut);
          if(dimensions%2==0)
          for(int i = 0; i<ammount/2+1; i++)
          MineSweeperPanel.add(new JLabel(""));
          if(dimensions%2!=0)
          for(int i = 0; i<ammount/2+2; i++)
          MineSweeperPanel.add(new JLabel(""));
          Buttons = new JButton[dimensions][dimensions];
          /*for(int i = 0; i < but1.length;i++)
           for(int j = 0; j < but1.length; j++)
                String first="";
               String last="";
                for(int k = 0; k <= i;k++)//adds i+1 \0 to string first(buttons[0][0]= "\0 \0",buttons[1][1]= "\0\0 \0\0")
                 first += "\0";
                 for(int l = 0; l <= j;l++)//adds j+1 \0 to string last
                 last += "\0";
                 but1[i][j]= new JButton(first + " " + last);
                 but1[i][j].addActionListener(this);
                 pan1.add(but1[i][j]);
          Buttons = new JButton[dimensions][dimensions];
          for(int i = 0; i < Buttons.length;i++)
           for(int j = 0; j < Buttons.length; j++)
            Buttons[i][j] = new JButton("");
            Buttons[i][j].setMaximumSize(new Dimension(5,5));
            Buttons[i][j].setActionCommand(i + " " + j);
            Buttons[i][j].addActionListener(this);
            defaultBut.setMargin(new Insets(5, 5, 5, 5));
            MineSweeperPanel.add(Buttons[i][j]);
     public static void main(String[] args)
       javax.swing.SwingUtilities.invokeLater(new Runnable()
                     public void run()
                         createAndShowGUI();
}

to make a (very) simple jar, run the JarMaker code in reply #3 here
http://forum.java.sun.com/thread.jspa?forumID=54&threadID=596973
(simple in the sense, it will only work under the simplest of conditions)
after you copy/paste it, you need to include
import java.awt.*;
before compiling (missed that line when posted)
this must be run in the same directory as minesweeper.java.
instructions are on the gui when run.
basically - you check the checkboxes for all the files you want to include in
the jar, and you also select the radio button for the .class file that contains 'main'
this only works with all files in the one directory, so if you have e.g. images in
images/flag.gif, they will need to go into the same directory as the minesweeper.java file,
and the minesweeper.java file modified - so do this with a backup copy of
your program in a temp directory,leaving the original unmodified.
if the jar file is successfully made, double-click it, see how it goes. Then move the
Minesweeper.jar file to some other directory, double-click and see if it works OK there.
Once you see the end result, you can go back to the jar docs and see if they
make any more sense, and if so, you can do it from the command prompt.
final point
if you have images, your code needs to get/load them as a resource e.g.
Image image = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Save.gif"), "Save.gif"));

Similar Messages

  • Question about laying out a maze and buttons

    I am very new to SWING, and I just finally figured out how to draw my maze. I am drawing it on a JPanel, using the layout manager. Then I plop that JPanel onto a JFrame. But now i want to have a program that has the JPanel, which is basically the maze, and two buttons far below, kind of like how a java minesweep game would look. Can somebody give me a hint as to how this is done? Do I have to put another JPanel, that holds this "maze JPanel," and which also holds 2 other places for buttons? Because if I just add the buttons to this JPanel, everythinig will be squished together right? How would a professional program lay this out?

    Well, the idea is you plan your layout ahead of time. The typical look of an application is:
    1) toolbar
    2) main window
    3) statusbar
    This layout suits the BorderLayout perfectly.
    Then take a look at you main window. If you main window consists of a single component then just add it to the center of the BorderLayout. If, however, it consists of multiple components then create a new JPanel add it to the center and determine the best LayoutManager to use. This can be a recursive process.
    So, to answer your question, yes, you would nest layout managers within layout managers (or JPanels within JPanels).

  • Java - Write And Read From memory Like CheatEngine ( Writing not working?)

    Hello Oracle Forum
    I came here some time ago to ask about javaFX , i solved all my issues and im right now waiting for javaFx tot ake over swing and hmm, im working on learning LIBGDX to create games in java.
    However, im in need to create an app to change values of memory to fix a bug in an old program that i have, and the only way until now is using cheatEngine, So i decided to take a tutorial and learn how to do that in java.
    Well, im able to read from the memory but the write isnt working somehow... Im posting the code here, if anyone can give me a hint, i would thank and a lot, because theres a community that really needs this app to automate the fix without using cheat engine.
    package MainStart;
    import com.br.HM.User32;
    import com.br.kernel.Kernel32;
    import com.sun.jna.Memory;
    import com.sun.jna.Native;
    import com.sun.jna.Pointer;
    import com.sun.jna.ptr.IntByReference;
    public class Cheater {
        static Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
        static User32 user32 = (User32) Native.loadLibrary("user32", User32.class);
        static int readRight = 0x0010;
        static int writeRight = 0x0020;
        //static int PROCESS_VM_OPERATION = 0x0008;
        public static void main(String[] args) {
            //Read Memory
            //MineSweeper = Campo Minado
            int pid = getProcessId("Campo Minado"); // get our process ID
            System.out.println("Pid = " + pid);
            Pointer readprocess = openProcess(readRight, pid); // open the process ID with read priviledges.
            Pointer writeprocess = openProcess(writeRight, pid);
            int size = 4; // we want to read 4 bytes
            int address = 0x004053C8;
            //Read Memory
            Memory read = readMemory(readprocess, address, size); // read 4 bytes of memory starting at the address 0x00AB0C62.
            System.out.println(read.getInt(0)); // print out the value!      
            //Write Memory
            int writeMemory = writeMemory(writeprocess, address, new short[0x22222222]);
            System.out.println("WriteMemory :" + writeMemory);
            Memory readM = readMemory(readprocess, address, size);
            System.out.println(readM.getInt(0));
        public static int writeMemory(Pointer process, int address, short[] data) {
            IntByReference written = new IntByReference(0);
            Memory toWrite = new Memory(data.length);
            for (long i = 0; i < data.length; i++) {
                toWrite.setShort(0, data[new Integer(Long.toString(i))]);
            boolean b = kernel32.WriteProcessMemory(process, address, toWrite, data.length, written);
            System.out.println("kernel32.WriteProcessMemory : " + b); // Retorna false
            return written.getValue();
        public static Pointer openProcess(int permissions, int pid) {
            Pointer process = kernel32.OpenProcess(permissions, true, pid);
            return process;
        public static int getProcessId(String window) {
            IntByReference pid = new IntByReference(0);
            user32.GetWindowThreadProcessId(user32.FindWindowA(null, window), pid);
            return pid.getValue();
        public static Memory readMemory(Pointer process, int address, int bytesToRead) {
            IntByReference read = new IntByReference(0);
            Memory output = new Memory(bytesToRead);
            kernel32.ReadProcessMemory(process, address, output, bytesToRead, read);
            return output;
    package com.br.HM;
    import com.sun.jna.Native;
    import com.sun.jna.Pointer;
    import com.sun.jna.Structure;
    import com.sun.jna.platform.win32.WinDef.RECT;
    import com.sun.jna.ptr.ByteByReference;
    import com.sun.jna.ptr.IntByReference;
    import com.sun.jna.win32.StdCallLibrary.StdCallCallback;
    import com.sun.jna.win32.W32APIOptions;
    * Provides access to the w32 user32 library. Incomplete implementation to
    * support demos.
    * @author Todd Fast, [email protected]
    * @author [email protected]
    public interface User32 extends W32APIOptions {
        User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, DEFAULT_OPTIONS);
        Pointer GetDC(Pointer hWnd);
        int ReleaseDC(Pointer hWnd, Pointer hDC);
        int FLASHW_STOP = 0;
        int FLASHW_CAPTION = 1;
        int FLASHW_TRAY = 2;
        int FLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY);
        int FLASHW_TIMER = 4;
        int FLASHW_TIMERNOFG = 12;
        public static class FLASHWINFO extends Structure {
            public int cbSize;
            public Pointer hWnd;
            public int dwFlags;
            public int uCount;
            public int dwTimeout;
        int IMAGE_BITMAP = 0;
        int IMAGE_ICON = 1;
        int IMAGE_CURSOR = 2;
        int IMAGE_ENHMETAFILE = 3;
        int LR_DEFAULTCOLOR = 0x0000;
        int LR_MONOCHROME = 0x0001;
        int LR_COLOR = 0x0002;
        int LR_COPYRETURNORG = 0x0004;
        int LR_COPYDELETEORG = 0x0008;
        int LR_LOADFROMFILE = 0x0010;
        int LR_LOADTRANSPARENT = 0x0020;
        int LR_DEFAULTSIZE = 0x0040;
        int LR_VGACOLOR = 0x0080;
        int LR_LOADMAP3DCOLORS = 0x1000;
        int LR_CREATEDIBSECTION = 0x2000;
        int LR_COPYFROMRESOURCE = 0x4000;
        int LR_SHARED = 0x8000;
        Pointer FindWindowA(String winClass, String title);
        int GetClassName(Pointer hWnd, byte[] lpClassName, int nMaxCount);
        public static class GUITHREADINFO extends Structure {
            public int cbSize = size();
            public int flags;
            Pointer hwndActive;
            Pointer hwndFocus;
            Pointer hwndCapture;
            Pointer hwndMenuOwner;
            Pointer hwndMoveSize;
            Pointer hwndCaret;
            RECT rcCaret;
        boolean GetGUIThreadInfo(int idThread, GUITHREADINFO lpgui);
        public static class WINDOWINFO extends Structure {
            public int cbSize = size();
            public RECT rcWindow;
            public RECT rcClient;
            public int dwStyle;
            public int dwExStyle;
            public int dwWindowStatus;
            public int cxWindowBorders;
            public int cyWindowBorders;
            public short atomWindowType;
            public short wCreatorVersion;
        boolean GetWindowInfo(Pointer hWnd, WINDOWINFO pwi);
        boolean GetWindowRect(Pointer hWnd, RECT rect);
        int GetWindowText(Pointer hWnd, byte[] lpString, int nMaxCount);
        int GetWindowTextLength(Pointer hWnd);
        int GetWindowModuleFileName(Pointer hWnd, byte[] lpszFileName, int cchFileNameMax);
        int GetWindowThreadProcessId(Pointer hWnd, IntByReference lpdwProcessId);
        interface WNDENUMPROC extends StdCallCallback {
             * Return whether to continue enumeration.
            boolean callback(Pointer hWnd, Pointer data);
        boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer data);
        boolean EnumThreadWindows(int dwThreadId, WNDENUMPROC lpEnumFunc, Pointer data);
        boolean FlashWindowEx(FLASHWINFO info);
        Pointer LoadIcon(Pointer hInstance, String iconName);
        Pointer LoadImage(Pointer hinst, // handle to instance
                String name, // image to load
                int type, // image type
                int xDesired, // desired width
                int yDesired, // desired height
                int load // load options
        boolean DestroyIcon(Pointer hicon);
        int GWL_EXSTYLE = -20;
        int GWL_STYLE = -16;
        int GWL_WNDPROC = -4;
        int GWL_HINSTANCE = -6;
        int GWL_ID = -12;
        int GWL_USERDATA = -21;
        int DWL_DLGPROC = 4;
        int DWL_MSGRESULT = 0;
        int DWL_USER = 8;
        int WS_EX_COMPOSITED = 0x20000000;
        int WS_EX_LAYERED = 0x80000;
        int WS_EX_TRANSPARENT = 32;
        int GetWindowLong(Pointer hWnd, int nIndex);
        int SetWindowLong(Pointer hWnd, int nIndex, int dwNewLong);
        int LWA_COLORKEY = 1;
        int LWA_ALPHA = 2;
        int ULW_COLORKEY = 1;
        int ULW_ALPHA = 2;
        int ULW_OPAQUE = 4;
        boolean SetLayeredWindowAttributes(Pointer hwnd, int crKey,
                byte bAlpha, int dwFlags);
        boolean GetLayeredWindowAttributes(Pointer hwnd,
                IntByReference pcrKey,
                ByteByReference pbAlpha,
                IntByReference pdwFlags);
         * Defines the x- and y-coordinates of a point.
        public static class POINT extends Structure {
            public int x, y;
         * Specifies the width and height of a rectangle.
        public static class SIZE extends Structure {
            public int cx, cy;
        int AC_SRC_OVER = 0x00;
        int AC_SRC_ALPHA = 0x01;
        int AC_SRC_NO_PREMULT_ALPHA = 0x01;
        int AC_SRC_NO_ALPHA = 0x02;
        public static class BLENDFUNCTION extends Structure {
            public byte BlendOp = AC_SRC_OVER; // only valid value
            public byte BlendFlags = 0; // only valid value
            public byte SourceConstantAlpha;
            public byte AlphaFormat;
        boolean UpdateLayeredWindow(Pointer hwnd, Pointer hdcDst,
                POINT pptDst, SIZE psize,
                Pointer hdcSrc, POINT pptSrc, int crKey,
                BLENDFUNCTION pblend, int dwFlags);
        int SetWindowRgn(Pointer hWnd, Pointer hRgn, boolean bRedraw);
        int VK_SHIFT = 16;
        int VK_LSHIFT = 0xA0;
        int VK_RSHIFT = 0xA1;
        int VK_CONTROL = 17;
        int VK_LCONTROL = 0xA2;
        int VK_RCONTROL = 0xA3;
        int VK_MENU = 18;
        int VK_LMENU = 0xA4;
        int VK_RMENU = 0xA5;
        boolean GetKeyboardState(byte[] state);
        short GetAsyncKeyState(int vKey);
    package com.br.kernel;
    import com.sun.jna.*;
    import com.sun.jna.win32.StdCallLibrary;
    import com.sun.jna.ptr.IntByReference;
    // by deject3d
    public interface Kernel32 extends StdCallLibrary
        // description from msdn
        //BOOL WINAPI WriteProcessMemory(
        //__in   HANDLE hProcess,
        //__in   LPVOID lpBaseAddress,
        //__in   LPCVOID lpBuffer,
        //__in   SIZE_T nSize,
        //__out  SIZE_T *lpNumberOfBytesWritten
        boolean WriteProcessMemory(Pointer p, int address, Pointer buffer, int size, IntByReference written);
        //BOOL WINAPI ReadProcessMemory(
        //          __in   HANDLE hProcess,
        //          __in   LPCVOID lpBaseAddress,
        //          __out  LPVOID lpBuffer,
        //          __in   SIZE_T nSize,
        //          __out  SIZE_T *lpNumberOfBytesRead
        boolean ReadProcessMemory(Pointer hProcess, int inBaseAddress, Pointer outputBuffer, int nSize, IntByReference outNumberOfBytesRead);
        //HANDLE WINAPI OpenProcess(
        //  __in  DWORD dwDesiredAccess,
        //  __in  BOOL bInheritHandle,
        //  __in  DWORD dwProcessId
        Pointer OpenProcess(int desired, boolean inherit, int pid);
        /* derp */
        int GetLastError();
    http://pastebin.com/Vq8wfy39

    Hello there,
    this tutorial was exactly what I needed, so thank you.
    Your problem seems to be in this line:
    int writeMemory = writeMemory(writeprocess, address, new short[0x22222222]); 
    The problem is, you're creating a new short array with the length of 0x22222222. Which not only results in an java.lang.OutOfMemoryError: Java heap space
    but also, if it would work, would create an empty array with the length of 0x22222222.
    I think you want to write 0x22222222 as value in your address.
    Correctly stored the code you'd need to write would be:
    short[] sarray = new short[]{(short) 0x22222222};
    But because the value is too long for the short, the value stored in your array would be the number 8738.
    I think, what you want to do is to store the number 572662306, which would be the hex value, stored in an int variable.
    So first of all you need to strip down your hex-value to shorts:
    Short in Java uses 16 Bit = 2 Byte. 0x22222222 -> 0x2222 for your high byte and 0x2222 for your low byte
    So your array would be
    short[] sarray = new short[]{0x2222,0x2222};//notice, that sarray[0] is the lowbyte and sarray[1] the high byte, if you want to store 20 it would be new short[]{20,0} or if you use hex new short[]{0x14,0x00}
    The next part is your writeToMemory Method. If I'm right, the method in the tutorial is a little bit wrong. The right version should be this:
    public static int writeMemory(Pointer process, int address, short[] data) {
      IntByReference written = new IntByReference(0);
      int size = data.length*Short.SIZE/8;
      Memory toWrite = new Memory(size);
      for (int i = 0; i < data.length; i++) {
      toWrite.setShort(i*Short.SIZE/8,
      data[i]);
      boolean b = kernel32.WriteProcessMemory(process, address, toWrite,
      size, written);
      return written.getValue();
    You need to calculate your offset right. And the size of your memory. Maybe you could write this method not with shorts, but with integers. But this should work.
    If you pass your new array to this function, it should write 0x22222222 to your adress. If you read out your toWrite value with toWrite.getInt(0) you get the right value.
    And there is one more thing. In order to write data to a process, you need to grant two access rights:
    A handle to the process memory to be modified. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process.
    You have to grant the right to write data: PROCESS_VM_WRITE: 0x0020 and PROCESS_VM_OPERATION: 0x0008
    So your writeProcess needs to get initialized this way:
    Pointer writeprocess = openProcess(0x0020|0x0008,pid);
    I hope this works for you. Let me know.
    Greetings
    Edit:
    Because every data you write will be 1 byte to whatever count of byte I think the best way is to use the following method to write data to the memory:
    public static void writeMemory(Pointer process, long address, byte[] data)
      int size = data.length;
      Memory toWrite = new Memory(size);
      for(int i = 0; i < size; i++)
      toWrite.setByte(i, data[i]);
      boolean b = kernel32.WriteProcessMemory(process, address, toWrite, size, null);
    You can see some changes. First I changed all address values from int to long, because some addresses are out of range. And with all, i mean all. Not only in writeMemory, but also in readMemory and in your kernel32 Class.
    Second I don't use the IntByReference anymore..
    To use this method you need to store your data the following way if you would write 4 Byte data:
    byte[] values = new byte[]{0x14,0x00,0x00,0x00};
    This value would be the number 20. Index 0 will be the lowest byte and index 3 will be the highest byte.
    And one more thing I wrote is an method which you can use to calculate your address if you have a baseAddress.
    If you restart your program/game your old addresses won't point at the same values of your game. With some research (I use CheatEngine) you can get the baseaddress. This one will alway be the same.
    To get from your baseaddress to the dynamic adress you use offsets.
    public static long findDynAddy(Pointer process, int[] offsets, long baseAddress)
      long pointer = baseAddress;
      int size = 4;
      Memory pTemp = new Memory(size);
      long pointerAddress = 0;
      for(int i = 0; i < offsets.length; i++)
      if(i == 0)
      kernel32.ReadProcessMemory(process, pointer, pTemp, size, null);
      pointerAddress = ((pTemp.getInt(0)+offsets[i]));
      if(i != offsets.length-1)
      kernel32.ReadProcessMemory(process, pointerAddress, pTemp, size, null);
      return pointerAddress;
    This methods gets a process, an array of offsets (hex-values) and your baseadress and returns the dynamic address.
    For Solitaire the following code would give you the address to the score:
    long baseAddr = 0x10002AFA8L;
      int[] offsets = new int[]{0x50,0x14};
      long addr = findDynAddy(process, offsets, baseAddr);
    If somebody wants to get the whole code (user32, kernel32 and the cheater) just pm me and I will give you a link.

  • How to compile ALL java files in OR UNDER a given directory?

    G'Day Folkies,
    At face value, TikeSwing looks like the money shot for enforcing MVC in my version of minesweeper http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5248903
    I'm attempting to build the "Hello World" example which comes with TikeSwing.
    http://www.javaworld.com/javaworld/jw-06-2005/jw-0620-tikeswing.html
    It compiles ok
    C:\Java\lib\tikeswing-1.5\example\src\fi\mmm\hello>javac -d C:\Java\home\classes -cp C:\Java\lib\tikeswing-1.5\src;C:\Java\lib\tikes
    wing-1.5\lib\commons-beanutils.jar;C:\Java\lib\tikeswing-1.5\lib\commons-lang-2.0.jar;C:\Java\lib\tikeswing-1.5\lib\commons-logging.
    jar;C:\Java\lib\tikeswing-1.5\lib\log4j.jar;C:\Java\lib\tikeswing-1.5\example\src;. HelloApplication.java
    Note: Some input files use unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    But it doesn't run
    I presume that javac isn't detecting all dependancies, presumably because Tike "decouples M from V from C" using reflections.
    C:\Java\lib\tikeswing-1.5\example\src\fi\mmm\hello>java -cp C:\Java\home\classes;C:\Java\lib\tikeswing-1.5\lib\commons-beanutils.jar
    ;C:\Java\lib\tikeswing-1.5\lib\commons-lang-2.0.jar;C:\Java\lib\tikeswing-1.5\lib\commons-logging.jar;C:\Java\lib\tikeswing-1.5\lib\
    log4j.jar;C:\Java\lib\tikeswing-1.5\example\src;C:\Java\lib\tikeswing-1.5\src;. fi.mmm.hello.HelloApplication
    Exception in thread "main" java.lang.NoClassDefFoundError: fi/mmm/yhteinen/swing/core/component/YFrame
            at java.lang.ClassLoader.defineClass1(Native Method)
            at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
            at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
            at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
            at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
            at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
            at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
            at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
            at fi.mmm.hello.HelloController.<init>(HelloController.java:8)
            at fi.mmm.hello.HelloApplication.main(HelloApplication.java:8)So, Please, is there a way of telling javac to just build *.java in or under C:\Java\lib\tikeswing-1.5\src\ ... regardless of dependencies?
    Thanking You for any thoughts. Keith.

    FYI.... Here's the quick and dirty, slower than a wet week, ugly, but effective batch script
    set TIKE=C:\Java\lib\tikeswing-1.5
    set SRC=%TIKE%\src
    set LIB=%TIKE%\lib
    set CLASSPATH=%LIB%\commons-beanutils.jar;%LIB%\commons-lang-2.0.jar;%LIB%\commons-logging.jar;%LIB%\log4j.jar;.
    FOR /R %SRC% %%f IN (*.java) DO javac -d C:\Java\home\classes -cp %CLASSPATH% %%f
    @ECHO OFF
    REM http://www.robvanderwoude.com/ntfor.html
    REM Walks the directory tree rooted at [drive:]path, executing the FOR statement
    REM in each directory of the tree. If no directory specification is specified
    REM after /R then the current directory is assumed. If set is just a single
    REM period (.) character then it will just enumerate the directory tree.I can't figure out how do the equivalent of javac `dir /s /b *.java` (ie: cmd doesn't seem to have a built-in facility for expanding the results of a command into the command line) which would be a lot quicker and cleaner.
    Cheers all. Thanx for the help. I appreciate it.

  • Java Web Services Editor?

    Hai there. I am new for Java Web Services.
    Can anyone tell what editor that can I use to write the Java Web Services?
    All the tutorial here are compile and run using dos environment.
    Then what editor that I can use for writing the code?
    Is that using jBuilder or else?

    Hi,
    You can use anything to write the web services. Even a notepad is good enough.
    But if you have anything that can format and highlight xml tags/java source in different color scemes it might be better. A simple text editor is sufficient for you to get started with web services.
    As for the examples and tutorial you can compile and run them in any environment. If ant scripts are used sometimes as newer version of ant is required to run a few task definitions which were not well suited for ant versions lower to 1.5.1
    Hope these answer your query
    Aviroop
    MCSE
    (Minesweeper Consultant & Solitaire Expert)

  • Help required in Minesweeper Game

    I am a novice in AWT and Applet programmer . I am presently making Minesweeper game. I have already done the background coding to generate random field in grid layout(9,9) . Now point where I have stuck what, is that , when I click any button. it must be replaced by a label on its ActionPerformed method. How can I do it...?
    PS:It would be more helpful if you reply with a small code as well.
    (Dummy example with may be (2,2) grid with 1 button in each grid is present and when any button is clicked it is replaced by Label with do fine).
    Thank You in anticipation...

    GridLayout was not designed to have components added and removed at arbitrary points. In order to have your original requirement, it would be necessary to add each Button to a Panel and add the Panel to the GridLayout. When it comes time to swap the Button for a Label, get a reference to the Button's owner, remove the button from the owner, then add the Label. The same effect could also be handled by setting the layout of the parent Panel to a CardLayout, and flipping between two cards, one of which is a Button, the other of which is the Label.
    2 points.
    1) tjacobs01 suggested an altogether better strategy for this.
    2) If you are determined to have each component as a separate component, why not try simply making the button change the label from 'C' to whatever you want. E.G.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    //<applet code = "ButtonToLabel" width="200" height="200"></applet>
    public class ButtonToLabel extends Applet implements ActionListener
         Button myB1,myB2,myB3,myB4;
         public void init()
              setLayout(new GridLayout(2,2));
              myB1 = new Button("A");
              myB2 = new Button("B");
              myB3 = new Button("Click Here...");
              myB3.addActionListener(this);        //ActionListener only on myB3 button
              myB4 = new Button("D");
         public void start()
              add(myB1);
              add(myB2);
              add(myB3);
              add(myB4);
         public void actionPerformed(ActionEvent ae)
              if(ae.getSource()==myB3)
                   myB3.setLabel("C");
    }

  • Generate a new (random) mine field?? for minesweeper

    I have to create a minesweeper game for my java class.
    but im having trouble creating the method to generate a random mine field?!?!
    (i dont even know where to start)
    public static boolean [][] generateMineField ( int length, int width, int numberMines)This method generates a new mine field as a matrix of boolean values where a cell is set to "true" to indicate the presence of a mine. The length and the width of the field are provided, and also the desired number of mines (numberMines).
    Hint: Use Math.random(), Math.floor(), and type cast to generate random positions for the mines.
    ThanK You!

    One thread is enough...
    [http://forums.sun.com/thread.jspa?threadID=5347127&tstart=0]

  • Minesweeper

    I have made a minesweeper game. It works well with Windows XP and java 1.4.1, but I have tried it with windows NT and java 1.4.0 and it doesn't work. (the mouse doesn't work). It throws an Exception (or was it an Error?) about native methods and libraries and creates a log file. I don't have NT now so I can't say exactly what exception.
    Can you check it if it works with your PC?
    It is at:
    http://www.geocities.com/myavuzselim/minesweeper.jar
    Has it something to do with Windows NT or something else?
    Thank you.

    Works fine for me. Can you give us the exact exception?

  • Minesweeper problem

    Formerly i write this game code using just J2SE 1.5 SDK and notepad in windows environment. Any i made it succesfully in the sense that i can play in command prompt, without any GUI elements. Now, when i am trying to implement GUI with netbeans 5.0, i have problem in accessing the game cells correctly.
    Please hv a look at the code and comment. I am using the recursion in unlocking empty cells when user click on one of the empty cells as in the Minesweeper in Windows XP.
    BombCell.class is the cell.
    GamePlatform.class is the platform that i declare array to store BombCell instances and calculate the number of bombs surrounding the clicked cell.
    * Main.java
    * Created on 26 September 2006, 23:39
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package minesweeper3;
    import javax.swing.*;
    import java.awt.*;
    * @author Raymond
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            GamePlatform game1 = new GamePlatform();
            JFrame gameFrame = new JFrame("Game Frame");
            Dimension gamePanel = new Dimension();
            game1.setBombIntoArray();
            game1.viewBomb();
            gameFrame.setSize(new Dimension(400,400));
            gameFrame.setLocation(200,200);
    //        gameFrame.setResizable(false);
            gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            gameFrame.getContentPane().add(game1,BorderLayout.NORTH);
            gameFrame.setVisible(true);
    * GamePlatform.java
    * Created on 26 September 2006, 23:57
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package minesweeper3;
    import java.util.Random;
    import java.lang.Math;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.border.LineBorder;
    * @author Raymond
    public class GamePlatform extends JPanel implements MouseListener{
        public int randomNum1;
        public int randomNum2;
        public BombCell[][] CellArray = new BombCell[10][10];    
        private FlowLayout cellLayout = new FlowLayout(3,0,0);
        /** Creates a new instance of GamePlatform */
        public GamePlatform() {
            this.addMouseListener(this);
            this.setPreferredSize(new Dimension(305,335));
            this.setLayout(cellLayout);
    //        this.setBorder(new LineBorder(Color.red, 1));
        public void setBombIntoArray()
            for(int i = 0; i < 10; i++)
                for(int j = 0; j < 10; j++)
                    this.CellArray[i][j] = new BombCell(false);
                    this.add(CellArray[i][j]);
            Random numGenerator = new Random(System.currentTimeMillis());
            int i = 0;
            do
                randomNum1 = numGenerator.nextInt() % 10;
                randomNum2 = numGenerator.nextInt() % 10;
                randomNum1 = Math.abs(randomNum1);
                randomNum2 = Math.abs(randomNum2);
                if(!this.CellArray[randomNum1][randomNum2].accessBombCell())
                    this.setBombIntoCell(randomNum1,randomNum2);
                    i++;
                else
                    continue;
            }while(i < 10);
        public void setBombIntoCell(int num1, int num2)
            this.CellArray[num1][num2].setBomb();
         public void viewBomb()
            for(int i = 0; i < 10; i++)
                for(int j = 0; j < 10; j++)
                    if(this.CellArray[i][j].accessBombCell())
                        System.out.println("CellArray["+i+"]["+j+"] is a bomb");
        public void accessCell(int Num1, int Num2)
            Num1 = Num1 / 30;
            Num2 = Num2 / 30;
            if(this.CellArray[Num1][Num2].accessBombCell())
                this.CellArray[Num1][Num2].showBomb();
    //            System.exit(1);
            else if(this.calculateBombs(Num1,Num2) != 0)
                this.CellArray[Num1][Num2].showNumOfBombs(this.calculateBombs(Num1,Num2));
                this.CellArray[Num1][Num2].setAccessed();
            else
                this.CellArray[Num1][Num2].setAccessed();
                this.CellArray[Num1][Num2].showNumOfBombs(this.recursiveCalculate(Num1,Num2));
        public int calculateBombs(int num1, int num2)
            int BombsSurrounding = 0;
           for(int i = num1-1; i < num1+2; i++)
                for(int j = num2-1; j < num2+2; j++)
                    if(i < 0 || i > 9 || j < 0 || j > 9)
                        continue;
                    else if(this.CellArray[i][j].accessBombCell())
                        BombsSurrounding++;
            return BombsSurrounding;
        public int recursiveCalculate(int x, int y)
            int BombsAround = 0;
            outer:
                for(int i = x-1; i < x+2; i++)
                inner:
                    for(int j = y-1; j < y+2; j++)
                           if(this.calculateBombs(i,j) != 0)
                               if(i < 0 || i > 9 || j < 0 || j > 9 || this.CellArray[i][j].checkAccess() || (i == x && j == y))
                                   continue inner;
                               else
                                   this.CellArray[i][j].showNumOfBombs(this.calculateBombs(i,j));
                                   this.CellArray[i][j].setAccessed();
                           else
                               if(i < 0 || i > 9 || j < 0 || j > 9 || this.CellArray[i][j].checkAccess() || (i == x && j == y)) // i == x && j == y for exactly the same cell chosen
                                   continue inner;
                               else
                                   this.CellArray[i][j].setAccessed();
                                   this.CellArray[i][j].showNumOfBombs(this.recursiveCalculate(i,j));
            return (this.calculateBombs(x,y));
        public void printFlag(int Num1,int Num2)
            Num1 = Num1 / 30;
            Num2 = Num2 / 30;
            this.CellArray[Num1][Num2].showFlag();
        public void mouseClicked(MouseEvent evt)
            if(!evt.isMetaDown())
                this.accessCell(evt.getY(), evt.getX());
            else
                this.printFlag(evt.getY(), evt.getX());
        public void mousePressed(MouseEvent evt)
        public void mouseReleased(MouseEvent evt)
        public void mouseEntered(MouseEvent evt)
        public void mouseExited(MouseEvent evt)
    * BombCell.java
    * Created on 26 September 2006, 23:39
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package minesweeper3;
    import javax.swing.JLabel;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * @author Raymond
    public class BombCell extends JLabel{
        private boolean bomb;
        private boolean accessed ;
        Border lineBorder = new LineBorder(Color.blue, 1);
        /** Creates a new instance of BombCell */
        public BombCell(boolean setBomb)
            this.bomb = setBomb;
            this.setHorizontalAlignment(SwingConstants.CENTER);
            this.setVerticalAlignment(SwingConstants.CENTER);
            this.setBackground(Color.yellow);
            this.setPreferredSize(new Dimension(30,30));
            this.setBorder(lineBorder);
    //    public void paintComponent(Graphics g)
    //        Graphics2D graphics = (Graphics2D) g;
    //        graphics.fillRect(0,0,30,30);
        public void setBomb()
            this.bomb = true;
        public boolean accessBombCell()
            return this.bomb;
        public void setAccessed()
            this.accessed = true;
        public boolean checkAccess()
            return accessed;
        public void showNumOfBombs(int num)
            if(num > 0)
                this.setText(""+num);
            else if(num == 0)
                this.setText(""+num);
            else
                this.setText("Error");
        public void showBomb()
            this.setIcon(new ImageIcon(getClass().getResource("/Physics2005_small.gif")));
        public void showFlag()
            this.setIcon(new ImageIcon(getClass().getResource("/lambologo_sml.jpg")));
            this.setText("");
    }

    bluez_exe wrote:
    i was starting to make java programmed games so i started on a Minesweeper game..
    i saw this problem but i don't know how to continue it...What problem? You don't show us an error message, compiler error, logic issue, or anything.
    please help... this is the worded problem and instructions(you can download the file here): http://cid-507d9fd0c94168c2.skydrive.live.com/self.aspx/.Public/Minesweeper%20set.rar
    Nobody wants to follow links. Post an [SSCCE |http://sscce.org] that shows your problem.
    my initial code is: When posting code, make sure you use the code tags. Highlight your code and press the CODE button in the forum text editor.

  • Error while running a Java Program

    Can anyone help me,
    I am getting the following error while running a Java program, Below is the exception thrown, please help.
    java.nio.BufferOverflowException
    at java.nio.Buffer.nextPutIndex(Buffer.java:425)
    at java.nio.DirectByteBuffer.putChar(DirectByteBuffer.java:463)
    at org.jetel.data.StringDataField.serialize(StringDataField.java:295)
    at org.jetel.data.DataRecord.serialize(DataRecord.java:283)
    at org.jetel.graph.DirectEdge.writeRecord(DirectEdge.java:216)
    at org.jetel.graph.Edge.writeRecord(Edge.java:288)
    at com.tcs.re.component.RESummer1.run(RESummer1.java:505)
    java.nio.BufferOverflowException
    at java.nio.Buffer.nextPutIndex(Buffer.java:425)
    at java.nio.DirectByteBuffer.putChar(DirectByteBuffer.java:463)
    at org.jetel.data.StringDataField.serialize(StringDataField.java:295)
    at org.jetel.data.DataRecord.serialize(DataRecord.java:283)
    at org.jetel.graph.DirectEdge.writeRecord(DirectEdge.java:216)
    at org.jetel.graph.Edge.writeRecord(Edge.java:288)
    at com.tcs.re.component.RECollectCont.run(RECollectCont.java:304)

    Ok, let's see. Write the following class:
    public class Grunt {
      public static void main(String[] args) {
        System.out.println("Hello Mars");
    }Save it as "C:\Grunt.java", compile by typing:
    javac c:\Grunt.javaRun by typing:
    java -classpath "C:\" GruntDoes it say "Hello Mars"? If yes, go back to your program and compare for differences (maybe you used the "package" statement?).
    Regards

  • Erro de SYSFAIL e Queda do Ambiente JAVA (PI)

    Bom Dia
    Estou num projeto de NFe e atualmente esta acontecendo o seguinte cenário de Erros:
        Na SMQ2 , quando apresenta um aumento nas filas de Mensagens , aparece SYSFAIL em determinadas Filas , todas as outras travam , aumenta o numero de Filas.
       Com essa mensagem de SYSFAIL nas filas , o serve0 (Parte JAVA do PI) cai e após isso estou tendo que efetuar manualmente um STOP/START em todos os canais de comunnicação para que os R/3 voltem a emitir NFe.
        Isso esta ocorrendo com mais frequência após inserir uma nova empresa para emissão de NFe.
        Alguem poderia me ajudar a entender por que ocorre o SYSFAIL as mensagens travam e derruba o ambiente JAVA ?
    Sérgio.

    1º) Erro: Commit Fault: com.sap.aii.af.rfc.afcommunication.RfcAFWException:SenderA
    2º) Foi alterado o numero de Filas O numero de Filas foi alterado , mas não consigo ver esse parametros na RZ10 , tem  3 entradas : X32_DVEBMGS32_NFISAP ; DEFAULT ; START_DVEBMGS32_NFISAP nessa transação ...onde eu vejo isso
    3º) Esse parametro não tem nessa transação (/usr/sap//DVEBMGS00/j2ee/cluster/server0/log/). em qual desses diretórios abaixo eu encontro esse parametro ?
    Existe esses:
    DIR_ATRA      /usr/sap/X32/DVEBMGS32/data
    DIR_BINARY      /usr/sap/X32/DVEBMGS32/exe
    DIR_CCMS      /usr/sap/ccms
    DIR_CT_LOGGIN    /usr/sap/X32/SYS/global
    DIR_CT_RUN              /usr/sap/X32/SYS/exe/run
    DIR_DATA              /usr/sap/X32/DVEBMGS32/data
    DIR_DBMS              /usr/sap/X32/SYS/SAPDB
    DIR_EXECUTABLE /usr/sap/X32/DVEBMGS32/exe
    DIR_EXE_ROOT     /usr/sap/X32/SYS/exe
    DIR_GEN              /usr/sap/X32/SYS/gen/dbg
    DIR_GEN_ROOT    /usr/sap/X32/SYS/gen
    DIR_GLOBAL        /usr/sap/X32/SYS/global
    DIR_GRAPH_EXE  /usr/sap/X32/DVEBMGS32/exe
    DIR_GRAPH_LIB   /usr/sap/X32/DVEBMGS32/exe
    DIR_HOME             /usr/sap/X32/DVEBMGS32/work
    DIR_INSTALL        /usr/sap/X32/SYS
    DIR_INSTANCE     /usr/sap/X32/DVEBMGS32
    DIR_LIBRARY      /usr/sap/X32/DVEBMGS32/exe
    DIR_LOGGING     /usr/sap/X32/DVEBMGS32/log
    DIR_MEMORY_INSPECTOR   /usr/sap/X32/DVEBMGS32/data
    DIR_ORAHOME       /oracle/X32/102_64
    DIR_PAGING                            /usr/sap/X32/DVEBMGS32/data
    DIR_PUT                            /usr/sap/X32/put
    DIR_PERF                            /usr/sap/tmp
    DIR_PROFILE      /usr/sap/X32/SYS/profile
    DIR_PROTOKOLLS     /usr/sap/X32/DVEBMGS32/log
    DIR_REORG                          /usr/sap/X32/DVEBMGS32/data
    DIR_ROLL                          /usr/sap/X32/DVEBMGS32/data
    DIR_RSYN                            /usr/sap/X32/DVEBMGS32/exe
    DIR_SAPHOSTAGENT     /usr/sap/hostctrl
    DIR_SAPUSERS     ./
    DIR_SETUPS                           /usr/sap/X32/SYS/profile
    DIR_SORTTMP     /usr/sap/X32/DVEBMGS32/data
    DIR_SOURCE     /usr/sap/X32/SYS/src
    DIR_TEMP                           /tmp
    DIR_TRANS                           /usr/sap/trans
    DIR_TRFILES                          /usr/sap/trans
    DIR_TRSUB                          /usr/sap/trans

  • Starting deployment prerequisites: error in BI-Java installation sapinst

    Hi all,
    We are in process updating Bw 3.5 to BI 7.0 we hace sucessfully completed the Upgrade but while installing Bi java thru Sapinst in third step like java instance installtion  i was stck with the below error.
               We have downloaded the Cryptographic file and placed in jdk folder still the same problem is  coming.
    Please suggest...
    Thanks,
    Subhash.G
    Starting deployment prerequisites:
    Oct 13, 2007 2:42:18 AM  Error: Creation of DataSource for database "BWQ" failed.
    Original error message is:
    com.sap.sql.log.OpenSQLException: Error while accessing secure store: Encryption or decryption is not possible because the full version of the SAP Java Crypto Toolkit was not found (iaik_jce.jar is required, iaik_jce_export.jar is not sufficient) or the JCE Jurisdiction Policy Files don't allow the use of the "PbeWithSHAAnd3_KeyTripleDES_CBC" algorithm..
    Stack trace of original Exception or Error is:
    com.sap.sql.log.OpenSQLException: Error while accessing secure store: Encryption or decryption is not possible because the full version of the SAP Java Crypto Toolkit was not found (iaik_jce.jar is required, iaik_jce_export.jar is not sufficient) or the JCE Jurisdiction Policy Files don't allow the use of the "PbeWithSHAAnd3_KeyTripleDES_CBC" algorithm..

    Problem solved  followed the notes 1063396.

  • If Statement in java.awt paint

    import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of Bmi classI have written the above code to calculate someones BMI (Body Mass Index). Basically as you can see it recieves a weight and height from the user and calculates the rest. But whilst that good I would like to know how I can make it tell the user something to the effect of "Your overweight" or "Your underweight". The if statement runs like this:
    if (wt > max)This forum doesn't quite handle <> properly. The greater and less than symbols. So above you will see > this is the html character code for a greater than symbol so please read it as such.
    And then if wt is greater than max then it will say "Your overweight".
    But I can't figure out how to include it in the above program. Becuase it won't run in paint, atleast it won't the way I have done it previously. So can you think of any other ways?
    Help much appreciated,
    Simon

    Thanks very much that works well.
    Simon
    My code now looks like this: import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void you(Graphics g)
      String statement;
      if(wt > max) statement="You are very fat";
      else if(wt < min) statement="You are very thin";
      else statement="You are in the recommended weight range for your height";
      g.drawString(statement, 20,210);
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        you(g);
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of BmiThanks again,
    Simon

  • SSO java sample application problem

    Hi all,
    I am trying to run the SSO java sample application, but am experiencing a problem:
    When I request the papp.jsp page I end up in an infinte loop, caught between papp.jsp and ssosignon.jsp.
    An earlier thread in this forum discussed the same problem, guessing that the cookie handling was the problem. This thread recommended a particlar servlet , ShowCookie, for inspecting the cookies for the current session.
    I have installed this cookie on the server, but don't see anything but one cookie, JSESSIONID.
    At present I am running the jsp sample app on a Tomcat server, while Oracle 9iAS with sso and portal is running on another machine on the LAN.
    The configuration of the SSO sample application is as follows:
    Cut from SSOEnablerJspBean.java:
    // Listener token for this partner application name
    private static String m_listenerToken = "wmli007251:8080";
    // Partner application session cookie name
    private static String m_cookieName = "SSO_PAPP_JSP_ID";
    // Partner application session domain
    private static String m_cookieDomain = "wmli007251:8080/";
    // Partner application session path scope
    private static String m_cookiePath = "/";
    // Host name of the database
    private static String m_dbHostName = "wmsi001370";
    // Port for database
    private static String m_dbPort = "1521";
    // Sehema name
    private static String m_dbSchemaName = "testpartnerapp";
    // Schema password
    private static String m_dbSchemaPasswd = "testpartnerapp";
    // Database SID name
    private static String m_dbSID = "IASDB.WMDATA.DK";
    // Requested URL (User requested page)
    private static String m_requestUrl = "http://wmli007251:8080/testsso/papp.jsp";
    // Cancel URL(Home page for this application which don't require authentication)
    private static String m_cancelUrl = "http://wmli007251:8080/testsso/fejl.html";
    Values specified in the Oracle Portal partner app administration page:
         ID: 1326
         Token: O87JOE971326
         Encryption key: 67854625C8B9BE96
         Logon-URL: http://wmsi001370:7777/pls/orasso/orasso.wwsso_app_admin.ls_login
         single signoff-URL: http://wmsi001370:7777/pls/orasso/orasso.wwsso_app_admin.ls_logout
         Name: testsso
         Start-URL: http://wmli007251:8080/testsso/
         Succes-URL: http://wmli007251:8080/testsso/ssosignon.jsp
         Log off-URL: http://wmli007251:8080/testsso/papplogoff.jsp
    Finally I have specified the cookie version to be v1.0 when running the regapp.sql script. Other parameters for this script are copied from the values specified above.
    Unfortunately the discussion in the earlier thread did not go any further but to recognize the cookieproblem, so I am now looking for help to move further on from here.
    Any ideas will be greatly appreciated!
    /Mads

    Pierre - When you work on the sample application, you should test the pages in a separate browser instance. Don't use the Run Page links from the Builder. The sample app has a different authentication scheme from that used in the development environment so it'll work better for you to use a separate development browser from the application testing browser. In the testing browser, to request the page you just modified, login to the application, then change the page ID in the URL. Then put some navigation controls into the application so you can run your page more easily by clicking links from other pages.
    Scott

  • SSO between a Java EE application (Running on CE) and r/3 backend

    Hi All,
    Over the past few days I have been trying to implement a SSO mechanism between NW CE Java Apps and R/3 backend without any success. I have been trying to use SAP logon tickets for implementing SSO.
    Below is what I need:
    I have a Java EE application which draws data from R/3 backend and does some processing before showing data to the users. As of now the only way the Java App on CE authenticates to r/3 backend is by passing the userid and pwds explicitly. See sample authentication code below:
    BindingProvider bp = (BindingProvider) myService;
    Map<String,Object> context = bp.getRequestContext();
    context.put(BindingProvider.USERNAME_PROPERTY, userID);
    context.put(BindingProvider.PASSWORD_PROPERTY, userPwd);
    Now this is not the way we want to implement it. What we need is when the user authenticates to CE ( using CE's UME) CE issues a SAP logon ticket to the user. This ticket should be used to subsequently login to other system without having to pass the credentials. We have configured the CE and Backend to use SAP logon tickets as per SAP help.
    What I am not able to figure out is: How to authenticate to SAP r/3 service from the java APP using SAP logon tickets. I couldnt find any sample Java  code on SAP help to do this. (For example the above sample code authenticates the user by explicitly passing userid and pwd, I need something similar to pass a token to the backend)
    Any help/pointers on this would be great.
    Thanks,
    Dhananjay

    Hi,
    Have you imported the java certificate into R/3 backend system ? if so.
    Then just go to backend system and check on sm50 for each applicaion instance of any error eg.
    SM50-> Display files (ICON) as DB symbol with spect.(cntrlshiftF8)
    You will get logon ticket details.
    with thanks,
        Rajat

Maybe you are looking for