0% found this document useful (0 votes)
13 views19 pages

Advanced Java AWT Programming Examples

Uploaded by

vidyamohite2607
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)
13 views19 pages

Advanced Java AWT Programming Examples

Uploaded by

vidyamohite2607
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

Advance Java Seminar

Programs

1. Program to create frame in AWT


import [Link];

public class SimpleFrameExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("Simple Frame Example");

// Set the size of the frame


[Link](300, 200);

// Make the frame visible


[Link](true);
}
}

2. Adding controls to frame


import [Link].*;
import [Link].*;

public class BasicControlsDemo {


// Declare AWT components
private Frame frame;
private Label label;
private Button button;
private TextField textField;
private TextArea textArea;
private Checkbox checkbox;
private List list;

// Constructor to initialize components


public BasicControlsDemo() {
frame = new Frame("Basic Controls Demo");
label = new Label("Label");
button = new Button("Click Me");
textField = new TextField();
textArea = new TextArea();
checkbox = new Checkbox("Check Me");
list = new List();

// Set layout manager for the frame


[Link](new FlowLayout());

// Add components to the frame


[Link](label);
[Link](button);
[Link](textField);
[Link](textArea);
[Link](checkbox);
[Link](list);

// Set action listener for the button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});

// Set window closing listener


[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Set frame properties


[Link](400, 300);
[Link](true);
}

public static void main(String[] args) {


new BasicControlsDemo();
}
}

3. creating simple applet


import [Link];
import [Link];

public class HelloWorldApplet extends Applet {

public void paint(Graphics g) {


[Link]("Hello, World!", 20, 20);
}
}

Html added

<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="[Link]" width="300" height="200">
</applet>
</body>
</html>

4. adding controls to applet


import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class LabelButtonApplet extends Applet implements ActionListener {

private Label label;


private Button button;

public void init() {


label = new Label("Click the button!");
button = new Button("Click Me");

// Add action listener to the button


[Link](this);

// Add components to the applet


add(label);
add(button);
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == button) {
[Link]("Button Clicked!");
}
}
}

