CIS3931 - Intro to JAVA

slimwhimperΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 4 χρόνια και 8 μήνες)

116 εμφανίσεις


Intro to JAVA

Lecture Notes Set 9


GUI Programming

EditorPane and

The smallest GUI frame program

import java.awt.*;

import javax.swing.*;

public class TestFrame1


public static void main ( String[] args )


JFrame frame = new JFrame("Test Frame 1");


frame.setVisible( true );



Program explanation

//Call the new constructor for JFrame and set

//the title = “Test Frame 1”

JFrame frame = new JFrame(“Test Frame 1”);

//Set the initial size to 200w x 100h pixels


//Make the frame visible (default is invisible)


Extending JFrame

GUIs are usually written in a class that
extends the JFrame

Main program then calls this class to run
the GUI.

This is how we will be writing our GUI

Extending JFrame example

import java.awt.*;

import javax.swing.*;

class MyFrame extends JFrame


// paint() is called automatically by the system to display your customizations to the frame.

public void paint ( Graphics g )


g.drawString("A MyFrame object", 10, 50 );
// draw a String at location x=10 y=50



public class TestFrame2


public static void main ( String[] args )


MyFrame frame = new MyFrame();
// construct a MyFrame object

frame.setSize( 150, 100 );
// set it to 150 wide by 100 high

frame.setVisible( true );
// ask it to become visible

// paint() is indirectly called



Example explanation

MyFrame extends JFrame

MyFrame does everything JFrame does,
with the addition of whatever methods are
in MyFrame.

A MyFrame is constructed, which actually
constructs a JFrame in addition to
whatever you added in MyFrame.

Creating an editorPane

editorPane = text window that allows the
user to type

Also includes methods that can print
information to the text window

Looks just like the editor window in
Microsoft Notepad

A skeleton editorPane

The following code will create a simple
EditorPane and put it in a JFrame. The
EditorPane was created to be “scrollable.”


GUI menu is called a JMenu

JMenus must be in a JMenuBar

Items in a JMenu are called JMenuItems

Menu example

//Create the JMenuBar

JMenuBar menuBar = new JMenuBar();

//Set the created bar to be the menu bar for this frame


//Create a JMenu called “Test”

JMenu menu = new JMenu(“Test”);

//Add a JMenuItem called “item1” to the JMenu

menu.add(new JMenuItem(“item1”));

//Add the menu to the JMenuBar


Adding the menu the EditorPane


Assignment 4

Create a simple GUI EditorPane with
some menu elements

This GUI will then be used to create a
simple text editor in Assignment 5

See Assignment description on course

Assignment Preview

Full text editor

Assignment 5

Web browser

Assignment 6