Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Java User Interface Programming

No description
by

Gaurav Paryani

on 27 February 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Java User Interface Programming

Now that you know the difference between command-line and Graphical User Interface (GUI), let's get into Swing... import javax.swing.*;

public class GUITest
{
public static void main(String[] args)
{
JFrame frame = new JFrame("My First Swing App");
JButton button = new JButton("click me");
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300);
frame.setVisible(true);
}
} Java User Interface Programming Using Swing components and layouts The content of this prezi is based off of Head First Java, 2nd edition by Kathy Sierra and Bert Bates (2005). Introduction Question: What is the main difference between apps that you have coded so far and the apps that you use daily (e.g. an internet browser, word processor, code editor, etc.)? Hint: Think of the way you see and use them. Still don't get it? Here's the answer: They all have a... GRAPHICAL USER INTERFACE! So far, all the apps you have coded are command-line, meaning that they are very simple, meant for older computers like the text-based MS-DOS. Swing is the GUI toolkit that ships with your Java development kit (JDK). Let's make a simple app... import the package containing the Swing classes A JFrame represents a window on the screen. You don't add components to the frame directly, instead you must add to the frame's content pane, which is where the components reside. This makes sure that your program exits when you close the window, otherwise your program will hang. If you don't add this, nothing will appear when you run your program. Now, let's see how it looks: Whoa! The button filled the whole window! Later on, we will learn how to control the placement (and size) of components. But first, let's see how to see if a button was clicked... Quick question: There needs to be a method that is called when a button is clicked. But how will the button know that it is supposed to call that method? If you want to know a button's events, implement an interface that says, "I'm listening for your events." An listener interface is the bridge between the listener (you) and the event source (the button). Swing uses a model known as the event-listener approach. In other words, when something is done with a component, the component fires the respective methods in the listeners that are registered with the buttons. Therefore, to get ahold of the button's events, you must implement the ActionListener interface to get the button's actions. So, here are the steps for getting a button's ActionEvent: 1. Implement the ActionListener interface

2. Register with the button, i.e. make your class one of the button's listeners

3. Define the event-handling method (implement the actionPerformed() method defined in ActionListener) Let's try it out: import javax.swing.*;
import java.awt.event.*;

public class SimpleGui1B implements ActionListener
{
private JButton button;

public static void main(String[] args)
{
new SimpleGui1B().go();
}

public void go()
{
JFrame frame = new JFrame();
button = new JButton("click me");

button.addActionListener(this);

frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
button.setText("I've been clicked!");
}
} Give the frame a size, in pixels. Add a new import for the package that ActionListener and ActionEvent are in. Register your class instance with the button. The parameter must be an instance of a class that implements ActionListener, which in this case is the current object, so you pass "this". Implement the actionPerformed() method defined in the ActionListener interface. This is the actual event-handling method. Let us see how that looks... after clicking Now, before going deeper into event handling, let's see how we can paint graphics on the screen... Drawing graphics on the screen There are many different ways to put stuff on your GUI! The three that we will cover are these: 1. Putting widgets on a frame



2. Drawing 2D graphics on a widget



3. Putting your own JPEG image on a widget Add buttons, menus, checkboxes, etc. The javax.swing package has more than a dozen widget types. The Java2D API is full of many different shapes such as ovals, rectangles, triangles, and more. That's right, you can even put your own images on your user interface! Here's how to make your own drawing widget: The best way to draw your own graphics is to create your very own drawing widget. You add it to your frame just like you add many different widgets (like buttons), but when it shows up on the screen, it shows your drawing. You can even make those images move (such as in an animation) or change the colors upon the occurrence of an event (such as an ActionEvent). It's surprisingly easy: Simply create a subclass of JPanel and override the paintComponent() method! All of your graphics code goes inside the paintComponent() method. Think of it as the method called by the system to tell the widget to paint itself. For example, to draw a circle, write the circle-drawing code in paintComponent(). When the frame holding your widget is displayed, paintComponent() is called. If the user minimizes the window, the system knows it's going to have to refresh the window, leading to another call of paintComponent(). In other words, anytime the system thinks the display needs refreshing, it calls paintComponent(). One more really important thing: YOU NEVER CALL THIS METHOD YOURSELF! The argument passed to paintComponent() (a Graphics object) is the thing that is placed on to the REAL display. You can't get this by yourself; it must be handed down to you by the system. However, you'll see later on, that you can ask the system to manually refresh the display, which will ultimately lead to the widget being redrawn. Let's try it out... import java.awt.*;
import javax.swing.*;

class MyDrawPanel extends JPanel
{

public void paintComponent(Graphics g)
{

g.setColor(Color.ORANGE);

g.fillRect(20, 50, 100, 100);
}
} You'll need both of these. Make a subclass of JPanel, a widget that you can add to a frame just like anything, except this is your own, customized widget. This is the graphics method. You will NEVER call this yourself. The system calls it and passes a Graphics object that the method can paint on. Imagine that 'g' is a painting machine. You're telling it what color to paint with and what shape to paint (with coordinates for where it goes and how big it is) Some fun stuff to do in paintComponent() Add an image public void paintComponent(Graphics g)
{
Image image = new ImageIcon("ImageName.jpg").getImage();
g.drawImage(image, 3, 4, this);
} file name goes here The x-y coordinates for the image. They are relative to the widget (your JPanel subclass), NOT the frame. Draw a randomly-colored circle on a black background public void paintComponent(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());



