0% found this document useful (0 votes)
6 views

Assignment( java classwork )

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Assignment( java classwork )

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Name: Patil Devdatta Narendra

Reg No: 22BCE11659

Assignment( java classwork 2)


Question 1
Implement:

Menus: Menu Building, Icons in

Menu Items, Check box and Radio Buttons in Menu Items, Pop-up

6 b, c

Menus, Keyboard Mnemonics and Accelerators, Enabling and

Design menu Items, Toolbars, Tooltips

SOLUTION:

package TextEditorApp;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class TextEditorApp extends JFrame {

private JTextArea textArea;

private JLabel statusBar;

public TextEditorApp() {

setTitle("Text Editor");

setSize(800, 600);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLocationRelativeTo(null);

// Text Area

textArea = new JTextArea();


textArea.setLineWrap(true);

textArea.setWrapStyleWord(true);

JScrollPane scrollPane = new JScrollPane(textArea);

add(scrollPane, BorderLayout.CENTER);

// Menu Bar

JMenuBar menuBar = new JMenuBar();

// File Menu

JMenu fileMenu = new JMenu("File");

fileMenu.setMnemonic('F');

JMenuItem newItem = new JMenuItem("New");

newItem.setAccelerator(KeyStroke.getKeyStroke('N',
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));

newItem.addActionListener(e -> textArea.setText(""));

fileMenu.add(newItem);

JMenuItem openItem = new JMenuItem("Open");

openItem.setAccelerator(KeyStroke.getKeyStroke('O',
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));

openItem.addActionListener(e -> JOptionPane.showMessageDialog(this, "Open file


feature coming soon!", "Info", JOptionPane.INFORMATION_MESSAGE));

fileMenu.add(openItem);

JMenuItem saveItem = new JMenuItem("Save");

saveItem.setAccelerator(KeyStroke.getKeyStroke('S',
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));

saveItem.addActionListener(e -> JOptionPane.showMessageDialog(this, "Save file


feature coming soon!", "Info", JOptionPane.INFORMATION_MESSAGE));

fileMenu.add(saveItem);

fileMenu.addSeparator();
JMenuItem exitItem = new JMenuItem("Exit");

exitItem.addActionListener(e -> System.exit(0));

fileMenu.add(exitItem);

menuBar.add(fileMenu);

// Edit Menu

JMenu editMenu = new JMenu("Edit");

editMenu.setMnemonic('E');

JMenuItem cutItem = new JMenuItem("Cut");

cutItem.addActionListener(e -> textArea.cut());

editMenu.add(cutItem);

JMenuItem copyItem = new JMenuItem("Copy");

copyItem.addActionListener(e -> textArea.copy());

editMenu.add(copyItem);

JMenuItem pasteItem = new JMenuItem("Paste");

pasteItem.addActionListener(e -> textArea.paste());

editMenu.add(pasteItem);

menuBar.add(editMenu);

// View Menu with Checkboxes and Radio Buttons

JMenu viewMenu = new JMenu("View");

JCheckBoxMenuItem showStatusBar = new JCheckBoxMenuItem("Show Status Bar",


true);

showStatusBar.addActionListener(e -> statusBar.setVisible(showStatusBar.isSelected()));

viewMenu.add(showStatusBar);
JMenu themeMenu = new JMenu("Theme");

JRadioButtonMenuItem lightTheme = new JRadioButtonMenuItem("Light", true);

JRadioButtonMenuItem darkTheme = new JRadioButtonMenuItem("Dark");

ButtonGroup themeGroup = new ButtonGroup();

themeGroup.add(lightTheme);

themeGroup.add(darkTheme);

lightTheme.addActionListener(e -> textArea.setBackground(Color.WHITE));

darkTheme.addActionListener(e -> textArea.setBackground(Color.DARK_GRAY));

themeMenu.add(lightTheme);

themeMenu.add(darkTheme);

viewMenu.add(themeMenu);

menuBar.add(viewMenu);

setJMenuBar(menuBar);

// ToolBar

JToolBar toolBar = new JToolBar();

JButton newButton = new JButton("New");

newButton.setToolTipText("Create a new file");

newButton.addActionListener(e -> textArea.setText(""));

toolBar.add(newButton);

JButton openButton = new JButton("Open");

openButton.setToolTipText("Open an existing file");

toolBar.add(openButton);

JButton saveButton = new JButton("Save");

saveButton.setToolTipText("Save the current file");

toolBar.add(saveButton);
add(toolBar, BorderLayout.NORTH);

// Popup Menu

JPopupMenu popupMenu = new JPopupMenu();

JMenuItem popupCut = new JMenuItem("Cut");

popupCut.addActionListener(e -> textArea.cut());

popupMenu.add(popupCut);

JMenuItem popupCopy = new JMenuItem("Copy");

popupCopy.addActionListener(e -> textArea.copy());

popupMenu.add(popupCopy);

JMenuItem popupPaste = new JMenuItem("Paste");

popupPaste.addActionListener(e -> textArea.paste());

popupMenu.add(popupPaste);

textArea.setComponentPopupMenu(popupMenu);

// Status Bar

statusBar = new JLabel(" Ready");

statusBar.setBorder(BorderFactory.createEtchedBorder());

add(statusBar, BorderLayout.SOUTH);

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

TextEditorApp app = new TextEditorApp();

app.setVisible(true);

});

}.

}
OUTPUT:

QUESTION: 2

Dialog Boxes: Option

Dialogs, Creating Dialogs, Data Exchange, File Choosers, Color

Choosers .

SOLUTION:

package drawingApp;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.File;

public class drawingApp extends JFrame {


private JPanel canvas;

public drawingApp() {

setTitle("Drawing Application");

setSize(800, 600);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLocationRelativeTo(null);

// Canvas panel

canvas = new JPanel();

canvas.setBackground(Color.WHITE);

add(canvas, BorderLayout.CENTER);

// Menu Bar

JMenuBar menuBar = new JMenuBar();

// File Menu

JMenu fileMenu = new JMenu("File");

fileMenu.setMnemonic('F');

JMenuItem newFile = new JMenuItem("New");

newFile.addActionListener(e -> newCanvas());

fileMenu.add(newFile);

JMenuItem openFile = new JMenuItem("Open");

openFile.addActionListener(e -> openFileDialog());

fileMenu.add(openFile);

JMenuItem saveFile = new JMenuItem("Save");

saveFile.addActionListener(e -> saveFileDialog());

fileMenu.add(saveFile);
JMenuItem exitApp = new JMenuItem("Exit");

exitApp.addActionListener(e -> exitApplication());

fileMenu.add(exitApp);

menuBar.add(fileMenu);

// Edit Menu

JMenu editMenu = new JMenu("Edit");

JMenuItem changeColor = new JMenuItem("Change Canvas Color");

changeColor.addActionListener(e -> openColorChooser());

editMenu.add(changeColor);

JMenuItem showCustomDialog = new JMenuItem("About");

showCustomDialog.addActionListener(e -> openCustomDialog());

editMenu.add(showCustomDialog);

menuBar.add(editMenu);

setJMenuBar(menuBar);

// Status Bar

JLabel statusBar = new JLabel(" Ready");

statusBar.setBorder(BorderFactory.createEtchedBorder());

add(statusBar, BorderLayout.SOUTH);

// Event Listener for Canvas Mouse Interaction

canvas.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

statusBar.setText("Mouse clicked at: " + e.getX() + ", " + e.getY());

}
});

/**

* Clears the canvas for a new drawing.

*/

private void newCanvas() {

int response = JOptionPane.showConfirmDialog(

this,

"Are you sure you want to start a new canvas? Unsaved changes will be lost.",

"New Canvas",

JOptionPane.YES_NO_OPTION,

JOptionPane.WARNING_MESSAGE

);

if (response == JOptionPane.YES_OPTION) {

canvas.setBackground(Color.WHITE);

JOptionPane.showMessageDialog(this, "New canvas created!", "Info",


JOptionPane.INFORMATION_MESSAGE);

/**

* Opens a File Chooser dialog to select a file to open.

*/

private void openFileDialog() {

JFileChooser fileChooser = new JFileChooser();

int response = fileChooser.showOpenDialog(this);

if (response == JFileChooser.APPROVE_OPTION) {

File selectedFile = fileChooser.getSelectedFile();


JOptionPane.showMessageDialog(this, "Opened file: " + selectedFile.getName(), "File Open",
JOptionPane.INFORMATION_MESSAGE);

/**

* Opens a File Chooser dialog to save a file.

*/

private void saveFileDialog() {

JFileChooser fileChooser = new JFileChooser();

int response = fileChooser.showSaveDialog(this);

if (response == JFileChooser.APPROVE_OPTION) {

File selectedFile = fileChooser.getSelectedFile();

JOptionPane.showMessageDialog(this, "File saved as: " + selectedFile.getName(), "File Save",


JOptionPane.INFORMATION_MESSAGE);

/**

* Opens a Color Chooser dialog to change the canvas background color.

*/

private void openColorChooser() {

Color selectedColor = JColorChooser.showDialog(this, "Choose Canvas Color",


canvas.getBackground());

if (selectedColor != null) {

canvas.setBackground(selectedColor);

/**
* Opens a custom dialog for displaying app information.

*/

private void openCustomDialog() {

JDialog dialog = new JDialog(this, "About Drawing App", true);

dialog.setSize(300, 200);

dialog.setLayout(new BorderLayout());

dialog.setLocationRelativeTo(this);

JLabel label = new JLabel("<html><h2>Drawing App</h2><p>Version: 1.0<br>Author: Your


Name</p></html>", JLabel.CENTER);

dialog.add(label, BorderLayout.CENTER);

JButton closeButton = new JButton("Close");

closeButton.addActionListener(e -> dialog.dispose());

dialog.add(closeButton, BorderLayout.SOUTH);

dialog.setVisible(true);

/**

* Handles application exit with confirmation.

*/

private void exitApplication() {

int response = JOptionPane.showConfirmDialog(

this,

"Are you sure you want to exit?",

"Exit Application",

JOptionPane.YES_NO_OPTION,

JOptionPane.QUESTION_MESSAGE

);
if (response == JOptionPane.YES_OPTION) {

System.exit(0);

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

drawingApp app = new drawingApp();

app.setVisible(true);

});

OUTPUT:
QUESTION: 3

Components Organizers: Split Panes, Tabbed Panes,

Desktop Panes and Internal Frames, Cascading and Tiling

Advance Swing Components: List, Trees, Tables, Progress Bars

SOLUTION:

package DocumentManagementSystem;

import javax.swing.*;

import javax.swing.table.DefaultTableModel;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;

import java.awt.*;

import java.awt.event.*;

import java.util.Vector;

public class DocumentManagementSystem extends JFrame {

private JTabbedPane mainTabbedPane;

private JDesktopPane desktopPane;

private JList<String> documentList;

private JTree documentTree;

private JTable documentTable;


private JProgressBar uploadProgressBar;

public DocumentManagementSystem() {

// Set up the main frame

setTitle("Document Management System");

setSize(1000, 700);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

// Create main layout with split pane

JSplitPane mainSplitPane = createMainSplitPane();

add(mainSplitPane);

// Set up menu bar

setJMenuBar(createMenuBar());

private JSplitPane createMainSplitPane() {

// Create left panel with document navigation components

JPanel leftPanel = new JPanel(new BorderLayout());

// Create tabbed pane for different views

mainTabbedPane = new JTabbedPane();

// List View

mainTabbedPane.addTab("List View", createListView());

// Tree View

mainTabbedPane.addTab("Tree View", createTreeView());

// Table View
mainTabbedPane.addTab("Table View", createTableView());

leftPanel.add(mainTabbedPane, BorderLayout.CENTER);

// Create right panel with desktop pane for internal frames

JPanel rightPanel = new JPanel(new BorderLayout());

desktopPane = new JDesktopPane();

desktopPane.setBackground(Color.LIGHT_GRAY);

// Add some sample internal frames

addInternalFrames();

rightPanel.add(desktopPane, BorderLayout.CENTER);

// Create upload progress bar

uploadProgressBar = new JProgressBar(0, 100);

uploadProgressBar.setStringPainted(true);

rightPanel.add(uploadProgressBar, BorderLayout.SOUTH);

// Create main split pane

JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);

mainSplitPane.setDividerLocation(300);

return mainSplitPane;

private JScrollPane createListView() {

// Create document list

Vector<String> documents = new Vector<>();

documents.add("Project Proposal.docx");

documents.add("Financial Report 2023.pdf");

documents.add("Marketing Strategy.pptx");
documents.add("Employee Handbook.pdf");

documentList = new JList<>(documents);

documentList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

return new JScrollPane(documentList);

private JScrollPane createTreeView() {

// Create document tree

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Documents");

// Department nodes

DefaultMutableTreeNode finance = new DefaultMutableTreeNode("Finance");

finance.add(new DefaultMutableTreeNode("Budget 2023.xlsx"));

finance.add(new DefaultMutableTreeNode("Expense Reports.pdf"));

DefaultMutableTreeNode marketing = new DefaultMutableTreeNode("Marketing");

marketing.add(new DefaultMutableTreeNode("Campaign Strategy.pptx"));

marketing.add(new DefaultMutableTreeNode("Social Media Plan.docx"));

root.add(finance);

root.add(marketing);

documentTree = new JTree(root);

return new JScrollPane(documentTree);

private JScrollPane createTableView() {

// Create document table

String[] columnNames = {"Document Name", "Type", "Size", "Last Modified"};


Object[][] data = {

{"Project Proposal.docx", "Word Document", "256 KB", "2023-12-01"},

{"Financial Report.pdf", "PDF", "1.2 MB", "2023-11-15"},

{"Marketing Strategy.pptx", "PowerPoint", "5.6 MB", "2023-12-05"},

{"Employee Handbook.pdf", "PDF", "2.3 MB", "2023-10-20"}

};

DefaultTableModel model = new DefaultTableModel(data, columnNames);

documentTable = new JTable(model);

return new JScrollPane(documentTable);

private void addInternalFrames() {

// Create internal frames

JInternalFrame frame1 = createInternalFrame("Document Preview", 50, 50, 300, 250);

JInternalFrame frame2 = createInternalFrame("Document Properties", 100, 100, 250, 200);

desktopPane.add(frame1);

desktopPane.add(frame2);

private JInternalFrame createInternalFrame(String title, int x, int y, int width, int height) {

JInternalFrame internalFrame = new JInternalFrame(title, true, true, true, true);

internalFrame.setBounds(x, y, width, height);

// Add some sample content

JTextArea textArea = new JTextArea("Document details...");

internalFrame.add(new JScrollPane(textArea));

internalFrame.setVisible(true);

return internalFrame;
}

private JMenuBar createMenuBar() {

JMenuBar menuBar = new JMenuBar();

// File Menu

JMenu fileMenu = new JMenu("File");

JMenuItem uploadItem = new JMenuItem("Upload Document");

uploadItem.addActionListener(e -> simulateUpload());

fileMenu.add(uploadItem);

menuBar.add(fileMenu);

return menuBar;

private void simulateUpload() {

// Simulate document upload with progress bar

SwingWorker<Void, Integer> worker = new SwingWorker<>() {

@Override

protected Void doInBackground() throws Exception {

for (int i = 0; i <= 100; i += 10) {

Thread.sleep(500);

publish(i);

return null;

@Override

protected void process(java.util.List<Integer> chunks) {

int latestProgress = chunks.get(chunks.size() - 1);

uploadProgressBar.setValue(latestProgress);
uploadProgressBar.setString("Uploading: " + latestProgress + "%");

@Override

protected void done() {

uploadProgressBar.setString("Upload Complete!");

};

worker.execute();

public static void main(String[] args) {

// Set up Nimbus Look and Feel

try {

for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

UIManager.setLookAndFeel(info.getClassName());

break;

} catch (Exception e) {

// If Nimbus is not available, we'll use the default look and feel

// Ensure GUI is created on Event Dispatch Thread

SwingUtilities.invokeLater(() -> {

DocumentManagementSystem dms = new DocumentManagementSystem();

dms.setVisible(true);

});

}
}

OUTPUT:

You might also like