Java Swing - Gui - Code / Coding

Ace your homework & exams now with Quizwiz!

color - constants

Color.BLACK Color.BLUE Color.CYAN Color.DARK_GRAY Color.GRAY Color.GREEN Color.LIGHT_GRAY Color.MAGENTA Color.ORANGE Color.PINK Color.RED Color.WHITE Color.YELLOW

System.exit

In order to end a GUI program, System.exit must be used when the user asks to end the program - It must be explicitly invoked, or included in some library code that is executed - Otherwise, a Swing program will not end after it has executed all the code in the program

GUI - combo boxes

String[] bookTitles = new String[] {"Effective Java", "Head First Java", "Thinking in Java", "Java for Dummies"}; JComboBox<String> bookList = new JComboBox<>(bookTitles); // add to the parent container (e.g. a JFrame): add(bookList); // get the selected item: String selectedBook = (String) bookList.getSelectedItem(); System.out.println("You seleted the book: " + selectedBook);

JFrame

The JFrame class is found in the javax.swing package. - A JFrame object includes 1. a border 2. the usual three buttons (shown at top right of typical window) : (a) minimizing, (b) changing the size of, and (c) closing the window import javax.swing.JFrame; import javax.swing.JButton;

Recursive Method - writing the recursive case

Write code to complete printFactorial()'s recursive case. Sample output if userVal is 5: 5! = 5 * 4 * 3 * 2 * 1 = 120 public class RecursivelyPrintFactorial { public static void printFactorial(int factCounter, int factValue) { int nextCounter = 0; int nextValue = 0; if (factCounter == 0) { // Base case: 0! = 1 System.out.println("1") } else if (factCounter == 1) { // Base case: Print 1 and result System.out.println(factCounter + " = " + factValue); } else { // Recursive case System.out.print(factCounter + " * "); nextCounter = factCounter - 1; nextValue = nextCounter * factValue; /* Your solution goes here */ *printFactorial (nextCounter, nextValue);* } } public static void main (String [] args) { int userVal = 0; userVal = 5; System.out.print(userVal + "! = "); printFactorial(userVal, userVal); return; } }

Recursive Method - writing the recursive math method

Write code to complete raiseToPower(). Sample output if userBase is 4 and userExponent is 2 is shown below. Note: This example is for practicing recursion; a non-recursive method, or using the built-in method pow(), would be more common. 4^2 = 16 public class ExponentMethod { public static int raiseToPower(int baseVal, int exponentVal) { int resultVal = 0; if (exponentVal == 0) { resultVal = 1; } else { *resultVal = baseVal * raiseToPower (baseVal, exponentVal-1);* } return resultVal; } public static void main (String [] args) { int userBase = 0; int userExponent = 0; userBase = 4; userExponent = 2; System.out.println(userBase + "^" + userExponent + " = " + raiseToPower(userBase, userExponent)); return; } }

JLabel greeting = new JLabel("Hello"); add(greeting);

a label can then be added to a JFrame

firstWindow.add(endButton);

adding button

public JFrame()

constructor, creates an object of the class JFrame

public JFrame(String Title)

constructor, creates an object of the class JFrame with the title given as the argument

JFrame firstWindow = new JFrame();

creating new JFrame. - A JFrame can have components added to it, such as buttons, menus, and text labels

FirstSwingDemo.java

import javax.swing.JFrame; import javax.swing.JButton; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame firstWindow = new JFrame( ); firstWindow.setSize(WIDTH, HEIGHT); firstWindow.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE); JButton endButton = new JButton ("click to end program."); EndingListener buttonEar = new EndingListener(); endButton.addActionListener(buttonEar); firstWindow.add(endButton); firstWindow.setVisible(true); // EndingListener.java file public class EndingListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0);} }

firstWindow.setVisible(true);

makes components visible

Recursive Method - calling a Recursive Method

public class RecursiveCalls { public static void backwardsAlphabet(char currLetter) { if (currLetter == 'a') { System.out.println(currLetter); } else { System.out.print(currLetter + " "); backwardsAlphabet(--currLetter); } return; } public static void main (String [] args) { char startingLetter = '-'; startingLetter = 'z'; /* Your solution goes here */ *backwardsAlphabet(startingLetter);* return; } }

JFrame - methods

public void setSize (int width, int height) public void setTitle (String title) public void add (Component componentAdded) public void setLayout (LayoutManager manager) public void setJMenuBar (JMenuBar menuBar) public void dispose ()

JFrame constants (4), what happens when JFrame is closed.... public void setDefaultCloseOperation (int operation) 1. JFrame.DO_NOTHING_ON_CLOSE 2. JFrame.HIDE_ON_CLOSE 3. JFrame.DISPOSE_ON_CLOSE 4. JFrame.EXIT_ON_CLOSE

sets the action that will happen by default when the user clicks the close-window button. 1. JFrame does nothing, but registered window listeners are invoked. 2. hide the frame after invoking 3. hide and dispose 4. exit the application (do not use for applets) ( if no action is specified using setDefaultCloseOperation, then the default action taken is Hide_on_close)

color- getContentPane().setBackground(Color);

the background color of a JFrame can be set using the following code:

GUI - event listener

*Adding an event listener* bookList.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JComboBox<String> combo = (JComboBox<String>) event.getSource(); String selectedBook = (String) combo.getSelectedItem(); if (selectedBook.equals("Effective Java")) { System.out.println("Good choice!"); } else if (selectedBook.equals("Head First Java")) { System.out.println("Nice pick, too!"); } } });

BorderLayouts

*setLayout(new BorderLayout());*

Recursive Method - creating a Recursive Method

// Write code to complete doublePennies()'s base // case public class CalculatePennies { // Returns number of pennies if pennies are // doubled numDays times public static long doublePennies(long numPennies, int numDays) { long totalPennies = 0; /* Your solution goes here */ *if(numDays==0)return numPennies;* else { totalPennies = doublePennies((numPennies * 2), numDays - 1); } return totalPennies; } // Program computes pennies if you have 1 penny // today, // 2 pennies after one day, 4 after two days, and // so on public static void main (String [] args) { long startingPennies = 0; int userDays = 0; startingPennies = 1; userDays = 10; System.out.println("Number of pennies after " + userDays + " days: " + doublePennies(startingPennies, userDays)); return; } }

GUI - menus

A menubar is created with JMenuBar. *JMenuBar menubar = new JMenuBar();* An Exit icon is displayed in the menu. *ImageIcon exitIcon = new* *ImageIcon("src/main/resources/exit.png");* A menu object is created with the JMenu class *JMenu file = new JMenu("File");* *file.setMnemonic(KeyEvent.VK_F);*


Related study sets

TORTS - Negligence: Standard of care: RPP, Custom, Negligence per se, special D's, Bailments

View Set

Learning Curve 14a: Puberty Begins

View Set

Prokaryotic and Eukaryotic Cells

View Set

MED SURG Exam 3 PrepU questions Module 8

View Set

Is That Plagarism? 🤷‍♂️

View Set

The Republicans' 1994 Contract with America is an example of which of the following ideas?

View Set

AP Human Geo Chapter 3 Key Issue 1 & 2

View Set