Programming graphics Drawing rectangles for example � Need a window – javax.swing.JFrame � Define class that extends JComponent – Several essential steps to use (necessary “plumbing”): – Or a subclass like JPanel for additional features � Set the size – width and height in pixels � Implement paintComponent method � Set a title (optional), and a close operation – Use Graphics object passed to this method � Make it visible – See EmptyFrameViewer.java (p. 59) � Actually a Graphics2D object since Java 1.2 � Add javax.swing.JComponent s to window – Then let that object draw Rectangle objects – Draw shapes, colors, … on these components – See RectangleComponent.java (p. 61) � That’s all there is to it! � Add the component to a frame for viewing – Except for the painstaking labor, of course – e.g., RectangleViewer.java java.awt.Graphics2D Drawing more complex shapes � Is a subclass of java.awt.Graphics � Text example (p. 114-116) – Car.java – So cast is allowed; and Graphics methods inherited – Acts like a Car that can draw itself – Car constructor sets x and y locations – If don’t cast, must use primitive drawing methods: � e.g., drawRect(int, int, int, int) , – Includes draw(Graphics2D g2) method fillOval(int, int, int, int) , … � Lets Graphics2D object draw lines, ellipses, rectangles � i.e., not object-oriented – so lots of work to use/reuse � A class like CarComponent.java just uses it: � But Graphics2D can do a lot more stuff Car myCar = new Car(x, y); – e.g., draw(java.awt.Shape) draws any Shape , myCar.draw(g2); // passes reference to graphics object including Rectangle , Ellipse2D , Polygon , … � Still need a view window, like CarViewer.java – fill(Shape) draws and fills Shape with current color C o l o r Rendering text with Graphics2D � Current color applies to text, lines, and fills: � Actually necessary to “draw” the text at a g2.setColor(Color.RED); specified location on the Graphics object g2.draw( … ); // draws … in red g2.setColor(Color.BLUE); – g.drawString(aString, x, y) – uses g2.fill(…); // fills … with blue current rendering context (e.g., color), and � Custom colors available: current text attributes (e.g., font) – Can set by float values in range 0.0F to 1.0F : � Font: a face name, a style , and a point size Color gb = new Color(0.0F, 0.7F, 1.0F); g2.setColor(gb); Font f = – Or by int values in range 0 to 255 : new Font(“Serif”, Font.BOLD, 24); Color bg = new Color(0, 255, 175); g2.setFont(f); // sets font for g2 1
Applets – an alternate approach “Running” an Applet � The applet is started by the web browser as soon as the � A way to run a program – but not an application web page (html file) is visited – No main method necessary � The html file (stands for hypertext markup language) — must have � Need a subclass of Applet (or JApplet) an applet tag in it: – So: class __ extends Applet (or extends JApplet ) <applet code=AppletClassName.class � Most web browsers know how to create a new width=### height=###> </applet> <!-- needs a closing tag too --> applet, and how to use certain Applet methods � The browser works in a certain order: – So, applets must be embedded in an html page – Creates a new applet object – includes a window, a Graphics object, lots – And, to be useful, they must include at least one of the of class Applet methods methods the browser invokes (e.g., paint ) – Invokes (1) init – once, (2) start – first & return visits, (3) paint – first & every need to paint (also stop , destroy ) Implementing a “simple” applet Images � import javax.swing.JApplet; // mandatory � Images are not drawings – Also usually Graphics and Graphics2D and others – You don’t draw them, you show them � Declare a class that extends JApplet: – But Graphics method is called drawImage anyway public class RectangleApplet extends JApplet � Implement paint method (at least) � Image is an abstract class – Same procedures as paintComponent for components – Generally, create instance by loading from file or URL � Create an html file to load the applet in a web – Can also create/edit by classes in java.awt.image browser or the appletviewer (provided with JDK) � Applets know how to get images (ImageApplet) � See RectangleApplet.java (p. 63) and related html – Applications use Toolkit to get (demo) files (p. 64) Toolkit.getDefaultToolkit().getImage("javacup.gif"); Events Event sources � Signals from the outside � Technically: can be any external signal – Usually user initiates: – Including from a different program or system � Mouse click, button push, � e.g., a “client” applet contacting a web “server” menu-select, enter text, … – In a GUI, focus is on user signals – Not always: TimerTester.java � Java Component s generate the events � Each event has a type – a – Each component generates different event types, e.g.: class in java.awt.event � Panels (inc. Applets) � MouseEvent s – So each event is an object � Textfields and buttons � ActionEvent s � Windows � WindowEvent s – Created almost constantly � Keyboard � KeyEvent s (by Java window manager) – Components inform a list of Listener s about events 2
Listeners Inner class listeners � Objects that components tell about events � Can access private instance variables of outer class – Must have methods a component can invoke – Stores implicit reference to outer class object � i.e., implements one of the Listener interfaces – So can often “handle” events more easily – Must be add ed to a component’s listener list � e.g., RectangleComponentViewer.java � Different listeners apply to different messages � Notice they can access final local variables too – ActionListener – actionPerformed � e.g., ClickListener (with ButtonTester.java) – Another example: TimerTester2.java – MouseListener – mouseClicked , mouseEntered , … – Must be final so no ambiguity about value � e.g., MouseSpy demo (from 1 st edition of textbook) � Note: also can extend Adapter class instead of – For example, no opportunity for variable to go out of implement listeners directly – saves busywork ☺ scope while object exists Laying out GUI components Choosing a layout manager � Depends on layout � e.g., a grid layout for manager calculator buttons: – Defaults: panel.setLayout( new � JFrame: GridLayout(4,3) ); BorderLayout panel.add(button7); � JPanel: FlowLayout panel.add(button8); – Others: panel.add(button9); panel.add(button4); � GridLayout � GridBagLayout ... � Can set new, and � e.g., CS10Display.java even make custom Text components Choices � JLabel – not for user input, just display � Choice objects generate ActionEvents � JTextField – for one row of text � Handlers for JCheckBox and JRadioButton : use – new JTextField(), or (int columns) boolean method isSelected() – getText(), setText(String), setFont(Font), – Note: put radio buttons in a ButtonGroup – so just setEditable(boolean), … (mostly inherited) one can be selected at a time – ActionEvent on <enter> – For same reason – should visually group them in a � JTextArea – for multiple rows of text panel with a border, like EtchedBorder – new JTextArea(), or (int rows, int columns) � For JComboBox : use getSelectedItem() – Same methods inherited from JTextComponent – Note: returns Object – usually cast to String – Generates no events, so usually use with a button � e.g., ChoiceFrame.java (see FontViewer.java, pp. 794-798) 3
Sliders, and more swing ing Menus � Steps to implement swing menus: � Note - good text section 18.4, pp. 808-814: – 1. Add a menu bar to a JFrame should read while browsing API on web JMenuBar bar = new JMenuBar(); – About how to “discover” swing features/usage setJMenuBar(bar); � Focuses on JSlider – generates ChangeEvent s, so – 2. Add menus to the menu bar addChangeListener(listener) , where listener JMenu fileMenu = new JMenu(“File”); implements stateChanged method bar.add(fileMenu); � Requires javax.swing.event for “change” events – 3. Add menu items to the menus, & listeners to items – e.g., SliderFrame.java (see ColorViewerFrame.java, pp. 812-814) JMenuItem openItem = new JMenuItem(“Open”); � Explore swing as needed, or even just for fun fileMenu.add(openItem); – Buy a book, or look at API classes starting with “ J ” openItem.addActionListener(listener); � e.g., MenuFrame.java (see FontViewer2.java, pp. 803-7) – Or just run the SwingSet demo from the JDK 4
Recommend
More recommend