Computer Science

Hobart College


JFrame in Java

My topic of choice to learn more about was the JFrame in java.

The JFrame is basically a more efficient way of creating the windows used to show our applets, games or whatever you’ve made to run in a window from Java.

Rather than just using setSize(x, y) the JFrame gives you a lot more options in terms of how the window is displayed.

For example the line…
frame.setUndecorated( false );
Will toggle the title bar on and off.



You can also do things like disallow the window to be resized or vice versa.
frame.setResizable( false );

The JFrame must be imported by the line import javax.swing.JFrame;

other elements to be used along with the JFrame method exist in the javax.swing package although some imports from the java.awt package are also useful.
You can also do things like make the window fullscreen, use buffers in the JFrame which is useful for setting up games in Java etc.
Below is an example of some code I used in eclipse to create a very basic window using the JFrame, using the parameters shown above.

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.JFrame;
  4. import javax.swing.JLabel;
  5. import java.awt.FlowLayout;
  6. public class Main extends JFrame {
  7. public static void main(String args[]) {
  8. JFrame frame = new JFrame("Testing the JFrame");
  9. //turns title bar on an off (including buttons)
  10. frame.setUndecorated( false );
  11. //Enables/Disables resizing of the window
  12. frame.setResizable( false );
  13. // Add a window listener for close button
  14. frame.addWindowListener(new WindowAdapter() {
  15. public void windowClosing(WindowEvent e) {
  16. System.exit(0);
  17. }
  18. });
  19. // This is an empty content area in the frame
  20. JLabel jlbempty = new JLabel("JText test");
  21. JLabel label = new JLabel("Text-Only Label");
  22. jlbempty.setPreferredSize(new Dimension(1280, 720));
  23. frame.getContentPane().add(jlbempty, BorderLayout.CENTER);
  24. frame.pack();
  25. frame.setVisible(true);
  26. }
  27. }

One Response to JFrame in Java

  1. Josh Stevenson says:

    You have to click on the images to enlarge them, in order to see the real beauty of this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar