Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JFrames

 
Kenneth Kim
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm working on an exercise, and I need a few pointers. Basically, I want to create a program that will create a frame using the JFrame class. Simple enough. However, I want to add a button so that if the user clicks "OK", the frame will relocate itself. I've looked hard at the API and I still haven't been able to find what I needed. My question is:

a) How do I create an OK button for my frame?

Here's the code I have now:

import javax.swing.*;

class JumpyWindow {

public static void main(String[] args) {
JFrame jumpywindow;
jumpywindow = new JFrame();
jumpywindow.setTitle("Jumpy Window");
jumpywindow.setSize(200, 100);
jumpywindow.setVisible(true);
jumpywindow.setLocation(412,334);
}

}

By the way, do I need to "cut and paste" that chunk of code setting the attributes of the JFrame jumpywindow five times if I want to relocate it five times? Thanks.
[ September 11, 2005: Message edited by: Kenneth Kim ]
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

a) How do I create an OK button for my frame?


You need to use the JButton class. First, you create a new JButton with some code like this:



Then you add the button to your frame's content pane:



This will use the content pane's default LayoutManager. If you want better control over where the button is placed in the window and how it changes if the user resizes the window, you need to learn more about layout managers.

You will also need to create an ActionListener so that the program responds when the user clicks the button. If you are unfamiliar with creating your own listeners for event handling, I suggest you read your text book or google for something like "java event handling" to get more information.

By the way, do I need to "cut and paste" that chunk of code setting the attributes of the JFrame jumpywindow five times if I want to relocate it five times?

If you find yourself copy-and-pasting code, you should usually back up and figure out a way to make a method out of it that you can just call each time you need it. So, no, you shouldn't copy and paste the code five times.

I hope this helps.

Layne

p.s. For further questions, you should mosey on over to our GUI forum where our experts on this topic hang out.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might also find this tutorial helpful...

http://java.sun.com/docs/books/tutorial/uiswing/index.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic