/////////////// Purpose. C++ application that uses Java GUI \\\\\\\\\\\\\\\\ #include #include #include #include "GridGameAdapter.cpp" class GridGameClass { private: int x; int y; GridGameAdapter board; public: GridGameClass( int size ) : board(size) { time_t t; srand((unsigned) time(&t)); x = rand() % size; y = rand() % size; } void guess( int a, int b ) { int xx = a - x; if (xx < 0) xx *= -1; int yy = b - y; if (yy < 0) yy *= -1; board.update( a, b, xx+yy ); } }; void main( void ) { int x, y; cout << "Enter size: "; cin >> x; GridGameClass gg( x ); while (1) { cout << "Enter x y: "; cin >> x >> y; gg.guess( x, y ); } } //////// Purpose. C++ adapter between C++ application and Java GUI \\\\\\\\\ #include class GridGameAdapter { private: JavaVM* jvm; JNIEnv* env; jobject obj; jmethodID upda; public: GridGameAdapter( int size ) { JavaVMOption options[2]; options[0].optionString = "-Djava.compiler=NONE"; options[1].optionString = "-Djava.class.path=c:\\msdev\\projects\\cpp"; // options[2].optionString = "-verbose:jni"; JavaVMInitArgs vm_args; vm_args.version = JNI_VERSION_1_2; vm_args.options = options; vm_args.nOptions = 2; vm_args.ignoreUnrecognized = true; int res = JNI_CreateJavaVM( &jvm, (void**)&env, &vm_args ); if (res < 0) cout << "create failed" << endl; jclass clas = env->FindClass( "GridGameJavaGUI" ); jmethodID ctor = env->GetMethodID( clas, "", "(I)V" ); obj = env->NewObject( clas, ctor, size ); upda = env->GetMethodID( clas, "update", "(III)V" ); } void update( int x, int y, int sc ) { env->CallVoidMethod( obj, upda, x, y, sc ); } ~GridGameAdapter() { jvm->DestroyJavaVM(); } }; ///////// Purpose. Java GUI component for C++ GridGame application \\\\\\\\\ import java.awt.*; import java.awt.event.*; public class GridGameJavaGUI { private Label[][] labels; private Font font; public GridGameJavaGUI( int size ) { labels = new Label[size][size]; Frame frame = new Frame( "GridGameBoard" ); frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); frame.setLayout( new GridLayout(size,size) ); for (int i=0; i < size; i++) for (int j=0; j < size; j++) { labels[i][j] = new Label(Integer.toString(i) +" " +j, Label.CENTER); frame.add( labels[i][j] ); } font = new Font( "Helvetica", Font.BOLD, 16 ); frame.pack(); frame.setVisible( true ); } public void update( int x, int y, int score ) { labels[x][y].setBackground( Color.yellow ); labels[x][y].setForeground( Color.red ); labels[x][y].setFont( font ); labels[x][y].setText( Integer.toString( score ) ); } }