5. flow layout
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FlowLayoutExample {

public static void main(String[] args) {


Frame frame = new Frame("FlowLayout Example");

// Create components
Label label = new Label("Label");
Button button = new Button("Button");

// Set layout manager for the frame


[Link](new FlowLayout());

// Add components to the frame


[Link](label);
[Link](button);

// Set window closing listener


[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Set frame properties


[Link](300, 150);
[Link](true);
}
}

6. Border layout
import [Link];
import [Link];
import [Link];

public class BorderLayoutExample {

public static void main(String[] args) {


Frame frame = new Frame("BorderLayout Example");

// Create buttons
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
Button button5 = new Button("Button 5");

// Add buttons to the frame with BorderLayout


[Link](button1, [Link]);
[Link](button2, [Link]);
[Link](button3, [Link]);
[Link](button4, [Link]);
[Link](button5, [Link]);

// Set frame properties


[Link](300, 200);
[Link](true);
}
}

7. Grid layout
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ButtonGridLayoutExample {


private Frame frame;

public ButtonGridLayoutExample() {
frame = new Frame("Button Grid Layout Example");

// Create buttons
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
Button button5 = new Button("Button 5");

// Create GridLayout with 2 rows and 3 columns


GridLayout gridLayout = new GridLayout(2, 3);

// Set GridLayout for the frame


[Link](gridLayout);

// Add buttons to the frame


[Link](button1);
[Link](button2);
[Link](button3);
[Link](button4);
[Link](button5);

// Set window closing listener


[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
// Set frame properties
[Link](300, 200);
[Link](true);
}

public static void main(String[] args) {


new ButtonGridLayoutExample();
}
}

8. Grid bag layout


import [Link];
import [Link];
import [Link];
import [Link];

public class GridBagLayoutExample {

public static void main(String[] args) {


JFrame frame = new JFrame("GridBagLayout Example");

// Create a GridBagLayout manager


GridBagLayout layout = new GridBagLayout();
[Link](layout);

// Create buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");

// Create GridBagConstraints to control the layout


GridBagConstraints gbc = new GridBagConstraints();

// Set constraints for button1


[Link] = 0;
[Link] = 0;
[Link](button1, gbc);

// Set constraints for button2


[Link] = 1;
[Link] = 0;
[Link](button2, gbc);

// Set constraints for button3


[Link] = 2;
[Link] = 0;
[Link](button3, gbc);

// Set constraints for button4


[Link] = 0;
[Link] = 1;
[Link](button4, gbc);

// Set constraints for button5


[Link] = 1;
[Link] = 1;
[Link](button5, gbc);

// Set frame properties


[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

9. Card layout
import [Link].*;
import [Link];
import [Link];

public class CardLayoutExample extends Frame implements ActionListener {

private CardLayout cardLayout;


private Panel cardPanel;

public CardLayoutExample() {
cardLayout = new CardLayout();
cardPanel = new Panel();

setLayout(new BorderLayout());
[Link](cardLayout);

// Create buttons for different "cards"


Button card1Button = new Button("Card 1");
Button card2Button = new Button("Card 2");
Button card3Button = new Button("Card 3");

// Add action listeners to the buttons


[Link](this);
[Link](this);
[Link](this);

// Add buttons to the card panel


[Link](card1Button, "Card 1");
[Link](card2Button, "Card 2");
[Link](card3Button, "Card 3");

// Add the card panel to the frame


add(cardPanel, [Link]);

// Set the frame properties


setTitle("Card Layout Example");
setSize(300, 200);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


[Link](cardPanel);
}

public static void main(String[] args) {


new CardLayoutExample();
}
}

10. Menu bar


import [Link].*;
import [Link].*;

public class MenuBarExample extends Frame {

public MenuBarExample() {
// Create a MenuBar
MenuBar menuBar = new MenuBar();

// Create Menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu helpMenu = new Menu("Help");

// Create MenuItems
MenuItem newMenuItem = new MenuItem("New");
MenuItem openMenuItem = new MenuItem("Open");
MenuItem saveMenuItem = new MenuItem("Save");
MenuItem exitMenuItem = new MenuItem("Exit");

MenuItem cutMenuItem = new MenuItem("Cut");


MenuItem copyMenuItem = new MenuItem("Copy");
MenuItem pasteMenuItem = new MenuItem("Paste");

MenuItem aboutMenuItem = new MenuItem("About");

// Add MenuItems to Menus


[Link](newMenuItem);
[Link](openMenuItem);
[Link](saveMenuItem);
[Link]();
[Link](exitMenuItem);

[Link](cutMenuItem);
[Link](copyMenuItem);
[Link](pasteMenuItem);

[Link](aboutMenuItem);

// Add Menus to MenuBar


[Link](fileMenu);
[Link](editMenu);
[Link](helpMenu);

// Set MenuBar for the frame


setMenuBar(menuBar);

// Set window closing listener


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Set frame properties


setTitle("Menu Bar Example");
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new MenuBarExample();
}
}

11. File dialog


import [Link].*;
import [Link].*;

public class FileDialogExample extends Frame {

public FileDialogExample() {
setTitle("File Dialog Example");

// Create a FileDialog with the specified title and mode


FileDialog fileDialog = new FileDialog(this, "Open File", [Link]);
// Create a button to trigger the FileDialog
Button openButton = new Button("Open File");

// Add an action listener to the button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Display the FileDialog when the button is clicked
[Link](true);

// Get the selected file and display its path


String directory = [Link]();
String file = [Link]();
if (file != null) {
[Link]("Selected File: " + directory + file);
}
}
});

// Set layout manager for the frame


setLayout(new FlowLayout());

// Add components to the frame


add(openButton);

// Set window closing listener


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Set frame properties


setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new FileDialogExample();
}
}

12. Image Icon class


import [Link].*;
import [Link].*;

public class ImageIconExample {

public ImageIconExample() {
// Create a JFrame
JFrame frame = new JFrame("ImageIcon Example");

// Create an ImageIcon with the specified image file path


ImageIcon icon = new ImageIcon("path/to/your/[Link]");

// Create a JLabel with the ImageIcon


JLabel label = new JLabel(icon);

// Set layout manager for the frame


[Link](new FlowLayout());

// Add the label to the frame


[Link](label);

// Set default close operation


[Link](JFrame.EXIT_ON_CLOSE);

// Set frame properties


[Link](300, 200);
[Link](true);
}

public static void main(String[] args) {


// Ensure to replace "path/to/your/[Link]" with the actual path to your image
file
new ImageIconExample();
}
}

13. Tabbed panes


import [Link].*;
import [Link].*;

public class TabbedPaneExample extends JFrame {

public TabbedPaneExample() {
setTitle("TabbedPane Example");

// Create a JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane();

// Create panels for each tab


JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();

// Add components to the panels


[Link](new JLabel("Content for Tab 1"));
[Link](new JLabel("Content for Tab 2"));
[Link](new JLabel("Content for Tab 3"));

// Add tabs to the tabbedPane


[Link]("Tab 1", panel1);
[Link]("Tab 2", panel2);
[Link]("Tab 3", panel3);

// Set layout manager for the frame


setLayout(new BorderLayout());

// Add the tabbedPane to the frame


add(tabbedPane, [Link]);

// Set default close operation


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Set frame properties


setSize(400, 300);
setLocationRelativeTo(null); // Center the frame
setVisible(true);
}

public static void main(String[] args) {


[Link](() -> new TabbedPaneExample());
}
}

14. trees
import [Link].*;
import [Link];

public class SwingTreeExample {


public static void main(String[] args) {
{
JFrame frame = new JFrame("Swing Tree Example");
[Link](JFrame.EXIT_ON_CLOSE);

// Create a root node


DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");

// Create child nodes


DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Node 1");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Node 2");

// Add child nodes to the root node


[Link](node1);
[Link](node2);

// Create the tree with the root node


JTree tree = new JTree(rootNode);

// Create a scroll pane to hold the tree


JScrollPane scrollPane = new JScrollPane(tree);

// Add the scroll pane to the frame


[Link](scrollPane);

// Set frame properties


[Link](300, 200);
[Link](null);
[Link](true);
});
}
}

