0% found this document useful (0 votes)
3 views22 pages

Java Gui Grok

The document is a comprehensive guide to mastering Java GUI development using Apache NetBeans, covering topics from basic setup to advanced concepts. It includes detailed instructions on using AWT, Swing, and JavaFX, along with practical examples and projects. The content is structured into sections that address layout managers, event handling, and various GUI components, providing a solid foundation for developers at all levels.

Uploaded by

Abhay Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Java Gui Grok

The document is a comprehensive guide to mastering Java GUI development using Apache NetBeans, covering topics from basic setup to advanced concepts. It includes detailed instructions on using AWT, Swing, and JavaFX, along with practical examples and projects. The content is structured into sections that address layout managers, event handling, and various GUI components, providing a solid foundation for developers at all levels.

Uploaded by

Abhay Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Mastering Java GUI with Apache NetBeans: From

Basics to Advanced

June 2025

Contents
1 Introduction to Java GUI with Apache NetBeans 2
1.1 Setting Up Apache NetBeans . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 AWT vs Swing vs JavaFX . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Java AWT Basics 2


2.1 AWT Layout Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Event Handling in AWT . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 Java Swing Basics 4


3.1 Layout Managers in Swing . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 Event Handling with Listeners . . . . . . . . . . . . . . . . . . . . . . . . 6

4 Intermediate Swing Components 7

5 Tables and Trees 8

6 Graphics and Custom Painting 9

7 Advanced GUI Concepts 10

8 File Handling and GUI Integration 12

9 JavaFX Introduction 13

10 Summary & Best Practices 14

11 Simple GUI Projects 14


11.1 Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
11.2 Todo List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
11.3 Login Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
11.4 Drawing App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
11.5 Notepad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

1
1 Introduction to Java GUI with Apache NetBeans
Graphical User Interface (GUI) programming enables developers to create interactive
applications with visual components like windows, buttons, and text fields. In Java,
GUI development is supported by libraries like AWT, Swing, and JavaFX. **Apache
NetBeans** is an IDE that simplifies GUI development, especially for Swing, with its
GUI Builder (formerly Matisse). This document uses NetBeans to demonstrate GUI
concepts, providing step-by-step instructions for setting up and running projects.

1.1 Setting Up Apache NetBeans


1. Download and install Apache NetBeans from https://netbeans.apache.org/.
2. Ensure JDK (e.g., JDK 17) is installed and configured in NetBeans (Tools > Java
Platforms).
3. Create a new Java project: File > New Project > Java with Ant > Java Application.
4. For Swing GUIs, enable the GUI Builder by adding a JFrame Form (right-click
project > New > JFrame Form).
5. For JavaFX, add JavaFX libraries to the project (right-click project > Properties
> Libraries > Add JavaFX SDK).

1.2 AWT vs Swing vs JavaFX


• AWT (Abstract Window Toolkit): Uses native OS components (heavyweight),
less flexible but fast.
• Swing: Lightweight, platform-independent, with rich components. NetBeans GUI
Builder supports Swing natively.
• JavaFX: Modern framework with CSS styling and multimedia support, suitable
for advanced applications.
NetBeans Tip: Use the GUI Builder for Swing to drag-and-drop components; for
JavaFX, code manually or use Scene Builder (integrated with NetBeans).
Diagram: A Venn diagram showing AWT (native), Swing (lightweight, NetBeans-
supported), and JavaFX (modern), with overlapping event-handling features.

2 Java AWT Basics


AWT, in java.awt, provides core GUI components like Frame, Button, Label, TextField,
Checkbox, and Choice. These are heavyweight, relying on OS rendering.
1 import java.awt .*;
2

3 public class AWTExample {


4 public static void main( String [] args) {
5 Frame frame = new Frame ("AWT Example in NetBeans ");
6 Label label = new Label (" Enter Name:");
7 TextField textField = new TextField (20);

2
8 Button button = new Button (" Submit ");
9 Checkbox checkbox = new Checkbox ("Agree ");
10 Choice choice = new Choice ();
11 choice .add(" Option 1");
12 choice .add(" Option 2");
13

14 frame.add( label );
15 frame.add( textField );
16 frame.add( button );
17 frame.add( checkbox );
18 frame.add( choice );
19 frame. setLayout (new FlowLayout ());
20 frame. setSize (400 , 300);
21 frame. setVisible (true);
22 }
23 }

