2008년 11월 25일 화요일
CardLayout 간단 예제
ioctl() 함수
유닉스
유닉스의 ioctl 콜은 다음과 같은 매개 변수를 취한다.
Win32
Win32 DeviceIoContrl은 다음과 같은 매개 변수를 취한다.
- 열려 있는 객체 관리 (파일 서술자와 동등)
- 요청 코드 번호 (제어 코드)
- 입력 매개 변수를 위한 버퍼
- 출력 결과를 위한 버퍼
- OVERLAPPED 구조 (오버랩 입출력이 쓰이는 경우)
이름
ioctl - 장치를 제어한다.사용법
#include <sys/ioctl.h>int ioctl(int d, int request, ...)
[세번째 인자는 전통적으로 char *argp 이며, 설명를 위해 그렇게 언급하겠다.]
설명
ioctl 함수는 특수 파일의 장치 인자를 조절한다. 특히, 문자 특수 파일(예로 터미널)의 많은 특징적인 동작은 ioctl의 요구에 의해 제어된다. d 인자는 반드시 열린 파일 기술자이어야 한다.ioctl request는 인자가 입력되는 인자인지 출력되는 인자인지와 argp 인자의 바이트 단위의 크기를 나타낸다. ioctl request를 나타내기 사용되는 매크로와 상수는 <sys/ioctl.h>파일에 정의되어 있다.
반환값
성공시, 0이 리턴된다. 에러시, -1이 리턴되며, errno는 적당한 값으로 설정된다.[Opencv] Facedetect 소스
more..
#include "cv.h"
#include "highgui.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "assert.h"
#include "math.h"
#include "float.h"
#include "limits.h"
#include "time.h"
#include "ctype.h"
#ifdef _EiC
#define WIN32
#endif
/*There are three parts in which first of all the program is divided ..
In the first part the program checks whether the Camera is connected and is it able to return frames to the program
If yes it detects the face from the camera/video file (or it also loads from a video file if you have specified) ...
If no
Then it checks for Lena.jpg if found it detects the face in the same....
If no
It checks for a file a text file where it can find the file names of each and every picture in which
The faces are to be detected..The text file should have the names of the pictures along with the extensions */
/*about CvMemStorage==>
typedef struct CvMemStorage
{
struct CvMemBlock* bottom;/* first allocated block */
/* struct CvMemBlock* top; /* the current memory block - top of the stack */
/* struct CvMemStorage* parent; /* borrows new blocks from */
/*int block_size; /* block size */
/*int free_space; /* free space in the top block (in bytes) */
/*} CvMemStorage;*/
/*CvMemStorage is a dynamic data structure used to store dynamically growing
data structures such as sequences contours Graphs..*/
static CvMemStorage* storage = 0;
static CvHaarClassifierCascade* cascade = 0;
/*This is the function which is going detect and draw the circle round the face..
For the Moment lets forget about the function*/
void detect_and_draw( IplImage* image );
/*WE assign the .xml file name which is the main basic thing which allows us to detect objects
and depending upon this file the object is realized..As I Said lets speak about xml file in some other post*/
const char* cascade_name =
"haarcascade_frontalface_alt.xml";
/* "haarcascade_profileface.xml";*/
/*This .xml file is available by default in the \root..\openCV\data folder and you may verify the same..*/
int main( int argc, char** argv )
{
CvCapture* capture = 0;
IplImage *frame, *frame_copy = 0;/*Another frame for Operations..frame_copy*/
int optlen = strlen("--cascade=");/*You will understamd this line afterwards*/
const char* input_name;
/*If you want to understand the below line then you have to first study about
the arguments the main function has..*/
/*Explanation of strncmp
int strncmp ( const char * str1, const char * str2, size_t num );
str1
C string to be compared.
str2
C string to be compared.
num
Maximim number of characters to compare.
See this link for more information
http://www.cplusplus.com/reference/clibrary/cstring/strncmp.html*/
if( argc > 1 && strncmp( argv[1], "--cascade=", optlen ) == 0 )
/*This line means that we compare the argument we got from the command line to that of the "--cascade"*/
/*We are comparing argc until the lenght optlen*/
{
/*If cascade name given in the command line then use it else go to the default..you can give the path to
the cascade to cascade name as given in the above line...*/
cascade_name = argv[1] + optlen;
input_name = argc > 2 ? argv[2] : 0;
/*If you know about arguments the main has and how they work then you should
be able to get this line by now..*/
}
else
{/*If you are running the program elsewhere other than the folder in which the program facedetect.c is
present by default then put the full path to the .xml file in the inverted commmas"
and replace "forward slash by a backslash" in the below line*/
/* try to comment this below line and then please use the command line for this program because the program does not
terminate after the execution and follow the same trick for many things*/
cascade_name = "C:/Program Files/OpenCV/data/haarcascades/haarcascade_frontalface_alt2.xml";
input_name = argc > 1 ? argv[1] : 0;/*Use of this line comes down..
If input name not given in the command line then load Zero
Ponder about this above line for sometime
Give some time to this program,..Once again if you have read about arguments the main function has then
you should be able to get this line*/
}
/*Here the use of cascade_name comes in..The previous lines involving the cascade_name were just
to ensure that a valid cascade name is passed to the function..other wise the program will give bad results*/
cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );/*Type conversion*/
/*Please see Cvload in documentation there is no space for text in this blog*/
/*If unable to load cascade then print the errors and quit */
if( !cascade )/*This loop is easy*/
{
fprintf( stderr, "ERROR: Could not load classifier cascade\n" );
fprintf( stderr,
"Usage: facedetect --cascade=\"\" [filename|camera_index]\n" );
return -1;
}
/*Else proceed here*/
storage = cvCreateMemStorage(0);
if( !input_name || (isdigit(input_name[0]) && input_name[1] == '\0') )
/*If input name is zero then capture from cam else it must be a
video file and load it with the help of capture from cam*/
capture = cvCaptureFromCAM( !input_name ? 0 : input_name[0] - '0' );
else
capture = cvCaptureFromAVI( input_name );
cvNamedWindow( "result", 1 );
/*The part where the capture from the camera starts */
if( capture )
{
for(;;)/*Infinite loop until we hit the escape buttom*/
{
if( !cvGrabFrame( capture ))/*If no frame break off just from this loop*/
break;
frame = cvRetrieveFrame( capture );/*If no frame break off just from this loop*/
if( !frame )
break;
if( !frame_copy )/*here frame copy =0 ==> !0=1 and hence it enters the loop*/
frame_copy = cvCreateImage( cvSize(frame->width,frame->height),
IPL_DEPTH_8U, frame->nChannels );
/*Copy the frame*/
if( frame->origin == IPL_ORIGIN_TL )/*if the origin is top left then procees else
flip the frame and then copy by using cvFlip*/
cvCopy( frame, frame_copy, 0 );
else
cvFlip( frame, frame_copy, 0 );
detect_and_draw( frame_copy );/*Send this frame to the function which wil detect
and dram the circle*/
if( cvWaitKey( 10 ) >= 0 )/*If you hit the escape key you will exit*/
break;
}
cvReleaseImage( &frame_copy );
cvReleaseCapture( &capture );
}
/*This part loads the image from the command line if image not found in the command line it loads the lena.jpg ..*/
else
{
const char* filename = input_name ? input_name : (char*)"lena.jpg";
IplImage* image = cvLoadImage( filename, 1 );
if( image )/*If image =0 then does not enter else enters and gives the frames for processing*/
{
detect_and_draw( image );
cvWaitKey(0);
cvReleaseImage( &image );
}
else
{
/* assume it is a text file containing the
list of the image filenames to be processed - one per line */
/* You may commment this part of the code as it is not always required
right from the opening brace of else to its closing brace*/
FILE* f = fopen( filename, "rt" );
if( f )/*i f!=0 enters the loop*/
{
char buf[1000+1];/*This part is really easy try to figure it out */
while( fgets( buf, 1000, f ))
{
/*This part consists of loading of the images by just loading the filename from the
textfile and one name per line
It requires the knowledge of C++ rather than OpenCV*/
int len = (int)strlen(buf);
while( len > 0 && isspace(buf[len-1]) )
len--;
buf[len] = '\0';
image = cvLoadImage( buf, 1 );/*Loads the image sends it as the argument */
if( image )
{
detect_and_draw( image );
cvWaitKey(0);
cvReleaseImage( &image );
}
}
fclose(f);/*Closing the file pointer*/
}
}
}
cvDestroyWindow("result");
return 0;
}
void detect_and_draw( IplImage* img )
{
static CvScalar colors[] =
{/*For the moment forget about this array*/
{{0,0,255}},
{{0,128,255}},
{{0,255,255}},
{{0,255,0}},
{{255,128,0}},
{{255,255,0}},
{{255,0,0}},
{{255,0,255}}
};
double scale = 0.6;/*Change this value and you can chang the color of the circle which detects the face*/
IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );/*Gray is the same as the image
(Actually pointer to the image) which is sent from program main whenever this funciton is called.*/
IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),
cvRound (img->height/scale)),
8, 1 );
/* here cvRound is just rounding off the double to an integer so that we have a perfect integer values
with good accuracy*/
int i;
cvCvtColor( img, gray, CV_BGR2GRAY );
/*The image is converted to GRAY because Haar training works only on grayscale or binary images*/
cvResize( gray, small_img, CV_INTER_LINEAR );
cvEqualizeHist( small_img, small_img );/*I feel we equlize because we want to get good results*/
cvClearMemStorage( storage );
if( cascade )
{
/*here lets leave about cvgetickcount and some other arithmetic calculations invoving time*/
double t = (double)cvGetTickCount();
CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,
1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,
cvSize(30, 30) );/*CV_HAAR_DO_CANNY_PRUNING is the only
method supported right now*/
/*This one line detects objects*/
t = (double)cvGetTickCount() - t;/*Let us just leave about detection time for the moment*/
/*Lets concentrate on detection first.*/
printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );
for( i = 0; i < (faces ? faces->total : 0); i++ )/*This condition in the condition field of the for loop is
once again for safety
/* If faces=0 then zero is assigned and if not the "total "is assigned to compare with 'i' .See the
cvseqstructure in the documentation for more details..*/
/*total is a member of cvseq- ITs the total number of elements"*/
{
CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
CvPoint center;
/*CvPoint is a structure which has just two members they store x coordinate and the y coordinate*/
int radius;
center.x = cvRound((r->x + r->width*0.5)*scale);/*CvRound explained above.
This line has more of Arithmetic and the following lines...
You can also try and change the numerical values to see the change*/
center.y = cvRound((r->y + r->height*0.5)*scale);
radius = cvRound((r->width + r->height)*0.25*scale);
cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );
/*Think over the 'colors[i%8]' remember % means Remainder*/
/*Explanation of cvCircle
void cvCircle( CvArr* img, CvPoint center, int radius, CvScalar color,
int thickness=1, int line_type=8, int shift=0 );
*/
}
}
cvShowImage( "result", img );
cvReleaseImage( &gray );
cvReleaseImage( &small_img );
}
//End
http://myopencv.blogspot.com/2008/05/facedetectc.html
2008년 11월 23일 일요일
[Linux] Thread Server 포트 2개 열기
more..
/*
** selectserver.c -- a cheezy multiperson chat server
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT1 9034 // port1 we're listening on
#define PORT2 9035 // port2 we're listening on
void *do_serv(void *argv)
{
int port_no = (int)argv;
fd_set master; // master file descriptor list
fd_set read_fds; // temp file descriptor list for select()
struct sockaddr_in myaddr; // server address
struct sockaddr_in remoteaddr; // client address
int fdmax; // maximum file descriptor number
int listener; // listening socket descriptor
int newfd; // newly accept()ed socket descriptor
char buf[256]; // buffer for client data
int nbytes;
int yes=1; // for setsockopt() SO_REUSEADDR, below
socklen_t addrlen;
int i, j;
FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);
// get the listener
if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
// lose the pesky "address already in use" error message
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
// bind
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY;
myaddr.sin_port = htons(port_no);
memset(myaddr.sin_zero, '\0', sizeof myaddr.sin_zero);
if (bind(listener, (struct sockaddr *)&myaddr, sizeof myaddr) == -1) {
perror("bind");
exit(1);
}
// listen
if (listen(listener, 10) == -1) {
perror("listen");
exit(1);
}
// add the listener to the master set
FD_SET(listener, &master);
// keep track of the biggest file descriptor
fdmax = listener; // so far, it's this one
// main loop
for(;;) {
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
perror("select");
exit(1);
}
// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!
if (i == listener) {
// handle new connections
addrlen = sizeof remoteaddr;
if ((newfd = accept(listener, (struct sockaddr *)&remoteaddr,
&addrlen)) == -1) {
perror("accept");
} else {
FD_SET(newfd, &master); // add to master set
if (newfd > fdmax) { // keep track of the maximum
fdmax = newfd;
}
printf("selectserver: new connection from %s on "
"socket %d\n", inet_ntoa(remoteaddr.sin_addr), newfd);
}
} else {
// handle data from a client
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
printf("selectserver: socket %d hung up\n", i);
} else {
perror("recv");
}
close(i); // bye!
FD_CLR(i, &master); // remove from master set
} else {
// we got some data from a client
for(j = 0; j <= fdmax; j++) {
// send to everyone!
if (FD_ISSET(j, &master)) {
// except the listener and ourselves
if (j != listener && j != i) {
if (send(j, buf, nbytes, 0) == -1) {
perror("send");
}
}
}
}
}
} // it's SO UGLY!
}
}
}
pthread_exit(NULL);
}
int main(void) {
pthread_t threads[2];
int rc;
rc = pthread_create(&threads[0], NULL, do_serv, (void *)PORT1);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
rc = pthread_create(&threads[1], NULL, do_serv, (void *)PORT2);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
pthread_exit(NULL);
};
출처 : http://kldp.org/node/94310
TCP Server [Thread]
more..
// by Softcream.kr/tc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <pthread.h>
#define MAXLINE 511
#define MAX_SOCK 1024 // 솔라리스의 경우 64
char *EXIT_STRING = "exit"; // 클라이언트의 종료요청 문자열
char *START_STRING = "Connected to chat_server \n";
// 클라이언트 환영 메시지
int maxfdp1, nbyte; // 최대 소켓번호 +1
int num_chat = 0; // 채팅 참가자 수
int clisock_list[MAX_SOCK]; // 채팅에 참가자 소켓번호 목록
int listen_sock; // 서버의 리슨 소켓
int clinum = 0, num = 0;
fd_set read_fds; // 읽기를 감지할 fd_set 구조체
pthread_t tid[MAX_SOCK]; // 각 클라이언트와 상대할 스레드 변수
pthread_mutex_t num_lock; // 뮤텍스 초기화
pthread_mutexattr_t mutex_attr; // 뮤텍스 속성 초기화
// 새로운 채팅 참가자 처리
void addClient(int s, struct sockaddr_in *newcliaddr);
int getmax(); // 최대 소켓 번호 찾기
void removeClient(int s, int t_tid); // 채팅 탈퇴 처리 함수
int tcp_listen(int host, int port, int backlog); // 소켓 생성 및 listen
void errquit(char *mesg) { perror(mesg); exit(1); }
void *thrfunc(void *arg);
int main(int argc, char *argv[]) {
struct sockaddr_in cliaddr;
int accp_sock, addrlen = sizeof(struct sockaddr_in);
int i, status;
pthread_mutexattr_init(&mutex_attr); // 뮤텍스
pthread_mutex_init(&num_lock, &mutex_attr); // 뮤텍스 속성 변수
if(argc != 2) {
printf("사용법 :%s port\n", argv[0]);
exit(0);
}
// tcp_listen(host, port, backlog) 함수 호출
listen_sock = tcp_listen(INADDR_ANY, atoi(argv[1]), 5);
while(1) {
FD_ZERO(&read_fds);
FD_SET(listen_sock, &read_fds);
for(i=0; i< num_chat; i++)
FD_SET(clisock_list[i], &read_fds);
maxfdp1 = getmax() + 1; // maxfdp1 재 계산
puts("wait for client");
if(FD_ISSET(listen_sock, &read_fds)) {
accp_sock=accept(listen_sock, (struct sockaddr
*)&cliaddr, &addrlen);
if(accp_sock == -1)
errquit("accept fail");
pthread_mutex_lock(&num_lock); // 뮤텍스 잠금
addClient(accp_sock,&cliaddr);
pthread_mutex_unlock(&num_lock); //뮤텍스 해제
send(accp_sock, START_STRING, strlen(START_STRING), 0);
printf("%d번째 사용자 추가.\n", num_chat);
// 각 클라이언트를 담당할 스레드 생성
if((status=pthread_create(&tid[num], NULL, &thrfunc, NULL))!=0)
errquit("pthread error");
num++;
continue;
}
} // end of while
return 0;
}
// 새로운 채팅 참가자 처리
void addClient(int s, struct sockaddr_in *newcliaddr) {
char buf[20];
inet_ntop(AF_INET,&newcliaddr->sin_addr,buf,sizeof(buf));
printf("new client: %s\n",buf);
// 채팅 클라이언트 목록에 추가
clisock_list[num_chat] = s;
num_chat++;
}
// 채팅 탈퇴 처리
void removeClient(int s, int ptid) {
close(clisock_list[s]);
if(s != num_chat-1)
clisock_list[s] = clisock_list[num_chat-1];
num_chat--;
printf("채팅 참가자 1명 탈퇴. 현재 참가자 수 = %d\n", num_chat);
pthread_cancel(ptid); // 해당 스레드 삭제
}
// 최대 소켓번호 찾기
int getmax() {
// Minimum 소켓번호는 가정 먼저 생성된 listen_sock
int max = listen_sock;
int i;
for (i=0; i < num_chat; i++)
if (clisock_list[i] > max )
max = clisock_list[i];
return max;
}
// listen 소켓 생성 및 listen
// listen 소켓 생성 및 listen
int tcp_listen(int host, int port, int backlog) {
int sd;
struct sockaddr_in servaddr;
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd == -1) {
perror("socket fail");
exit(1);
}
// servaddr 구조체의 내용 세팅
bzero((char *)&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(host);
servaddr.sin_port = htons(port);
if (bind(sd , (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind fail"); exit(1);
}
// 클라이언트로부터 연결요청을 기다림
listen(sd, backlog);
return sd;
}
void *thrfunc(void *arg) // 스레드 함수 부분. 스레드 하나가 하나의 클라이언트를 담당
{
int i, j, cnt, status;
pthread_t ptid;
char buf[MAXLINE+1];
ptid = (pthread_t*) &tid[num]; // 스레드의 tid
if( (status=pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL))!=0) {
printf("pthread_setcancelstate fail: %s\n",strerror(status));
exit(0); // 취소 요청 허용
}
if( (status=pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL))!=0) {
printf("pthread_setcanceltype fail: %s\n",strerror(status));
exit(0); // 취소 요청시 즉시 종료
}
cnt = clinum;
clinum++;
while(1){
FD_ZERO(&read_fds);
FD_SET(listen_sock, &read_fds);
for(i=0; i < num_chat; i++)
FD_SET(clisock_list[i], &read_fds);
if(FD_ISSET(clisock_list[cnt], &read_fds)) {
nbyte = recv(clisock_list[cnt], buf, MAXLINE, 0);
if(nbyte<=0) {
pthread_mutex_lock(&num_lock); // 뮤텍스 잠금
removeClient(i,ptid); // 클라이언트의 종료
pthread_mutex_unlock(&num_lock); // 뮤텍스 해제
continue;
}
buf[nbyte] = 0;
// 종료문자 처리
if(strstr(buf, EXIT_STRING) != NULL) {
pthread_mutex_lock(&num_lock); // 뮤텍스 잠금
removeClient(i,ptid); // 클라이언트의 종료
pthread_mutex_unlock(&num_lock); // 뮤텍스 해제
continue;
}
// 모든 채팅 참가자에게 메시지 방송
for (j = 0; j < num_chat; j++)
send(clisock_list[j], buf, nbyte, 0);
printf("%s\n", buf);
}
}
}
JScrollPane Scrollbar 맨 아래로 위치하기
2008년 11월 21일 금요일
Frame 중앙 정렬
2008년 11월 19일 수요일
JMenu 예제
more..
import java.awt.event.*;
import javax.swing.*;
String[ ] editItems = new String[ ] { "Undo", "Cut", "Copy", "Paste" };
char[ ] fileShortcuts = { 'N','O','S','X' };
char[ ] editShortcuts = { 'Z','X','C','V' };
JMenu editMenu = new JMenu("Edit");
JMenu otherMenu = new JMenu("Other");
JMenu subMenu = new JMenu("SubMenu");
JMenu subMenu2 = new JMenu("SubMenu2");
ActionListener printListener = new ActionListener( ) {
public void actionPerformed(ActionEvent event) {
System.out.println("Menu item [" + event.getActionCommand( ) +
"] was pressed.");
}
};
for (int i=0; i < fileItems.length; i++) {
JMenuItem item = new JMenuItem(fileItems[i], fileShortcuts[i]);
item.addActionListener(printListener);
fileMenu.add(item);
}
for (int i=0; i < editItems.length; i++) {
JMenuItem item = new JMenuItem(editItems[i]);
item.setAccelerator(KeyStroke.getKeyStroke(editShortcuts[i],
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
item.addActionListener(printListener);
editMenu.add(item);
}
editMenu.insertSeparator(1);
JMenuItem item;
subMenu2.add(item = new JMenuItem("Extra 2"));
item.addActionListener(printListener);
subMenu.add(item = new JMenuItem("Extra 1"));
item.addActionListener(printListener);
subMenu.add(subMenu2);
otherMenu.add(subMenu);
otherMenu.add(item = new JCheckBoxMenuItem("Check Me"));
item.addActionListener(printListener);
otherMenu.addSeparator( );
ButtonGroup buttonGroup = new ButtonGroup( );
otherMenu.add(item = new JRadioButtonMenuItem("Radio 1"));
item.addActionListener(printListener);
buttonGroup.add(item);
otherMenu.add(item = new JRadioButtonMenuItem("Radio 2"));
item.addActionListener(printListener);
buttonGroup.add(item);
otherMenu.addSeparator( );
otherMenu.add(item = new JMenuItem("Potted Plant",
new ImageIcon("image.gif")));
item.addActionListener(printListener);
add(fileMenu);
add(editMenu);
add(otherMenu);
}
JFrame frame = new JFrame("Simple Menu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(new IntroExample( ));
frame.pack( );
frame.setVisible(true);
}
}
출처: http://cafe.naver.com/javalove.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=83 자바사랑
JLabel 색상변경 / JFrame exit
label.setOpaque(true);위의 코드를 추가해주면 원하는 색상을 볼수가 있다.. (JBuilder 에서는 못잡아준다 ..ㅡㅡ;)
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);