15. tables
import [Link].*;
import [Link].*;

public class testing extends JFrame {

public testing() {
setTitle("Table Example");

// Create column names and data for the table


String[] columnNames = {"Name", "Age", "Occupation"};
Object[][] data = {
{"John Doe", 30, "Engineer"},
{"Jane Smith", 25, "Teacher"},
{"Bob Johnson", 40, "Doctor"},
{"Alice Williams", 35, "Artist"}
};

// Create a JTable with the given data and column names


JTable table = new JTable(data, columnNames);

// Set the layout manager for the frame


setLayout(new BorderLayout());

// Add the table to a JScrollPane to make it scrollable


JScrollPane scrollPane = new JScrollPane(table);

// Add the scroll pane to the frame


add(scrollPane, [Link]);

// Set window properties


setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String[] args) {


new testing();
}
}

16. Progress bar


import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class testing extends JFrame {

private JProgressBar progressBar;


private JButton startButton;

public testing() {
setTitle("Progress Bar Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create components
progressBar = new JProgressBar(0, 100);
startButton = new JButton("Start");

// Set layout manager


setLayout(new FlowLayout());

// Add components to the frame


add(progressBar);
add(startButton);

// Add action listener to the button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Perform a task in a separate thread
SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i <= 100; i++) {
[Link](50); // Simulate a time-consuming task
publish(i); // Update the progress
}
return null;
}

@Override
protected void process([Link]<Integer> chunks) {
// Update the progress bar
[Link]([Link]([Link]() - 1));
}
};

// Execute the SwingWorker


[Link]();
}
});

// Set frame properties


setSize(300, 100);
setLocationRelativeTo(null); // Center the frame on the screen
setVisible(true);
}

public static void main(String[] args) {


new testing();

}
}

17. mouse event


import [Link].*;
import [Link].*;
public class MouseEventExample extends Frame {

private Panel panel;

public MouseEventExample() {
setTitle("Mouse Event Example");

// Create a panel to handle mouse events


panel = new Panel();
[Link](new MyMouseListener());

// Set layout manager for the frame


setLayout(new FlowLayout());

// Add components to the frame


add(panel);

// Set window closing listener


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Set frame properties


setSize(300, 200);
setVisible(true);
}

// Inner class to implement MouseListener


class MyMouseListener implements MouseListener {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at: " + [Link]() + ", " + [Link]());
}

public void mouseEntered(MouseEvent e) {


[Link]("Mouse Entered");
}

public void mouseExited(MouseEvent e) {


[Link]("Mouse Exited");
}

public void mousePressed(MouseEvent e) {


[Link]("Mouse Pressed at: " + [Link]() + ", " + [Link]());
}

public void mouseReleased(MouseEvent e) {


[Link]("Mouse Released at: " + [Link]() + ", " + [Link]());
}
}

public static void main(String[] args) {


new MouseEventExample();
}
}

18. Keyboard event


import [Link].*;
import [Link].*;

public class KeyEventExample extends Frame implements KeyListener {

private TextArea textArea;

public KeyEventExample() {
setTitle("Key Event Example");

textArea = new TextArea();


[Link](this);

// Set layout manager for the frame


setLayout(new BorderLayout());

// Add components to the frame


add(textArea, [Link]);

// Set window closing listener


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Set frame properties


setSize(300, 200);
setVisible(true);
}

// KeyListener methods
public void keyTyped(KeyEvent e) {
// Called when a key is typed (pressed and released)
char keyChar = [Link]();
[Link]("Key Typed: " + keyChar + "\n");
}

public void keyPressed(KeyEvent e) {


// Called when a key is pressed
int keyCode = [Link]();
[Link]("Key Pressed: " + [Link](keyCode) + "\n");
}

public void keyReleased(KeyEvent e) {


// Called when a key is released
int keyCode = [Link]();
[Link]("Key Released: " + [Link](keyCode) + "\n");
}

public static void main(String[] args) {


new KeyEventExample();
}
}

19. Adapter class


import [Link].*;
import [Link].*;

// Custom adapter class for mouse events