NetBeans Instructions:
1. Create a new Java class (File > New File > Java > Java Class).
2. Copy the code into the class.
3. Run the project (Run > Run Main Project or F6).

2.1 AWT Layout Managers


AWT supports:
• FlowLayout: Components in a row, wrapping as needed.
• BorderLayout: Five regions (North, South, East, West, Center).
• GridLayout: Grid of equal-sized cells.
1 import java.awt .*;
2

3 public class AWTPanel {


4 public AWTPanel () {
5 Frame frame = new Frame ("AWT Layout Example ");
6 frame. setLayout (new BorderLayout ());
7 frame.add(new Button ("North "), BorderLayout . NORTH );
8 frame.add(new Button ("South "), BorderLayout . SOUTH );
9 frame.add(new Button ("East"), BorderLayout .EAST);
10 frame.add(new Button ("West"), BorderLayout .WEST);
11 frame.add(new Button (" Center "), BorderLayout . CENTER );
12 frame. setSize (400 , 300);
13 frame. setVisible (true);
14 }
15

16 public static void main( String [] args) {


17 new AWTPanel ();
18 }
19 }

3
Diagram: A figure showing FlowLayout (row of buttons), BorderLayout (five labeled
regions), and GridLayout (2x2 button grid).

2.2 Event Handling in AWT


AWT uses listeners (e.g., ActionListener, WindowListener) for user interactions.
1 import java.awt .*;
2 import java.awt.event .*;
3