int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);

g.setColor(new Color(red, green, blue));
g.fillOval(70, 70, 100, 100);
} fill the entire panel with black The first two arguments are the x-y coordinates of the starting point of the rectangle. The other two define the dimensions of the rectangle, in pixels. In this case, thay are the height and width of the panel, and they can be accessed via the methods you inherit from JPanel. Create a new color by passing in the individual color values. The values can be from 0 (color is off) and 255 (color is on at brightest level). start 70 pixels from the left, 70 from the top, and make it 100 pixels wide and 100 pixels tall. Remember the rules of polymorphism... The argument to paintComponent(Graphics g) is declared as type Graphics (java.awt.Graphics). Remembering the rules of polymorphism, the argument can be either a Graphics object or a subclass of Graphics. And in fact, it is an object of a Graphics subclass. The argument to paintComponent() is actually an instance of the Graphics2D class. Why do you care? Because there are additional stuff that you can do with a Graphics2D reference than with a Graphics reference. Remember, the compiler decides which methods you can call on a reference on the reference type, not the actual object type. So, if you have the following:

Object o = new String("Hello!");

You CANNOT say:

char a = o.charAt(2);

Therefore, if it is necessary to use a method from the Graphics2D class, you must use a cast:

Graphics2D g2d = (Graphics2D) g; Methods you can call on a Graphics reference: drawImage()
drawLine()
drawPolygon()
drawRect()
fillRect()
fillRoundRect()
setColor() on a Graphics2D reference: fill3DRect()
draw3DRect()
rotate()
scale()
shear()
transform() Note: these are incomplete lists; check the API for more. With Graphics2D, you aren't limited to a solid color. You can even paint a gradient! Let's see: public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;

GradientPaint gradient = new GradientPaint(70, 70, Color.BLUE, 150, 150, Color.ORANGE);


g2d.setPaint(gradient);
g2d.fillOval(70, 70, 100, 100);
} It's really a Graphics2D object masquerading as a mere Graphics object. cast it so that we can call something that Graphics2D has but Graphics doesn't starting point starting color ending point ending color set the virtual paint brush to a gradient instead of a solid color We can get an event. We can paint graphics.
But can we paint graphics upon receiving an event? Let's create a program that has a circle that changes color upon the user clicking a button. The basic design: We have a frame with a button. The rest of the frame has a black background with a circle. When the user clicks the button, the color of the circle will randomly change. click the button and the color changes But wait... How do we put more than one component onto a frame? So far, we have just been dealing with putting just one component onto a frame, such that it fills the entire frame, like the first example. But how do we put more than one component onto a frame? GUI Layouts: Putting more than one component onto a frame We'll go in depth on layouts later, but here's a quick lesson to get you going: By default, a frame has five regions that you can add to: north, south, east, west, and center. You can add only one component to each region, but don't worry! That could be a panel that contains other components! In fact, we weren't using proper design when we were saying:

frame.getContentPane().add(button); This isn't really the way you're supposed to do it (the single-argument add() method) north south east west center Let's do the same thing, except now we'll specify the region we want to add it in When you do this:

frame.getContentPane().add(button);

The component that you add will end up in the center region. But if you want it to be in a different region, specify it:

frame.getContentPane().add(BorderLayout.SOUTH, button); We're going ahead We're going ahead and checking out how to get some more events. But, if you want to stay behind and look at the code of the program we just discussed, you can: import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleGui3C implements ActionListener
{
JFrame frame;

public static void main(String[] args)
{
new SimpleGui3C().go();
}

public void go()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button = new JButton("Change colors");
button.addActionListener(this);

JPanel pane = (JPanel) frame.getContentPane();
pane.add(BorderLayout.SOUTH, button);
pane.add(BorderLayout.CENTER, new MyDrawPanel());
frame.setSize(300, 300);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
frame.repaint();
}
} save the frame's content pane into a reference so that we don't have to type frame.getContentPane() every time Our JPanel subclass. Call repaint() on the frame. This calls paintComponent() on every widget in the frame. Now, back to event handling... Let's try it with two buttons! The button in the south region will continue to work as before. The second button, which we'll put in the east region, will change the text of a label, which is text on the screen that isn't in anything else. Ahh...but how do we get events from TWO buttons when we have just ONE actionPerformed() method?? 1 2 3 Choice 1 Implement two actionPerformed() methods class MyGui implements ActionListener
{
//lots of code here and then:

public void actionPerformed(ActionEvent e)
{
frame.repaint();
}

public void actionPerformed(ActionEvent e)
{
label.setText("Ouch!");
}
} But this is impossible! Register the same listener with both buttons class MyGui implements ActionListener
{
JButton colorButton, labelButton;

public void go()
{
//build gui
colorButton = new JButton();
labelButton = new JButton();
colorButton.addActionListener(this);
labelButton.addActionListener(this);
}

public void actionPerformed(ActionEvent event)
{
if(event.getSource() == colorButton) {
frame.repaint();
} else {
label.setText("That hurt!");
}

}
}
Full transcript