Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
// Simple Example with JOptionPane import javax.swing.JOptionPane; // program uses JOptionPane public class Addition { public static void main( String args[]) { // obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert String inputs to int values for use in a calculation int number1 = Integer.parseInt( firstNumber ); int number2 = Integer.parseInt( secondNumber ); int sum = number1 + number2; // add numbers // display result in a JOptionPane message dialog JOptionPane.showMessageDialog(null,"The sum is " + sum,"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); } // end method main } // end class Addition import javax.swing.*; public class FrameTest { public static void main(String args[]) { JFrame firstFrame = new JFrame("First Frame"); firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); firstFrame.setSize(200, 300); firstFrame.setVisible(true); } } // end main // end class FrameTest import javax.swing.*; import java.awt.*; public class Label0 { public static void main(String[] args){ LabelFrame firstLabel = new LabelFrame("Frame with Label"); firstLabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); firstLabel.setSize(200, 300); irstLabel.setVisible(true); } // end main } // end class Label1 class LabelFrame extends JFrame { // creates a JLabel reference private JLabel label1; public LabelFrame(String title) { super(title); // send the title to JFrame’s consturctor // set labout setLayout(new FlowLayout()); // create a new JLabel refered by label1 label1 = new JLabel("I am a label"); add(label1); // add to the frame } // end constructor } // end classLabelFrame import javax.swing.*; import java.awt.*; public class Label0 { public static void main(String[] args) { JFrame firstLabel = new JFrame("Frame with Label"); firstLabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); firstLabel.setSize(200, 300); firstLabel.setVisible(true); JLabel label1; // a JLabel type varible firstLabel. setLayout(new FlowLayout()); // create a new JLabel refered by label1 label1 = new JLabel("I am a label"); firstLabel.add(label1); // add to the frame } // end main } // end class Label1 class LabelFrame extends JFrame { // creates three JLabel references private JLabel label1; private JLabel label2; private JLabel label3; public LabelFrame(String title) { super(title); // send the title to JFrame’s consturctor // set labout setLayout(new FlowLayout()); // create a new JLabel refered by label1 label1 = new JLabel("I am a label"); add(label1); // add to the frame // create a new JLabel refered by label2 label2 = new JLabel("second label"); label2.setToolTipText("tooltip of scond label"); // set a tooltip to label2 invoking setToolTip method add(label2); // add to the frame // create a new JLabel refered by label3 label3 = new JLabel(); label3.setText("label 3"); label3.setToolTipText("tool tip text 3"); label3.setHorizontalTextPosition(SwingConstants.CENTER); label3.setVerticalTextPosition(SwingConstants.BOTTOM); add(label3);; } // end constructor } // end class LabelFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Button0 { public static void main(String[] args) { ButtonFrame jButtonFrame = new ButtonFrame("Title"); jButtonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jButtonFrame.setLocationRelativeTo(null); jButtonFrame.setSize(200, 400); jButtonFrame.setVisible(true); } } class ButtonFrame extends JFrame { private JButton button; public ButtonFrame(String title) { super(title); setLayout(new FlowLayout()); button = new JButton("I am a Button"); add(button); ButtonHandler handler = new ButtonHandler(); button.addActionListener(handler); } // end constructor private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog( null,"You clicked me"); } // end actionPerformed } // end inner class } // end class ButtonFrame // Simple TextField example import javax.swing.*; import java.awt.*; public class Text0 { public static void main(String[] args) { JText0 jTextFrame = new JText0("TextField"); jTextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jTextFrame.setSize(200, 400); jTextFrame.setVisible(true); } end main } end class Text0 class JText0 extends JFrame { private JTextField textField1; public JText0(String title) { super(title); setLayout(new FlowLayout()); textField1 = new JTextField(10); add(textField1); TextHandler handler = new TextHandler(); textField1.addActionListener(handler); } // end constructor JText0 // the class has not ended private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String string = String.format( “textfield:%s”,e.getActionCommand()); JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end innter class TextHandler } // end class JText0 Another approach only the inner class is changed private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { // useing the getText method String string = String.format( “text field:%s”,textField1.getText()); JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end innter class TextHandler } // end class JText0 // Text and Pasward Fields book’s example import java.awt.*; import javax.swing.*; public class TextFieldTest { public static void main( String args[] ){ TextFieldFrame textFieldFrame = new TextFieldFrame(); textFieldFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); textFieldFrame.setSize( 325, 100 ); // set frame size textFieldFrame.setVisible( true ); // display frame } // end main } // end class TextFieldTest class TextFieldFrame extends JFrame { // text field with set size private JTextField textField1; // text field constructed with text private JTextField textField2; // text field with text and size private JTextField textField3; // password field with text private JPasswordField passwordField; // TextFieldFrame constructor adds JTextFields to JFrame public TextFieldFrame() { super( "Testing JTextField and JPasswordField"); // set frame layout setLayout( new FlowLayout() ); // construct textfield with 10 columns textField1 = new JTextField( 10 ); // add textField1 to JFrame add( textField1 ); // construct textfield with default text textField2 = new JTextField( "Enter text here" ); // add textField2 to JFrame add( textField2 ); // construct textfield with default text and 21 columns textField3 = new JTextField( "Uneditable text field", 21); // disable editing textField3.setEditable( false ); // add textField3 to JFrame add( textField3 ); // construct passwordfield with default text passwordField = new JPasswordField( "Hidden text"); // add passwordField to JFrame add( passwordField ); // register event handlers TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler ); passwordField.addActionListener( handler ); } // end TextFieldFrame constructor // private inner class for event handling private class TextFieldHandler implements ActionListener { // process text field events public void actionPerformed( ActionEvent event ) { String string = ""; // declare string to display // user pressed Enter in JTextField textField1 if ( event.getSource() == textField1 ) string = String.format( "textField1: %s", event.getActionCommand() ); // user pressed Enter in JTextField textField2 else if ( event.getSource() == textField2 ) string = String.format( "textField2: %s", event.getActionCommand() ); // user pressed Enter in JTextField passwordField else if ( event.getSource() == passwordField ) string = String.format( "passwordField: %s", new String( passwordField.getPassword() ) ); // display JTextField content JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end private inner class TextFieldHandler } // end class TextFieldFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Button0 { public static void main(String[] args) { ButtonFrame jButtonFrame = new ButtonFrame("Title"); jButtonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jButtonFrame.setLocationRelativeTo(null); jButtonFrame.setSize(200, 400); jButtonFrame.setVisible(true); } } class ButtonFrame extends JFrame { private JButton button; public ButtonFrame(String title) { super(title); setLayout(new FlowLayout()); button = new JButton("I am a Button"); add(button); ButtonHandler handler = new ButtonHandler(); button.addActionListener(handler); } // end constructor private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog( null,"You clicked me"); } // end actionPerformed } // end inner class } // end class ButtonFrame import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBox0 { public static void main(String[] args) { CheckBoxFrame0 checkBoxFrame0 = new CheckBoxFrame0(); checkBoxFrame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); checkBoxFrame0.setSize(400, 400); checkBoxFrame0.setVisible(true); } // end mehod main } endd class CheckBox0 class CheckBoxFrame0 extends JFrame { private JLabel priceLabel; private JCheckBox cheeseCheckBox; private JCheckBox salamiCheckBox; private int pricePlane = 10; private int priceCheese = 5; private int priceSalami = 7; private int totalPrice = pricePlane; private String priceString = "price: "; public CheckBoxFrame0() { setLayout(new FlowLayout()); // creating and adding textField priceLabel = new JLabel(priceString+totalPrice); add(priceLabel); // creating and adding checkBox objects cheeseCheckBox = new JCheckBox("Cheese"); salamiCheckBox = new JCheckBox("Salami"); add(cheeseCheckBox); add(salamiCheckBox); // registering events to the checkBoxes CheckBoxHandler handler = new CheckBoxHandler(); cheeseCheckBox.addItemListener(handler); salamiCheckBox.addItemListener(handler); } // end constructor private class CheckBoxHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if(event.getSource()==cheeseCheckBox) totalPrice += cheeseCheckBox.isSelected() ? priceCheese :-priceCheese ; if(event.getSource()==salamiCheckBox) totalPrice += salamiCheckBox.isSelected() ? priceSalami :- priceSalami ; priceLabel.setText(priceString+totalPrice); } // end ItemSteteChanged method } // end CheckBoxHandler inner class } // end CheckBoxFrame0 class Another implementation of the CheckBoxHandler private class CheckBoxHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if(cheeseCheckBox.isSelected() && salamiCheckBox.isSelected()) totalPrice = priceCheese+priceSalami+pricePlain; else if(cheeseCheckBox.isSelected()) totalPrice = priceCheese+pricePlain; else if(salamiCheckBox.isSelected()) totalPrice = priceSalami+pricePlain; else totalPrice = pricePlain; priceLabel.setText(priceString+totalPrice); } // end ItemSteteChanged method } // end CheckBoxHandler inner class } // end CheckBoxFrame0 class //imports public class RadioButton0 { public static void main(String[] args) { RadioButtonFrame0 radioButtonFrame0 = new RadioButtonFrame0("Radio Button Example"); } } class RadioButton0 extends jFrame { private JLabel label; private JRadioButton maleRadioButton; private JRadioButton femaleRadioButton; private ButtonGroup genderGrup; new; public RadioButtonFrame0(String title) { super(title); setLayout(new FlowLayout()); label = new JLabel(“gender is female"); add(label); maleRadioButton = new JRadioButton(“Male",false); femaleRadioButton = new JRadioButton(“Female",true); genderGrup = new ButtonGroup(); genderGrup.add(maleRadioButton); genderGrup.add(femaleRadioButton); add(mleRadioButton); add(femaleRadioButton); RadioButtonHandler handler = new RadioButtonHandler(); maleRadioButton.addItemListener(handler); femaleRadioButton.addItemListener(handler); } // end of constructor private class RadioButtonHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if(event.getSource() instanceof JRadioButton) { if(boyRadioButton.isSelected()) label.setText(“gender is male"); if(girlRadioButton.isSelected()) label.setText(“gender is female"); } } // end ItemSteteChanged method } // end Handler inner class } // end RadioButtonFrame0 class import javax.swing.*; import java.awt.*; import java.awt.event.*; public class RadioButtonFrame extends JFrame { // Changing fornt of a text with radio buttons // modified version of books example private JTextField textField; private JRadioButton italicRadioButton; private JRadioButton boldRadioButton; private JRadioButton italicveboldRadioButton; private JRadioButton plainRadioButton; private ButtonGroup fontGrup; public RadioButtonFrame() { setLayout(new FlowLayout()); textField = new JTextField(“trail",20); textField.setFont(new Font("Serif",Font.PLAIN,14)); add(textField); boldRadioButton = new JRadioButton("Bold",false); italicRadioButton = new JRadioButton("Italic",false); italicveboldRadioButton = new JRadioButton("italic&bold",false); plainRadioButton = new JRadioButton("plain",true); fontGrup = new ButtonGroup(); fontGrup.add(boldRadioButton); fontGrup.add(italicRadioButton); fontGrup.add(italicveboldRadioButton); fontGrup.add(plainRadioButton); add(boldRadioButton); add(italicRadioButton); add(italicveboldRadioButton); add(plainRadioButton); RadioButtonHandler handler = new RadioButtonHandler(); boldRadioButton.addItemListener(handler); italicveboldRadioButton.addItemListener(handler); italicRadioButton.addItemListener(handler); plainRadioButton.addItemListener(handler); } // end of constructor private class RadioButtonHandler implements ItemListener { private int valFont = Font.PLAIN; private Font newFont; public void itemStateChanged(ItemEvent event) { if(event.getSource() instanceof JRadioButton) { if(boldRadioButton.isSelected()) valFont = Font.BOLD ; if(italicRadioButton.isSelected()) valFont = Font.ITALIC; if(italicveboldRadioButton.isSelected()) valFont = Font.ITALIC+Font.BOLD; if(plainRadioButton.isSelected()) valFont = Font.PLAIN; } newFont = new Font("Serif",valFont,14); textField.setFont(newFont); } // end method ItemSteteChanged } // end inner class RadioButtonHandler } // end class RadioButtonFrame import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ComboBox0 { public static void main(String[] args) { ComboBoxFrame comboBoxFrame = new ComboBoxFrame(); comboBoxFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); comboBoxFrame.setSize(400, 200); comboBoxFrame.setVisible(true); } } class ComboBoxFrame extends JFrame { private JComboBox combo; private JTextArea status; String names[] = {"Ali","Burak","Can","Derya","Elif"}; String lastNames[] = {"Or","Pamuk","Ulaş","Tınaz","Yılmaz"}; int wages[] = {1000,1500,1200,800,900}; public ComboBoxFrame() { setLayout(new FlowLayout(FlowLayout.LEFT,10,30)); combo = new JComboBox(names); status = new JTextArea(7,25); add(combo); add(status); ComboBoxHandler handler = new ComboBoxHandler(); combo.addActionListener(handler); } // end constructor private class ComboBoxHandler implements ActionListener { public void actionPerformed(ActionEvent e) { int i = combo.getSelectedIndex(); status.setText(""); status.append("Name:"+names[i]+"\n"); status.append("LastName:"+lastNames[i]+"\n"); status.append("Wage:"+wages[i]); } // end method } // end inner class ComboBoxHandler } // end class ComboBoxFrame // with anonumous class implementatition class ComboBoxFrame extends JFrame { private JComboBox combo; private JTextArea status; String names[] = {"Ali","Burak","Can","Derya","Elif"}; String lastNames[] = {"Or","Pamuk","Ulaş","Tınaz","Yılmaz"}; int wages[] = {1000,1500,1200,800,900}; public ComboBoxFrame() { setLayout(new FlowLayout(FlowLayout.LEFT,10,30)); combo = new JComboBox(names); status = new JTextArea(7,25); add(combo); add(status); combo.addActionListener( // invoke method new ActionListener() { // anonymous class begins public void actionPerformed(ActionEvent e) { int i = combo.getSelectedIndex(); status.setText(""); status.append("Name:"+names[i]+"\n"); status.append("LastName:"+lastNames[i]+"\n"); status.append("Wage:"+wages[i]); } // end method } // end anonymous class ComboBoxHandler ); // end invoking addActionListener method } // end constructor } // end class ComboBoxFrame 5 import javax.swing.JFrame; 6 import javax.swing.JList; 7 import javax.swing.JScrollPane; 8 import javax.swing.event.ListSelectionListener; 9 import javax.swing.event.ListSelectionEvent; 10 import javax.swing.ListSelectionModel; 11 12 public class ListFrame extends JFrame 13 { 14 private JList colorJList; // list to display colors 15 private final String colorNames[] = { "Black", "Blue", "Cyan", 16 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", 17 "Orange", "Pink", "Red", "White", "Yellow" }; 18 private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN, 19 Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, 20 Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, 21 Color.YELLOW }; 26 super( "List Test" ); 27 setLayout( new FlowLayout() ); // set frame layout 29 colorJList = new JList( colorNames ); // create with colorNames 30 colorJList.setVisibleRowCount( 5 ); // display five rows at once 31 32 // do not allow multiple selections 33 colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); 34 35 // add a JScrollPane containing JList to frame 36 add( new JScrollPane( colorJList ) ); 37 38 39 40 41 42 43 44 45 46 47 48 49 50 colorJList.addListSelectionListener( new ListSelectionListener() // anonymous inner class { // handle list selection events public void valueChanged( ListSelectionEvent event ) { getContentPane().setBackground( colors[ colorJList.getSelectedIndex() ] ); } // end method valueChanged } // end anonymous inner class ); // end call to addListSelectionListener } // end ListFrame constructor } // end class ListFrame class ListFrame0 extends JFrame { private JList list; private JButton button; private JTextArea purchased; private String products[] = {"book","tea","cheese","bread","milk"}; private int prices[] = {10,12,20,15,2}; private int total; public ListFrame0() { setLayout(new FlowLayout()); list = new JList(products); list.setVisibleRowCount(3); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); button = new JButton("add"); purchased = new JTextArea(7,25); add(list); add(new JScrollPane(list)); add(button); add(purchased); button.addActionListener(new ListHandler()); } // end constructor private class ListHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==button) { total = 0; purchased.setText("purchased:"); int choice[] = list.getSelectedIndices(); for(int i = 0;i < choice.length;i++) { purchased.append("\n\t"+products[choice[i]]); purchased.append("\t"+prices[choice[i]]); total += prices[choice[i]]; } // end for purchased.append("\ntotal:\t"+total); } // end if } // end method actionPerformed } // end inner class ListHandler } // end class ListFrame0 // Border layout Example class BorderFrame0 extends JFrame { private private private private private JLabel title; JLabel result; JButton addition; JTextField first; JTextField second; public BorderFrame0() { setLayout(new BorderLayout(10,10)); title = new JLabel("Adding two integers"); result = new JLabel(" "); addition = new JButton("+"); first = new JTextField(10); second = new JTextField(10); add(title,BorderLayout.NORTH); add(addition,BorderLayout.CENTER); add(first,BorderLayout.WEST); add(second,BorderLayout.EAST); add(result,BorderLayout.SOUTH); ButtonHandler handler = new ButtonHandler(); addition.addActionListener(handler); } // end constructor private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { int a,b,sum; if(e.getSource() == addition) { a = Integer.parseInt(first.getText()); b = Integer.parseInt(second.getText()); sum = a+b; result.setText(""+a+" + "+b+" = "+sum); } // end if } // end method actionPerformed } // end inner class ButtonHandler } // end class GridFrame0 // Grid Layout Example class GridFrame0 extends JFrame { private JLabel name; private JLabel lastName; private JTextField nameText; private JTextField lastNameText; private JButton ok; private JButton cancel; public GridFrame0() { setLayout(new GridLayout(3,2,5,5)); name = new JLabel("Name"); lastName = new JLabel("Last Name"); ok = new JButton("OK"); cancel = new JButton("Cancel"); nameText = new JTextField(10); lastNameText = new JTextField(20); add(name); add(nameText); add(lastName); add(lastNameText); add(ok); add(cancel); ButtonHandler handler = new ButtonHandler(); ok.addActionListener(handler); cancel.addActionListener(handler); } // end constructor private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) System.out.println(nameText.getText()+ ""+lastNameText.getText()); if(e.getSource() == cancel) { nameText.setText(""); lastNameText.setText(""); } // end if } // end method actionPerformed } // end inner class ButtonHandler } // end class GridFrame0 // Same example with Panels class GridFrame1 extends JFrame implements ActionListener { private JLabel name; private JLabel lastName; private JTextField nameText; private JTextField lastNameText; private JButton ok; private JButton cancel; // create three panels private JPanel topPanel; private JPanel midPanel; private JPanel butomPanel; public GridFrame1() { setLayout(new GridLayout(3,1,5,5)); name = new JLabel("Name"); lastName = new JLabel("Last Name"); ok = new JButton("OK"); cancel = new JButton("Cancel"); nameText = new JTextField(10); lastNameText = new JTextField(20); topPanel = new JPanel(); midPanel = new JPanel(); butomPanel = new JPanel(); // add components to relevant panels topPanel.add(name); topPanel.add(nameText); midPanel.add(lastName); midPanel.add(lastNameText); butomPanel.add(ok); butomPanel.add(cancel); // add panels to the frame add(topPanel); add(midPanel); add(butomPanel); ok.addActionListener(this); cancel.addActionListener(this); } // end constructor public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) System.out.println(nameText.getText()+" "+lastNameText.getText()); if(e.getSource() == cancel) { nameText.setText(""); lastNameText.setText(""); } // end if } // end method actionPerformed } // end class GridFrame0 // Example array of buttons class PanelFrame0 extends JFrame implements ActionListener { private JPanel buttonJPanel; private JButton buttons[]; private JTextField textField; public PanelFrame0() { buttons = new JButton[5]; buttonJPanel = new JPanel(); textField = new JTextField(); buttonJPanel.setLayout(new GridLayout(1,buttons.length)); for(int i = 0;i < buttons.length;i++) { buttons[i] = new JButton("Button"+(i+1)); buttonJPanel.add(buttons[i]); } add(buttonJPanel,BorderLayout.SOUTH); add(textField,BorderLayout.NORTH); for(int i = 0;i < buttons.length;i++) buttons[i].addActionListener(this); } // end constructor public void actionPerformed(ActionEvent e) { String str = ""; textField.setText(""); for(int i = 0;i < buttons.length;i++) { if(e.getSource()==buttons[i]) str += "you clicked "+"Button"+(i+1); textField.setText(str); } // end for } // end method actionPerformed } // end class PanelFrame0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 textarea1 27 29 button 30 31 32 33 34 35 textArea1 36 37 38 39 40 41 42 43 textarea 44 45 46 47 48 // Fig. 11.47: TextAreaFrame.java // Copying selected text from one textarea to another. import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.Box; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JScrollPane; public class TextAreaFrame extends { private JTextArea textArea1; // private JTextArea textArea2; // private JButton copyJButton; // JFrame displays demo string highlighted text is copied here initiates copying of text // no-argument constructor public TextAreaFrame() { super( "TextArea Demo" ); Box box = Box.createHorizontalBox(); // create box String demo = "This is a demo string to\n" + "illustrate copying text\nfrom one textarea to \n" + "another textarea using an\nexternal event\n"; textArea1 = new JTextArea( demo, 10, 15 ); // create box.add( new JScrollPane( textArea1 ) ); // add scrollpane copyJButton = new JButton( "Copy >>>" ); // create copy box.add( copyJButton ); // add copy button to box copyJButton.addActionListener( new ActionListener() // anonymous inner class { // set text in textArea2 to selected text from public void actionPerformed( ActionEvent event ) { textArea2.setText( textArea1.getSelectedText() ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener textArea2 = new JTextArea( 10, 15 ); // create second textArea2.setEditable( false ); // disable editing box.add( new JScrollPane( textArea2 ) ); // add scrollpane add( box ); // add box to frame } // end TextAreaFrame constructor 49 } // end class TextAreaFrame // Example gUIs overall and null layout class EmployeeFrame3 extends JFrame { private JButton ok; private JButton cancel; private private private private private private private private private JLabel name; JLabel lastName; JTextField empName; JTextField empLName; JTextArea status; JPanel leftPanel; JPanel centerPanel; JPanel rightPanel; JPanel typePanels[]; private JLabel commision; private JLabel sales; private JLabel wage; private JLabel hours; private JTextField empCommision; private JTextField empSales; private JTextField empWage; private JTextField empHours; private String types[] = {"Commision","Hourly","Salaried"}; private JComboBox empType; private int selected=0; int i; // couter for loops public void EmployeeFrame3() { setLayout(null); ok = new JButton("OK"); cancel = new JButton("CANCEL"); rightPanel= new JPanel(); rightPanel.setLayout(null); rightPanel.setSize(200,200); rightPanel.setLocation(450,150); ok.setSize(100,50); ok.setLocation(0,0); rightPanel.add(ok); rightPanel.add(cancel); cancel.setSize(100,50); cancel.setLocation(0,100); add(rightPanel); centerPanel= new JPanel(); centerPanel.setSize(250,250); centerPanel.setLocation(200,100); centerPanel.setLayout(new GridLayout(2,2,10,30)); name = new JLabel("Employee Name"); name.setLocation(0,0); name.setSize(80,20); lastName = new JLabel("Employee LastName"); empName = new JTextField(10); empLName = new JTextField(10); centerPanel.add(name); centerPanel.add(empName); centerPanel.add(lastName); centerPanel.add(empLName); add(centerPanel); // define and add status texarea status = new JTextArea(5,30); status.setLocation(50,350); status.setSize(200,100); add(status); // define and add left panel typeEmp = new JLabel("Emp Type:"); empType = new JComboBox(types); leftPanel = new JPanel(); lftPanel.setSize(150,50); eftPanel.setLocation(10,40); eftPanel.setLayout(new GridLayout(1,2,10,10)); eftPanel.add(typeEmp); eftPanel.add(empType); dd(leftPanel); // create and edd typ panels typePanels = new JPanel[3]; for(i=0;i<typePanels.length;i++) {//create arry of panels typePanels[i] = new JPanel(); typePanels[i].setLayout(new GridLayout(0,2,10,10)); typePanels[i].setSize(150,80); typePanels[i].setLocation(10,200); add(typePanels[i]); typePanels[i].setVisible(false); } // end for loop // define and add components for type panels commision = new JLabel("Commision:"); sales = new JLabel("Sales:"); wage = new JLabel("Wage:"); hours = new JLabel("Hours:"); empCommision = new JTextField(10); empHours = new JTextField(10); empWage = new JTextField(10); empSales = new JTextField(10); typePanels[0].add(commision); typePanels[0].add(empCommision); typePanels[0].add(sales); typePanels[0].add(empSales); typePanels[1].add(hours); typePanels[1].add(empHours); typePanels[2].add(wage); typePanels[2].add(empWage); typePanels[0].setVisible(true); // registoring events to components ButtonHandler handler = new ButtonHandler(); ok.addActionListener(handler); cancel.addActionListener(handler); empType.addActionListener(handler); } // end constructor private class ButtonHandler implements ActionListener { int j; double x; public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) { status.setText(""); status.append("\nName :"+empName.getText()); status.append("\nLastName:"+empLName.getText()); status.append("\nType :"+types[selected]); switch(selected) { case 0: x=Double.parseDouble(empCommision.getText()); status.append("\nCom Rate:“ +String.format("%10.2f",x)); x=Double.parseDouble(empSales.getText(); status.append("\nSalary:"+String.format("%10.2f",x)); break; case 1: x=Double.parseDouble(empHours.getText()); status.append("\nHourly Rate:"+String.format("%10.2f",x)); break; case 2: x=Double.parseDouble(empWage.getText()); status.append("\nwage:"+String.format("%10.2f",x)); break; } // end switch } // end if if(e.getSource() == cancel) { empName.setText(""); empLName.setText(""); status.setText(""); empCommision.setText(""); empSales.setText(""); empWage.setText(""); empHours.setText(""); } // end if if(e.getSource() == empType) { selected = empType.getSelectedIndex(); empCommision.setText(""); empSales.setText(""); empWage.setText(""); empHours.setText(""); for(j=0;j< typePanels.length;j++) if(j==selected) typePanels[j].setVisible(true); else typePanels[j].setVisible(false); } // end if getSource } // end method actionPerformed } // end inner class ButtonHandler } // end outer class // Fig. 11.28: MouseTrackerFrame.java // Demonstrating mouse events. import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class MouseTrackerFrame extends JFrame { private JPanel mousePanel; // panel in which mouse events will occur private JLabel statusBar; // label that displays event information // MouseTrackerFrame constructor sets up GUI and // registers mouse event handlers public MouseTrackerFrame() { super( "Demonstrating Mouse Events" ); mousePanel = new JPanel(); // create panel mousePanel.setBackground( Color.WHITE ); // set background color add( mousePanel, BorderLayout.CENTER ); // add panel to JFrame statusBar = new JLabel( "Mouse outside JPanel" ); add( statusBar, BorderLayout.SOUTH ); // add label to JFrame // create and register listener for mouse and mouse motion events MouseHandler handler = new MouseHandler(); mousePanel.addMouseListener( handler ); mousePanel.addMouseMotionListener( handler ); } // end MouseTrackerFrame constructor private class MouseHandler implements MouseListener, MouseMotionListener { // MouseListener event handlers // handle event when mouse released immediately after press public void mouseClicked( MouseEvent event ) { statusBar.setText( String.format( "Clicked at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseClicked // handle event when mouse pressed public void mousePressed( MouseEvent event ) { statusBar.setText( String.format( "Pressed at [%d, %d]", event.getX(), event.getY() ) ); } // end method mousePressed // handle event when mouse released after dragging public void mouseReleased( MouseEvent event ) { statusBar.setText( String.format( "Released at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseReleased // handle event when mouse enters area public void mouseEntered( MouseEvent event ) { statusBar.setText( String.format( "Mouse entered at [%d, %d]", event.getX(), event.getY() ) ); mousePanel.setBackground( Color.GREEN ); } // end method mouseEntered // handle event when mouse exits area public void mouseExited( MouseEvent event ) { statusBar.setText( "Mouse outside JPanel" ); mousePanel.setBackground( Color.WHITE ); } // end method mouseExited // MouseMotionListener event handlers // handle event when user drags mouse with button pressed public void mouseDragged( MouseEvent event ) { statusBar.setText( String.format( "Dragged at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseDragged // handle event when user moves mouse public void mouseMoved( MouseEvent event ) { statusBar.setText( String.format( "Moved at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseMoved } // end inner class MouseHandler } // end class MouseTrackerFrame import import import import import import java.awt.BorderLayout; java.awt.Graphics; java.awt.event.MouseAdapter; java.awt.event.MouseEvent; javax.swing.JFrame; javax.swing.JLabel; public class MouseDetailsFrame extends JFrame { private String details; // String representing private JLabel statusBar; // JLabel that appears at bottom of window // constructor sets title bar String and register mouse listener public MouseDetailsFrame() { super( "Mouse clicks and buttons" ); statusBar = new JLabel( "Click the mouse" ); add( statusBar, BorderLayout.SOUTH ); addMouseListener( new MouseClickHandler() ); // add handler } // end MouseDetailsFrame constructor // inner class to handle mouse events private class MouseClickHandler extends MouseAdapter { // handle mouse click event and determine which button was pressed public void mouseClicked( MouseEvent event ) { int xPos = event.getX(); // get x position of mouse int yPos = event.getY(); // get y position of mouse details = String.format( "Clicked %d time(s)", event.getClickCount() ); if ( event.isMetaDown() ) // right mouse button details += " with right mouse button"; else if ( event.isAltDown() ) // middle mouse button details += " with center mouse button"; else // left mouse button details += " with left mouse button"; statusBar.setText( details ); // display message in statusBar } // end method mouseClicked } // end private inner class MouseClickHandler } // end class MouseDetailsFrame import import import import import java.awt.Color; java.awt.event.KeyListener; java.awt.event.KeyEvent; javax.swing.JFrame; javax.swing.JTextArea; public class KeyDemoFrame extends JFrame implements KeyListener { private String line1 = ""; // first line of textarea private String line2 = ""; // second line of textarea private String line3 = ""; // third line of textarea private JTextArea textArea; // textarea to display output // KeyDemoFrame constructor public KeyDemoFrame() { super( "Demonstrating Keystroke Events" ); textArea = new JTextArea( 10, 15 ); // set up JTextArea textArea.setText( "Press any key on the keyboard..." ); textArea.setEnabled( false ); // disable textarea textArea.setDisabledTextColor( Color.BLACK ); // set text color add( textArea ); // add textarea to JFrame addKeyListener( this ); // allow frame to process key event } // end KeyDemoFrame constructor // handle press of any key public void keyPressed( KeyEvent event ) { line1 = String.format( "Key pressed: %s", event.getKeyText( event.getKeyCode() ) ); // output pressed key setLines2and3( event ); // set output lines two and three } // end method keyPressed // handle release of any key public void keyReleased( KeyEvent event ) { line1 = String.format( "Key released: %s", event.getKeyText( event.getKeyCode() ) ); // output released key setLines2and3( event ); // set output lines two and three } // end method keyReleased // handle press of an action key public void keyTyped( KeyEvent event ) { line1 = String.format( "Key typed: %s", event.getKeyChar() ); setLines2and3( event ); // set output lines two and three } // end method keyTyped // set second and third lines of output private void setLines2and3( KeyEvent event ) { line2 = String.format( "This key is %san action key", ( event.isActionKey() ? "" : "not " ) ); String temp = event.getKeyModifiersText( event.getModifiers() ); line3 = String.format( "Modifier keys pressed: %s", ( temp.equals( "" ) ? "none" : temp ) ); // output modifiers textArea.setText( String.format( "%s\n%s\n%s\n", line1, line2, line3 ) ); // output three lines of text } // end method setLines2and3 } // end class KeyDemoFrame