class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}

public void mousePressed(MouseEvent e) {


[Link]("Mouse Pressed");
}

public void mouseReleased(MouseEvent e) {


[Link]("Mouse Released");
}
}

public class MouseEventAdapterExample extends Frame {

public MouseEventAdapterExample() {
setTitle("Mouse Event Adapter Example");

// Create an instance of the custom adapter class


MyMouseAdapter mouseAdapter = new MyMouseAdapter();

// Add the adapter to the frame to handle mouse events


addMouseListener(mouseAdapter);

// Set layout manager for the frame


setLayout(new FlowLayout());

// Set window closing listener


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Set frame properties


setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new MouseEventAdapterExample();
}
}

Common questions

Powered by AI

MouseListener and KeyEvent provide detailed, low-level event handling for mouse and keyboard interactions, respectively. Implementing MouseListener allows applications to react to mouse clicks, presses, releases, movement, etc., enabling features like drag-and-drop or custom pointing device actions. KeyEvent allows fine-grained control over keyboard interactions, crucial for implementing hotkeys, shortcuts, or custom input methods. These event listeners enhance interactivity by allowing precise, context-sensitive responses to user inputs, thereby creating a seamless, engaging user experience .

JTabbedPane offers a structured approach to organizing interfaces by grouping related panels or components into separate tabs, reducing clutter in single-window designs. It enhances navigation efficiency by allowing users to switch contexts quickly without opening new windows, which is particularly beneficial in data-heavy applications like IDEs or configuration settings. However, it requires thoughtful design to ensure that tab names and orders are intuitive, avoiding overwhelming users with too many tabs or too much data in one place, thus maintaining usability and accessibility .

MenuBars are useful in Java for providing a structured and intuitive navigation method in applications, enhancing user experience by organizing commands in a hierarchical manner. They allow for efficient space utilization by listing actions in a pull-down format, which is ideal for desktop applications. However, limitations include reduced usefulness on touch interfaces where gestures or icons may be more ergonomic. Additionally, implementing complex command hierarchies necessitates careful planning to maintain usability .

Adapter classes in Java provide a way to implement event-handling interfaces with multiple methods by allowing developers to focus on those methods they need, circumventing the need to implement all interface methods. This simplifies the code for handling mouse, keyboard, and other events by overriding only essential methods, reducing overhead and enhancing maintainability. However, excessive use of adapters without consideration can lead to fragmented logic and possible redundancy, especially if multiple event behaviors require integration into a single handling model .

JFileChooser, part of the Swing library, is more flexible and widely compatible with modern Java applications, providing a richer set of customization options and UI consistency across platforms. FileDialog, an AWT component, is simpler and offers native OS dialogs for file selection, providing a more integrated user experience on systems where native look-and-feel is a priority. The choice depends on the need for simplicity and native integration (FileDialog) versus the need for extensive customization and control over the component's appearance and behavior (JFileChooser).

The ActionListener interface allows Java AWT components, like buttons, to respond to user interaction by defining behavior when an event, such as a button press, occurs. Its key function is the `actionPerformed(ActionEvent e)` method, which must be implemented to specify actions that take place once an event is triggered. This interaction model is crucial for creating dynamic and responsive GUI applications, as it decouples event handling logic from the rest of the program structure, promoting better code organization .

CardLayout is advantageous when you want to switch between multiple components or views within the same space, such as in a wizard dialog or a set of tabbed panes without visible tabs. It manages components like a stack, displaying one at a time, with methods to cycle through the components or directly target one. For example, using the `next()` method will show the next set of components, effectively allowing interactive applications where views change based on user actions .

In applet-based Java applications, ActionListeners enable interaction by responding to user events like button presses or menu selections. This allows applets to perform specific actions, such as updating UI components or processing data, upon user input. By adding ActionListeners to components within applets, developers can create dynamic and engaging web applications, enabling interactive features like form submissions or real-time updates. This mechanism is crucial for enhancing user experience and interaction in applet environments .

GridLayout arranges components in a rectangular grid, where each component takes equally sized space. It is useful for creating uniform layouts like a calculator's buttons. Conversely, FlowLayout aligns components in a row, respects their natural size, and wraps them into new rows if necessary. It is suited for layouts where a natural, non-grid-based structure is desired, such as toolbars. GridLayout offers precise control over size distribution at the cost of flexibility, while FlowLayout provides a simple, adaptive structure ideal for variable-sized components .

GridBagConstraints in GridBagLayout provide more precise control over the components' placement and size compared to other layout managers like FlowLayout or BorderLayout. With GridBagConstraints, you can define the grid position using gridx and gridy, control the component size and alignment using weightx, weighty, fill, and anchor properties. This allows for flexible, dynamic layouts accommodating various component sizes and screen dimensions .

You might also like