Jump to content
  • Advertisement
Sign in to follow this  
  • entries
  • comments
  • views

Simplified Example Of How To Use JPanel & JFrame With Lots Of Different Stuff

Sign in to follow this  


Below you will find a fully functional code example that shows how to do many common tasks with JPanel & JFrame. I stripped out as much useless "fluff" as I could, leaving the code as bare as possible( all code is in a single class ) .
If you have a question on a specific area please refer to a Google search before asking here.

Things this code demonstrates:
Buttons, and how to identify which one was clicked
Action listeners
Mouse listeners, and how to get exact click coordinates
Key listener
Focuses listener, and how to fix a common issue when using several listeners at one time
Drawing text and Unicode
Fonts, text size ,text styles, text colors
Popup windows
How to get anti-aliasing to actually work
Loading images from files and URLs
Resizing images
Drawing images

Please note: this code is not optimized - but it is a single class and fully functional !!!import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Image;import java.awt.RenderingHints;import java.awt.event.*;import java.net.URL;import javax.imageio.ImageIO;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;public class Main extends JPanel implements KeyListener,ActionListener,MouseListener,FocusListener { public static void main(String args[]) { Main m = new Main(); // building object container - using " 'this' " will not work JFrame frame = new JFrame("Title Here"); // set title frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set behavior when closed frame.addKeyListener(m); // add keylistener frame.addFocusListener(m); // add focuse listener frame.addMouseListener(m); // add mouse listener JButton button = new JButton("Click"); // build a button button.setBounds(1, 200, 80, 30); // location and size of button frame.add(button); // add a button button.addActionListener(m); // something happens when button is clicked frame.add(m); // package and create the Jframe frame.setSize(new Dimension(300,300 )); // set window size frame.setFocusable(true); // add focuse button.setFocusable(true); // add focuse frame.setVisible(true); // make the window } // This method is automatically called \\ public void paintComponent(Graphics g) { Graphics2D g1 = (Graphics2D) g; // this is for antialiasing RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// this is for antialiasing g1.setRenderingHints(rh);// this is for antialiasing g.setFont(new Font("Times New Roman",Font.BOLD,40)); // set font try { // add an image ( replace "URL" with "File" if loading from local hard drive Image img = ImageIO.read( new URL("http://img.brothersoft.com/icon/softimage/s/smileysidebar-387849-1280302029.jpeg") ); // get image from internet g.drawImage(img, 1, 100, null); // draw normal image g.drawImage(img.getScaledInstance(15, 15, Image.SCALE_DEFAULT), 1, 130, null); // draw resized image } catch (Exception e) {} // I'm too lazy to handle this error g.setColor(Color.black); // set text color g.drawString("Hello World ! ", 1, 30); // draw some words g.drawString("\u263A", 1, 100); // draw some unicode } public void keyReleased(KeyEvent kr) { // do something when a key is released jo("You pushed a key ! \n Key Name: " + kr.getKeyChar() ); // create popup window when a key is pressed }public void actionPerformed(ActionEvent bp) { // when a button is pressed, do something jo("You pushed the button ! \n Button Name: " + bp.getActionCommand() ); // create popup window when button is pressed} // "getActionCommand()" is the name of buttonpublic void mouseReleased(MouseEvent me) { // when a mouse button is clicked jo("Mouse clicked !\n Mouse Button: " + me.getButton() + "\nLocation Of Click: X-" + me.getX() + " Y-" + me.getY() ); // were did you click ? }public void focusLost(FocusEvent fl) { fl.getComponent().requestFocusInWindow(); // this keeps the window focused}public void jo (String s){ // added this to save space else were JOptionPane.showMessageDialog( new JFrame(""), s); // popup wondow}// These methods have to be declared \\public void keyTyped(KeyEvent kt) {}public void keyPressed(KeyEvent kp) {}public void focusGained(FocusEvent fg) {}public void mouseClicked(MouseEvent me) {}public void mouseEntered(MouseEvent me) {}public void mouseExited(MouseEvent me) {}public void mousePressed(MouseEvent me) {}}
Sign in to follow this  


Recommended Comments

A screen shot of the above code may help more people understand how these components work.

Personally, I am not a huge fan of Java, but it is great for cross platform projects.

Share this comment

Link to comment

I personally no longer would spend Time with Java Swing. I was a Pro and used in Projects but, its simply out-of-date. You have to worry about stuff which should be provided by Swing. There are so many missing features. And the architecture is sometimes quite complicated so that you are not sure, if you misunderstood the MVC concept or if it is simply a problem of the API.

Share this comment

Link to comment

I see a couple of things that alone in that example might not be an issue but it could add up in a project.


Unnecesary objects:

There is no need for creating new RenderingHints each time the widget is drawn. You could just set them individually and since they're enums, no new object gets initialized.

Font object is getting created each time the thing is drawn, also it could be retained somewhere as a field.


Unnecesary work:

The Image is downloaded from internet (!) each time the widget is drawn, if you do that with several components, it will be slow as fuck. It should be loaded only once, maybe in the constructor, and stored as a field.


In any case, its a good example of the crazy things you can do when you start to implement all the listener interfaces :D

Share this comment

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!