4 public class AWTEventExample {


5 public AWTEventExample () {
6 Frame frame = new Frame ("AWT Event Handling ");
7 Button button = new Button ("Click Me");
8 Label label = new Label ("No clicks yet");
9

10 button . addActionListener (e -> label . setText (" Button


Clicked !"));
11 frame. addWindowListener (new WindowAdapter () {
12 public void windowClosing ( WindowEvent e) {
13 System .exit (0);
14 }
15 });
16

17 frame.add(button , BorderLayout . CENTER );


18 frame.add(label , BorderLayout . SOUTH );
19 frame. setSize (300 , 200);
20 frame. setVisible (true);
21 }
22

23 public static void main( String [] args) {


24 new AWTEventExample ();
25 }
26 }

NetBeans Instructions: Create a new Java class, paste the code, and run. Use the
debugger (Debug > Debug Project) to inspect event flow.

3 Java Swing Basics


Swing, in javax.swing, is lightweight and platform-independent, using the Model-View-
Controller (MVC) architecture:
• Model: Manages data (e.g., text in JTextField).
• View: Renders the component.
• Controller: Processes user input.
NetBeans GUI Builder simplifies Swing development with drag-and-drop design.

4
Key components: JFrame, JPanel, JLabel, JButton, JTextField, JCheckBox, JRadioButton,
JComboBox.
1 // Generated by NetBeans GUI Builder, modified for clarity
2 import javax. swing .*;
3 import java.awt .*;
4

5 public class SwingExample extends JFrame {


6 public SwingExample () {
7 setTitle ("Swing Example in NetBeans ");
8 setLayout (new FlowLayout ());
9 JLabel label = new JLabel ("Name:");
10 JTextField textField = new JTextField (15);
11 JButton button = new JButton (" Submit ");
12 JCheckBox checkBox = new JCheckBox (" Subscribe ");
13 JComboBox <String > comboBox = new JComboBox <>( new
String []{" Option 1", " Option 2"});
14

15 add( label );
16 add( textField );
17 add( button );
18 add( checkBox );
19 add( comboBox );
20 setSize (400 , 300);
21 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
22 }
23

24 public static void main( String [] args) {


25 SwingUtilities . invokeLater (() -> new
SwingExample (). setVisible (true));
26 }
27 }

NetBeans Instructions:
1. Create a JFrame Form (File > New File > Swing GUI Forms > JFrame Form).
2. Use the GUI Builder to drag-and-drop components (e.g., JLabel, JTextField).
3. Modify the generated code in the initComponents() method or add logic manually.
4. Run the form (right-click form > Run File).

3.1 Layout Managers in Swing


Swing supports FlowLayout, BorderLayout, GridLayout, and BoxLayout (vertical or
horizontal arrangement).
1 import javax. swing .*;
2 import java.awt .*;
3

4 public class SwingLayoutExample extends JFrame {


5 public SwingLayoutExample () {

5
6 setTitle (" BoxLayout Example ");
7 JPanel panel = new JPanel ();
8 panel. setLayout (new BoxLayout (panel , BoxLayout . Y_AXIS ));
9 panel.add(new JButton (" Button 1"));
10 panel.add(new JButton (" Button 2"));
11 panel.add(new JButton (" Button 3"));
12 add(panel);
13 setSize (300 , 200);
14 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
15 }
16

17 public static void main( String [] args) {


18 SwingUtilities . invokeLater (() -> new
SwingLayoutExample (). setVisible (true));
19 }
20 }

Diagram: A figure comparing FlowLayout, BorderLayout, GridLayout, and BoxLayout


with sample component arrangements.

3.2 Event Handling with Listeners


Swing uses listeners like ActionListener, ItemListener, and KeyListener.
1 import javax. swing .*;
2 import java.awt.event .*;
3

4 public class SwingEventExample extends JFrame {


5 public SwingEventExample () {
6 setTitle ("Swing Event Handling ");
7 JButton button = new JButton ("Click Me");
8 JTextField textField = new JTextField (15);
9

10 button . addActionListener (e ->


JOptionPane . showMessageDialog (this , " Button Clicked !"));
11 textField . addKeyListener (new KeyAdapter () {
12 public void keyPressed ( KeyEvent e) {
13 if (e. getKeyCode () == KeyEvent . VK_ENTER ) {
14 JOptionPane . showMessageDialog ( SwingEventExample .this ,
textField . getText ());
15 }
16 }
17 });
18

19 setLayout (new FlowLayout ());


20 add( button );
21 add( textField );
22 setSize (300 , 200);
23 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
24 }
25

6
26 public static void main( String [] args) {
27 SwingUtilities . invokeLater (() -> new
SwingEventExample (). setVisible (true));
28 }
29 }

NetBeans Instructions: In the GUI Builder, right-click components, select ”Events”


to add listeners, and implement logic in the generated methods.

4 Intermediate Swing Components


Intermediate components include:
• JTextArea: Multi-line text.
• JPasswordField: Secure text input.
• JSlider, JSpinner: Value selection.
• JTabbedPane, JSplitPane: Multi-panel interfaces.
• JMenuBar, JMenu, JMenuItem: Menus.
• JOptionPane, JDialog: Dialogs.
1 import javax. swing .*;
2 import java.awt .*;
3

4 public class IntermediateSwingExample extends JFrame {


5 public IntermediateSwingExample () {
6 setTitle (" Intermediate Components ");
7 JTabbedPane tabbedPane = new JTabbedPane ();
8 JPanel panel1 = new JPanel ();
9 JTextArea textArea = new JTextArea (5, 20);
10 JSlider slider = new JSlider (0, 100 , 50);
11 panel1 .add(new JScrollPane ( textArea ));
12 panel1 .add( slider );
13 tabbedPane . addTab ("Tab 1", panel1 );
14

15 JMenuBar menuBar = new JMenuBar ();


16 JMenu fileMenu = new JMenu ("File");
17 JMenuItem exitItem = new JMenuItem ("Exit");
18 exitItem . addActionListener (e -> System .exit (0));
19 fileMenu .add( exitItem );
20 menuBar .add( fileMenu );
21 setJMenuBar ( menuBar );
22

23 add( tabbedPane );
24 setSize (500 , 400);
25 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
26 }
27

28 public static void main( String [] args) {

7
29 SwingUtilities . invokeLater (() -> new
IntermediateSwingExample (). setVisible (true));
30 }
31 }

NetBeans Instructions: Use the GUI Builder to add JTabbedPane and JMenuBar from
the Palette. Configure properties (e.g., tab titles) in the Properties window.
Diagram: A figure showing a JTabbedPane with two tabs and a JMenuBar with a ”File”
menu.

5 Tables and Trees


JTable displays tabular data, supporting editing and rendering.
1 import javax. swing .*;
2 import javax. swing .table . DefaultTableModel ;
3

4 public class TableExample extends JFrame {


5 public TableExample () {
6 setTitle (" JTable Example ");
7 String [] columns = {"ID", "Name", "Age"};
8 Object [][] data = {{1 , "John", 25} , {2, "Jane", 30}};
9 DefaultTableModel model = new DefaultTableModel (data ,
columns );
10 JTable table = new JTable ( model );
11 add(new JScrollPane ( table ));
12 setSize (500 , 300);
13 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
14 }
15

16 public static void main( String [] args) {


17 SwingUtilities . invokeLater (() -> new
TableExample (). setVisible (true));
18 }
19 }

JTree displays hierarchical data.


1 import javax. swing .*;
2 import javax. swing .tree. DefaultMutableTreeNode ;
3

4 public class TreeExample extends JFrame {


5 public TreeExample () {
6 setTitle ("JTree Example ");
7 DefaultMutableTreeNode root = new
DefaultMutableTreeNode ("Root");
8 DefaultMutableTreeNode child1 = new
DefaultMutableTreeNode (" Folder 1");
9 child1 .add(new DefaultMutableTreeNode ("File 1"));
10 root.add( child1 );

8
11 root.add(new DefaultMutableTreeNode (" Folder 2"));
12 JTree tree = new JTree (root);
13 add(new JScrollPane (tree));
14 setSize (300 , 400);
15 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
16 }
17

18 public static void main( String [] args) {


19 SwingUtilities . invokeLater (() -> new
TreeExample (). setVisible (true));
20 }
21 }

NetBeans Instructions: Add JTable or JTree via GUI Builder, then customize the
model in code.
Diagram: A figure with a JTable (2x3 grid) and a JTree (root with two folders, one
with a file).

6 Graphics and Custom Painting


Custom graphics use paintComponent() with Graphics2D.
1 import javax. swing .*;
2 import java.awt .*;
3 import java.awt.event .*;
4

5 public class GraphicsExample extends JPanel {


6 private int x = 50, y = 50;
7

8 public GraphicsExample () {
9 addMouseListener (new MouseAdapter () {
10 public void mouseClicked ( MouseEvent e) {
11 x = e.getX ();
12 y = e.getY ();
13 repaint ();
14 }
15 });
16 }
17

18 @Override
19 protected void paintComponent ( Graphics g) {
20 super . paintComponent (g);
21 Graphics2D g2d = ( Graphics2D ) g;
22 g2d. setColor ( Color .BLUE);
23 g2d. fillOval (x - 25, y - 25, 50, 50);
24 g2d. setColor ( Color .RED);
25 g2d. drawRect (100 , 100 , 100 , 100);
26 }
27

28 public static void main( String [] args) {

9
29 SwingUtilities . invokeLater (() -> {
30 JFrame frame = new JFrame (" Graphics Example ");
31 frame.add(new GraphicsExample ());
32 frame. setSize (400 , 400);
33 frame. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
34 frame. setVisible (true);
35 });
36 }
37 }

NetBeans Instructions: Create a JPanel Form, override paintComponent in the source


code.
Diagram: A figure showing a blue circle (movable by mouse) and a red rectangle.

7 Advanced GUI Concepts


SwingWorker handles background tasks.
1 import javax. swing .*;
2 import java.util.List;
3

4 public class SwingWorkerExample extends JFrame {


5 public SwingWorkerExample () {
6 setTitle (" SwingWorker Example ");
7 JLabel label = new JLabel (" Ready ");
8 JButton start = new JButton (" Start Task");
9 start. addActionListener (e -> {
10 SwingWorker <Void , String > worker = new SwingWorker < >() {
11 @Override
12 protected Void doInBackground () throws Exception {
13 for (int i = 1; i <= 5; i++) {
14 Thread . sleep (1000) ;
15 publish (" Processing step " + i);
16 }
17 return null;
18 }
19 @Override
20 protected void process (List <String > chunks ) {
21 label . setText ( chunks .get( chunks .size () - 1));
22 }
23 @Override
24 protected void done () {
25 label . setText ("Task Complete !");
26 }
27 };
28 worker . execute ();
29 });
30 setLayout (new FlowLayout ());
31 add(start);
32 add( label );

10
33 setSize (300 , 200);
34 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
35 }
36

37 public static void main( String [] args) {


38 SwingUtilities . invokeLater (() -> new
SwingWorkerExample (). setVisible (true));
39 }
40 }

Timer creates animations.


1 import javax. swing .*;
2 import java.awt .*;
3 import java.awt.event .*;
4

5 public class AnimationExample extends JPanel {


6 private int x = 0;
7

8 public AnimationExample () {
9 Timer timer = new Timer (50 , e -> {
10 x += 5;
11 if (x > getWidth ()) x = 0;
12 repaint ();
13 });
14 timer. start ();
15 }
16

17 @Override
18 protected void paintComponent ( Graphics g) {
19 super . paintComponent (g);
20 g. setColor ( Color . GREEN );
21 g. fillRect (x, 50, 50, 50);
22 }
23

24 public static void main( String [] args) {


25 SwingUtilities . invokeLater (() -> {
26 JFrame frame = new JFrame (" Animation Example ");
27 frame.add(new AnimationExample ());
28 frame. setSize (400 , 200);
29 frame. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
30 frame. setVisible (true);
31 });
32 }
33 }

Customize appearance with UIManager.


1 import javax. swing .*;
2

3 public class LookAndFeelExample extends JFrame {


4 public LookAndFeelExample () {

11
5 try {
6 UIManager . setLookAndFeel ("javax .swing .plaf. nimbus . NimbusLookAndFeel "
7 } catch ( Exception e) {
8 e. printStackTrace ();
9 }
10 setTitle ("Look and Feel Example ");
11 add(new JButton (" Styled Button "));
12 setSize (300 , 200);
13 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
14 }
15

16 public static void main( String [] args) {


17 SwingUtilities . invokeLater (() -> new
LookAndFeelExample (). setVisible (true));
18 }
19 }

NetBeans Instructions: Use the GUI Builder for layout, add SwingWorker or Timer
in the source code.

8 File Handling and GUI Integration


JFileChooser integrates file I/O with GUIs.
1 import javax. swing .*;
2 import java.awt .*;
3 import java.io .*;
4

5 public class FileChooserExample extends JFrame {


6 public FileChooserExample () {
7 setTitle ("File Handling ");
8 JTextArea textArea = new JTextArea (10 , 30);
9 JButton openButton = new JButton ("Open File");
10 JButton saveButton = new JButton ("Save File");
11

12 openButton . addActionListener (e -> {


13 JFileChooser chooser = new JFileChooser ();
14 if ( chooser . showOpenDialog (this) ==
JFileChooser . APPROVE_OPTION ) {
15 try ( BufferedReader reader = new BufferedReader (new
FileReader ( chooser . getSelectedFile ()))) {
16 textArea .read(reader , null);
17 } catch ( IOException ex) {
18 JOptionPane . showMessageDialog (this , "Error
reading file");
19 }
20 }
21 });
22

23 saveButton . addActionListener (e -> {


24 JFileChooser chooser = new JFileChooser ();

12
25 if ( chooser . showSaveDialog (this) ==
JFileChooser . APPROVE_OPTION ) {
26 try ( BufferedWriter writer = new BufferedWriter (new
FileWriter ( chooser . getSelectedFile ()))) {
27 textArea . write ( writer );
28 } catch ( IOException ex) {
29 JOptionPane . showMessageDialog (this , "Error
saving file");
30 }
31 }
32 });
33

34 setLayout (new BorderLayout ());


35 add(new JScrollPane ( textArea ), BorderLayout . CENTER );
36 JPanel buttonPanel = new JPanel ();
37 buttonPanel .add( openButton );
38 buttonPanel .add( saveButton );
39 add( buttonPanel , BorderLayout . SOUTH );
40 setSize (500 , 400);
41 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
42 }
43

44 public static void main( String [] args) {


45 SwingUtilities . invokeLater (() -> new
FileChooserExample (). setVisible (true));
46 }
47 }

NetBeans Instructions: Add JFileChooser via GUI Builder, implement I/O logic in
the source.

9 JavaFX Introduction
JavaFX uses a scene graph, supporting CSS and FXML. NetBeans integrates with Scene
Builder for visual design.
1 import javafx . application . Application ;
2 import javafx .scene. Scene ;
3 import javafx .scene. control . Button ;
4 import javafx .scene. control . TextField ;
5 import javafx .scene. layout .VBox;
6 import javafx .stage. Stage ;
7

8 public class JavaFXExample extends Application {


9 @Override
10 public void start ( Stage stage ) {
11 TextField textField = new TextField (" Enter text");
12 Button button = new Button (" Submit ");
13 button . setOnAction (e -> System .out. println ("Text: " +
textField . getText ()));
14 VBox vbox = new VBox (10 , textField , button );

13
15 Scene scene = new Scene (vbox , 300 , 200);
16 stage. setTitle (" JavaFX Example ");
17 stage. setScene ( scene );
18 stage.show ();
19 }
20

21 public static void main( String [] args) {


22 launch (args);
23 }
24 }

NetBeans Instructions:
1. Create a JavaFX project (File > New Project > JavaFX > JavaFX Application).
2. Add JavaFX SDK to libraries.
3. Optionally, use Scene Builder to design the layout, then load the FXML in code.
Diagram: A figure showing VBox, HBox, BorderPane, and GridPane layouts.

10 Summary & Best Practices


Use SwingUtilities.invokeLater for GUI updates.
Create custom JPanel classes.
Avoid:
• Non-EDT GUI updates.
• null layouts.
• Hardcoding sizes.
NetBeans Tip: Use the GUI Builder for rapid prototyping, but understand the gener-
ated code for customization.

11 Simple GUI Projects


11.1 Calculator
Pseudocode:
CREATE window with title "Calculator"
ADD display text field at top
CREATE 4x4 grid of buttons (0-9, ., +, -, *, /, =)
INITIALIZE result = 0, lastCommand = "=", start = true
FOR each button click:
IF button is a digit or .:
IF start is true:
SET display to button text
SET start to false

14
ELSE:
APPEND button text to display
ELSE (operator or =):
IF not start:
CALCULATE result using lastCommand and display value
SET start to true
SET lastCommand to button text
IF button is =:
DISPLAY result
CALCULATE function:
PARSE display value to number
APPLY lastCommand (+, -, *, /) to result and number
UPDATE display with result
1 import javax. swing .*;
2 import java.awt .*;
3 import java.awt.event .*;
4

5 public class Calculator extends JFrame {


6 private JTextField display ;
7 private double result = 0;
8 private String lastCommand = "=";
9 private boolean start = true;
10

11 public Calculator () {
12 setTitle (" Calculator ");
13 display = new JTextField ("0");
14 display . setEditable (false );
15 add(display , BorderLayout . NORTH );
16

17 JPanel panel = new JPanel (new GridLayout (4, 4, 5, 5));


18 String [] buttons = {"7", "8", "9", "/", "4", "5", "6", "*",
"1", "2", "3", "-", "0", ".", "=", "+"};
19 for ( String text : buttons ) {
20 JButton button = new JButton (text);
21 button . addActionListener (this :: handleButton );
22 panel.add( button );
23 }
24

25 add(panel);
26 setSize (300 , 400);
27 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
28 }
29

30 private void handleButton ( ActionEvent e) {


31 String input = e. getActionCommand ();
32 if (input. matches ("[0 -9.]")) {
33 if (start ) {
34 display . setText ( input );
35 start = false ;
36 } else {

15
37 display . setText ( display . getText () + input );
38 }
39 } else {
40 if (! start ) {
41 calculate ( Double . parseDouble ( display . getText ()));
42 start = true;
43 }
44 lastCommand = input ;
45 if (input . equals ("=")) {
46 display . setText ("" + result );
47 }
48 }
49 }
50

51 private void calculate ( double x) {


52 switch ( lastCommand ) {
53 case "+": result += x; break ;
54 case "-": result -= x; break ;
55 case "*": result *= x; break ;
56 case "/": result /= x; break ;
57 case "=": result = x; break ;
58 }
59 display . setText ("" + result );
60 }
61

62 public static void main( String [] args) {


63 SwingUtilities . invokeLater (() -> new
Calculator (). setVisible (true));
64 }
65 }

NetBeans Instructions: Create a JFrame Form, use GUI Builder to add JTextField
and JButtons in a GridLayout, implement logic in the source.
Diagram: A figure showing a display at the top and a 4x4 button grid.

11.2 Todo List


Pseudocode:
CREATE window with title "Todo List"
ADD text field at top
ADD scrollable list in center
ADD buttons "Add Task" and "Remove Selected" at bottom
INITIALIZE list model
ON "Add Task" click:
GET text from text field
IF text is not empty:
ADD text to list model
CLEAR text field
ON "Remove Selected" click:

16
GET selected list item
IF item is selected:
REMOVE item from list model
1 import javax. swing .*;
2 import java.awt .*;
3 import java.awt.event .*;
4

5 public class TodoList extends JFrame {


6 private DefaultListModel <String > listModel ;
7

8 public TodoList () {
9 setTitle ("Todo List");
10 listModel = new DefaultListModel < >();
11 JList <String > taskList = new JList <>( listModel );
12 JTextField input = new JTextField (20);
13 JButton addButton = new JButton ("Add Task");
14 JButton removeButton = new JButton (" Remove Selected ");
15

16 addButton . addActionListener (e -> {


17 String task = input . getText ().trim ();
18 if (! task. isEmpty ()) {
19 listModel . addElement (task);
20 input . setText ("");
21 }
22 });
23

24 removeButton . addActionListener (e -> {


25 int selected = taskList . getSelectedIndex ();
26 if ( selected != -1) {
27 listModel . remove ( selected );
28 }
29 });
30

31 setLayout (new BorderLayout ());


32 add(input , BorderLayout . NORTH );
33 add(new JScrollPane ( taskList ), BorderLayout . CENTER );
34 JPanel buttonPanel = new JPanel ();
35 buttonPanel .add( addButton );
36 buttonPanel .add( removeButton );
37 add( buttonPanel , BorderLayout . SOUTH );
38 setSize (400 , 300);
39 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
40 }
41

42 public static void main( String [] args) {


43 SwingUtilities . invokeLater (() -> new
TodoList (). setVisible (true));
44 }
45 }

17
NetBeans Instructions: Use GUI Builder to add JTextField, JList, and JButtons,
configure BorderLayout.
Diagram: A figure with a text field (top), task list (center), and two buttons (bottom).

11.3 Login Form


Pseudocode:
CREATE window with title "Login Form"
ADD labels and fields for username and password
ADD "Login" button
ON "Login" click:
GET username and password
IF username is "admin" and password is "password":
SHOW "Login Successful" message
ELSE:
SHOW "Invalid Credentials" message
1 import javax. swing .*;
2 import java.awt .*;
3 import java.awt.event .*;
4

5 public class LoginForm extends JFrame {


6 public LoginForm () {
7 setTitle ("Login Form");
8 JLabel userLabel = new JLabel (" Username :");
9 JLabel passLabel = new JLabel (" Password :");
10 JTextField userField = new JTextField (15);
11 JPasswordField passField = new JPasswordField (15);
12 JButton loginButton = new JButton (" Login ");
13

14 loginButton . addActionListener (e -> {


15 String username = userField . getText ();
16 String password = new String ( passField . getPassword ());
17 if ( username . equals (" admin ") &&
password . equals (" password ")) {
18 JOptionPane . showMessageDialog (this , "Login
Successful !");
19 } else {
20 JOptionPane . showMessageDialog (this , " Invalid
Credentials !");
21 }
22 });
23

24 JPanel panel = new JPanel (new GridLayout (3, 2, 10, 10));


25 panel.add( userLabel );
26 panel.add( userField );
27 panel.add( passLabel );
28 panel.add( passField );
29 panel.add(new JLabel ());
30 panel.add( loginButton );

18
31

32 add(panel);
33 setSize (300 , 150);
34 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
35 }
36

37 public static void main( String [] args) {


38 SwingUtilities . invokeLater (() -> new
LoginForm (). setVisible (true));
39 }
40 }

NetBeans Instructions: Create a JFrame Form, use GUI Builder to add components
in a GridLayout.
Diagram: A figure showing a 3x2 grid with username/password fields and a login button.

11.4 Drawing App


Pseudocode:
CREATE window with title "Drawing App"
ADD canvas panel
INITIALIZE list to store line points
ON mouse press:
STORE start point
ON mouse drag:
ADD start and current points to list
UPDATE start point to current
REDRAW canvas
ON redraw:
FOR each pair of points in list:
DRAW line between points
1 import javax. swing .*;
2 import java.awt .*;
3 import java.awt.event .*;
4 import java.util. ArrayList ;
5

6 public class DrawingApp extends JPanel {


7 private ArrayList <Point > points = new ArrayList < >();
8 private Point startPoint ;
9

10 public DrawingApp () {
11 addMouseListener (new MouseAdapter () {
12 public void mousePressed ( MouseEvent e) {
13 startPoint = e. getPoint ();
14 }
15 });
16 addMouseMotionListener (new MouseMotionAdapter () {
17 public void mouseDragged ( MouseEvent e) {

19
18 points .add( startPoint );
19 points .add(e. getPoint ());
20 startPoint = e. getPoint ();
21 repaint ();
22 }
23 });
24 }
25

26 @Override
27 protected void paintComponent ( Graphics g) {
28 super . paintComponent (g);
29 g. setColor ( Color . BLACK );
30 for (int i = 0; i < points .size () - 1; i += 2) {
31 Point p1 = points .get(i);
32 Point p2 = points .get(i + 1);
33 g. drawLine (p1.x, p1.y, p2.x, p2.y);
34 }
35 }
36

37 public static void main( String [] args) {


38 SwingUtilities . invokeLater (() -> {
39 JFrame frame = new JFrame (" Drawing App");
40 frame.add(new DrawingApp ());
41 frame. setSize (500 , 400);
42 frame. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
43 frame. setVisible (true);
44 });
45 }
46 }

NetBeans Instructions: Create a JPanel Form, override paintComponent, add mouse


listeners in the source.
Diagram: A figure showing a canvas with sample drawn lines.

11.5 Notepad
Pseudocode:
CREATE window with title "Notepad"
ADD menu bar with "File" menu ("Open", "Save")
ADD scrollable text area
ON "Open" click:
SHOW file chooser dialog
IF file selected:
READ file content into text area
HANDLE errors
ON "Save" click:
SHOW save dialog
IF file selected:
WRITE text area content to file

20
HANDLE errors
1 import javax. swing .*;
2 import java.awt .*;
3 import java.io .*;
4

5 public class Notepad extends JFrame {


6 public Notepad () {
7 setTitle (" Notepad ");
8 JTextArea textArea = new JTextArea (20 , 40);
9 JMenuBar menuBar = new JMenuBar ();
10 JMenu fileMenu = new JMenu ("File");
11 JMenuItem openItem = new JMenuItem ("Open");
12 JMenuItem saveItem = new JMenuItem ("Save");
13

14 openItem . addActionListener (e -> {


15 JFileChooser chooser = new JFileChooser ();
16 if ( chooser . showOpenDialog (this) ==
JFileChooser . APPROVE_OPTION ) {
17 try ( BufferedReader reader = new BufferedReader (new
FileReader ( chooser . getSelectedFile ()))) {
18 textArea .read(reader , null);
19 } catch ( IOException ex) {
20 JOptionPane . showMessageDialog (this , "Error
opening file");
21 }
22 }
23 });
24

25 saveItem . addActionListener (e -> {


26 JFileChooser chooser = new JFileChooser ();
27 if ( chooser . showSaveDialog (this) ==
JFileChooser . APPROVE_OPTION ) {
28 try ( BufferedWriter writer = new BufferedWriter (new
FileWriter ( chooser . getSelectedFile ()))) {
29 textArea . write ( writer );
30 } catch ( IOException ex) {
31 JOptionPane . showMessageDialog (this , "Error
saving file");
32 }
33 }
34 });
35

36 fileMenu .add( openItem );


37 fileMenu .add( saveItem );
38 menuBar .add( fileMenu );
39 setJMenuBar ( menuBar );
40 add(new JScrollPane ( textArea ));
41 setSize (600 , 400);
42 setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
43 }
44

21
45 public static void main( String [] args) {
46 SwingUtilities . invokeLater (() -> new
Notepad (). setVisible (true));
47 }
48 }

NetBeans Instructions: Create a JFrame Form, add JMenuBar and JTextArea via
GUI Builder, implement file I/O in the source.
Diagram: A figure showing a text area with a ”File” menu containing ”Open” and
”Save”.

22

You might also like