0% found this document useful (0 votes)
1 views33 pages

Java Programs Recent

The document contains multiple Java programs created by Laban Onyango at Ndejje University, showcasing various functionalities such as appending strings, creating combo boxes, radio buttons, sliders, menus, and drag-and-drop features. Each program includes code snippets and brief descriptions of their purpose, demonstrating the use of Swing components for GUI applications. The document serves as a practical guide for learning Java programming and GUI development.

Uploaded by

ronniemc98
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)
1 views33 pages

Java Programs Recent

The document contains multiple Java programs created by Laban Onyango at Ndejje University, showcasing various functionalities such as appending strings, creating combo boxes, radio buttons, sliders, menus, and drag-and-drop features. Each program includes code snippets and brief descriptions of their purpose, demonstrating the use of Swing components for GUI applications. The document serves as a practical guide for learning Java programming and GUI development.

Uploaded by

ronniemc98
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/ 33

Java programs by Laban Onyango Ndejje University

1. This program will append

class appendDemo

public static void main(String arg[])

String s;

int a=76;

StringBuffer sb=new StringBuffer(40);

s=sb.append("a=").append(a).append("!").toString();

System.out.println(s);

2. This program will create a combo box and allow the user to add or remove items from the
combo with ease

import javax.swing.*;

import java.awt.event.*;

public class AddRemoveItemFromCombo{

JComboBox combo;

JTextField txtBox;

public static void main(String[] args){

AddRemoveItemFromCombo ar = new AddRemoveItemFromCombo();

public AddRemoveItemFromCombo(){

1
JFrame frame = new JFrame("Add-Remove Item of a Combo Box");

String items[] = {"Java", "JSP", "PHP", "C", "C++"};

combo = new JComboBox(items);

JButton button1 = new JButton("Add");

txtBox = new JTextField(20);

button1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (!txtBox.getText().equals("")){

int a = 0;

for(int i = 0; i < combo.getItemCount(); i++){

if(combo.getItemAt(i).equals(txtBox.getText())){

a = 1;

break;

if (a == 1)

JOptionPane.showMessageDialog(null,"Combo has already this item.");

else

combo.addItem(txtBox.getText());

else{

JOptionPane.showMessageDialog(null,"Please enter text in Text Box");

});

2
JButton button2 = new JButton("Remove");

button2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

if (combo.getItemCount() > 0)

combo.removeItemAt(0);

else

JOptionPane.showMessageDialog(null,"Item not available");

});

JPanel panel = new JPanel();

JPanel panel1 = new JPanel();

panel.add(txtBox);

panel.add(combo);

panel.add(button1);

panel.add(button2);

frame.add(panel);

// frame.add(panel1);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Output

3
3. Program to create a combo box

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class ComboBox{

JComboBox combo;

JTextField txt;

public static void main(String[] args) {

ComboBox b = new ComboBox();

public ComboBox(){

String course[] = {"BCA","MCA","BCIM","BBAM"};

JFrame frame = new JFrame("Creating a JComboBox Component");

4
JPanel panel = new JPanel();

combo = new JComboBox(course);

combo.setBackground(Color.gray);

combo.setForeground(Color.red);

txt = new JTextField(10);

panel.add(combo);

panel.add(txt);

frame.add(panel);

combo.addItemListener(new ItemListener(){

public void itemStateChanged(ItemEvent ie){

String str = (String)combo.getSelectedItem();

txt.setText(str);

});

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400,400);

frame.setVisible(true);

5
Output

4. Create list of items

import javax.swing.*;

public class CreateJList{

public static void main(String[] args) {

String subject[] = {"Math", "Computer", "Phisics", "Chemestry"};

JFrame frame = new JFrame("Creating a JList Component");

JPanel panel = new JPanel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JList list = new JList(subject);

frame.setUndecorated(true);

frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);

panel.add(list);

frame.add(panel);

frame.setSize(400,400);

frame.setVisible(true);

6
}

Output

5. Program to create a radio button

import javax.swing.*;

import java.awt.*;

public class CreateRadioButton{

public static void main(String[] args) {

CreateRadioButton r = new CreateRadioButton();

public CreateRadioButton(){

JRadioButton Male,Female;

JFrame frame = new JFrame("Creating a JRadioButton Component");

JPanel panel = new JPanel();

ButtonGroup buttonGroup = new ButtonGroup();

Male = new JRadioButton("Male");

buttonGroup.add(Male);

7
panel.add(Male);

Female = new JRadioButton("Female");

buttonGroup.add(Female);

panel.add(Female);

Male.setSelected(true);

frame.add(panel);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400,400);

frame.setVisible(true);

Output

6. This program creates slider

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

8
public class CreateSlider{

JSlider slider;

JLabel label;

public static void main(String[] args){

CreateSlider cs = new CreateSlider();

public CreateSlider(){

JFrame frame = new JFrame("Slider Frame");

slider = new JSlider();

slider.setValue(70);

slider.addChangeListener(new MyChangeAction());

label = new JLabel("LABAN AND FAMILY");

JPanel panel = new JPanel();

panel.add(slider);

panel.add(label);

frame.add(panel, BorderLayout.CENTER);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public class MyChangeAction implements ChangeListener{

public void stateChanged(ChangeEvent ce){

9
int value = slider.getValue();

String str = Integer.toString(value);

label.setText(str);

Output

7. Program to create a menu

import javax.swing.*;

public class SwingMenu{

public static void main(String[] args) {

SwingMenu s = new SwingMenu();

public SwingMenu(){

JFrame frame = new JFrame("Creating a JMenuBar, JMenu, JMenuItem and seprator Component");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

10
JMenuBar menubar = new JMenuBar();

JMenu filemenu = new JMenu("File");

filemenu.add(new JSeparator());

JMenu editmenu = new JMenu("Edit");

editmenu.add(new JSeparator());

JMenuItem fileItem1 = new JMenuItem("New");

JMenuItem fileItem2 = new JMenuItem("Open");

JMenuItem fileItem3 = new JMenuItem("Close");

fileItem3.add(new JSeparator());

JMenuItem fileItem4 = new JMenuItem("Save");

JMenuItem editItem1 = new JMenuItem("Cut");

JMenuItem editItem2 = new JMenuItem("Copy");

editItem2.add(new JSeparator());

JMenuItem editItem3 = new JMenuItem("Paste");

JMenuItem editItem4 = new JMenuItem("Insert");

filemenu.add(fileItem1);

filemenu.add(fileItem2);

filemenu.add(fileItem3);

filemenu.add(fileItem4);

editmenu.add(editItem1);

editmenu.add(editItem2);

editmenu.add(editItem3);

editmenu.add(editItem4);

menubar.add(filemenu);

menubar.add(editmenu);

11
frame.setJMenuBar(menubar);

frame.setSize(400,400);

frame.setVisible(true);

Output

8. Program that will allow text to be dragged and dropped

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SwingDragDrop{

JTextField txtField;

JLabel lbl;

public static void main(String[] args){

SwingDragDrop sdd = new SwingDragDrop();

12
public SwingDragDrop(){

JFrame frame = new JFrame("Drag Drop Demo");

txtField = new JTextField(20);

lbl = new JLabel("This is the text for drag and drop.");

lbl.setTransferHandler(new TransferHandler("text"));

MouseListener ml = new MouseAdapter(){

public void mousePressed(MouseEvent e){

JComponent jc = (JComponent)e.getSource();

TransferHandler th = jc.getTransferHandler();

th.exportAsDrag(jc, e, TransferHandler.COPY);

};

lbl.addMouseListener(ml);

JPanel panel = new JPanel();

panel.add(txtField);

frame.add(lbl, BorderLayout.CENTER);

frame.add(panel, BorderLayout.NORTH);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setResizable(false);

13
Output

9. Tooltip program

import java.awt.event.*;

public class TooltipTextOfList{

private JScrollPane scrollpane = null;

JList list;

JTextField txtItem;

DefaultListModel model;

public static void main(String[] args){

TooltipTextOfList tt = new TooltipTextOfList();

public TooltipTextOfList(){

JFrame frame = new JFrame("Tooltip Text for List Item");

String[] str_list = {"One", "Two", "Three", "Four"};

model = new DefaultListModel();

14
for(int i = 0; i < str_list.length; i++)

model.addElement(str_list[i]);

list = new JList(model){

public String getToolTipText(MouseEvent e) {

int index = locationToIndex(e.getPoint());

if (-1 < index) {

String item = (String)getModel().getElementAt(index);

return item;

} else {

return null;

};

txtItem = new JTextField(10);

JButton button = new JButton("Add");

button.addActionListener(new MyAction());

JPanel panel = new JPanel();

panel.add(txtItem);

panel.add(button);

panel.add(list);

frame.add(panel, BorderLayout.CENTER);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

15
public class MyAction extends MouseAdapter implements ActionListener{

public void actionPerformed(ActionEvent ae){

String data = txtItem.getText();

if (data.equals(""))

JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");

else{

model.addElement(data);

JOptionPane.showMessageDialog(null,"Item added successfully.");

txtItem.setText("");

Output

16
10. To find multiples of numbers provided by the user (the user provides the starting number and
the last number

import java.util.Scanner;

public class Multiples

public static void main(String args[])

final int PER_LINE = 5;

int value, limit, mult, count = 0;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter postive value: ");

value = scan.nextInt();

System.out.print ("Enter an upper limit: ");

limit = scan.nextInt();

System.out.println ();

System.out.println ("The multiples of " +value + "between" + value + "and" + limit + "inclusive are:");

for (mult = value; mult <= limit; mult +=value)

17
System.out.print (mult + "\t");

count++;

if(count % PER_LINE == 0)

System.out.println();

11. Program to create tool bar with three buttons

import javax.swing.*;

import java.awt.*;

public class CreateToolbar{

public static void main(String[] args) {

JFrame frame = new JFrame("Create a toolbar Which have three buttons Such as: Cut, Copy, Paste");

JToolBar toolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);

JButton cutbutton = new JButton(new ImageIcon("cut.gif"));

toolbar.add(cutbutton);

JButton copybutton = new JButton(new ImageIcon("copy.gif"));

18
toolbar.add(copybutton);

JButton pastebutton = new JButton(new ImageIcon("paste.gif"));

toolbar.add(pastebutton);

frame.getContentPane().add(toolbar,BorderLayout.NORTH);

frame.setUndecorated(true);

frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(500,400);

frame.setVisible(true);

12. Same button program but the name of the button changes when clicked on

import javax.swing.*;

import java.awt.event.*;

public class ChangeButtonLabel{

JButton button;

public static void main(String[] args){

ChangeButtonLabel cl = new ChangeButtonLabel();

19
}

public ChangeButtonLabel(){

JFrame frame = new JFrame("Change JButton Lebel");

button = new JButton("Click here");

button.addActionListener(new MyAction());

frame.add(button);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public class MyAction implements ActionListener{

public void actionPerformed(ActionEvent e){

String text = (String)e.getActionCommand();

if (text.equals("Click here")){

button.setText("another label");

else{

button.setText("Click here");

20
13. List items for selection but only one can be selected

import javax.swing.*;

import java.awt.event.*;

public class DimensionItemList{

public static void main(String[] args) {

DimensionItemList di = new DimensionItemList();

public DimensionItemList(){

String name[] = {"PEACE", "PATRICIA DEBORAH ", "LABAN", "IRENE", "PAULINE", "JAMES",
"MATHEW"};

JFrame frame = new JFrame("Setting the Dimensions of an Item in a JList Component");

JPanel panel = new JPanel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

DefaultListModel model = new DefaultListModel();

for(int i = 0; i < name.length; i++)

21
model.addElement(name[i]);

JList list = new JList(model){

public String getToolTipText(MouseEvent e) {

int index = locationToIndex(e.getPoint());

if (-1 < index) {

String item = (String)getModel().getElementAt(index);

return item;

} else {

return null;

};

list.setPrototypeCellValue("NDEJJE UNIVERSITY");

panel.add(list);

frame.add(panel);

frame.setSize(400,400);

frame.setVisible(true);

22
14. Program to display message dialog box when a button is clicked

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class ShowMessageDialog{

JButton button;

public static void main(String[] args){

ShowMessageDialog md = new ShowMessageDialog();

public ShowMessageDialog(){

JFrame frame = new JFrame("Message Dialog Box");

button = new JButton("Show simple message dialog box");

button.addActionListener(new MyAction());

JPanel panel = new JPanel();

panel.add(button);

23
button = new JButton("Show \"Ok/Cancel\" message dialog box");

button.addActionListener(new MyAction());

panel.add(button);

button = new JButton("Show \"Yes/No/Cancel\" dialog box");

button.addActionListener(new MyAction());

panel.add(button);

frame.add(panel);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public class MyAction implements ActionListener{

public void actionPerformed(ActionEvent ae){

String str = ae.getActionCommand();

if(str.equals("Show simple message dialog box")){

JOptionPane.showMessageDialog(null, "This is the simple message dialog box.", "Laban's dialog


box", 1);

else if(str.equals("Show \"Ok/Cancel\" message dialog box")){

if(JOptionPane.showConfirmDialog(null, "This is the \"Ok/Cancel\" message dialog box.",


"Roseindia.net", JOptionPane.OK_CANCEL_OPTION) == 0)

JOptionPane.showMessageDialog(null, "You clicked on \"Ok\" button", "Laban's dialog box", 1);

else

JOptionPane.showMessageDialog(null, "You clicked on \"Cancel\" button", "Laban's dialog box",


1);

else if(str.equals("Show \"Yes/No/Cancel\" dialog box")){

24
JOptionPane.showConfirmDialog(null, "This is the \"Yes/No/Cancel\" message dialog box.");

15. Program to design a simple data entry form

import java.awt.*;

import java.awt.event.*;

public class DataEntry {

public static void main(String[] args) {

Frame frm=new Frame("DataEntry frame");

Label lbl = new Label("Please fill this blank:");

frm.add(lbl);

frm.setSize(350,200);

frm.setVisible(true);

frm.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);

});

Panel p = new Panel();

Panel p1 = new Panel();

Label jFirstName = new Label("First Name");

25
TextField lFirstName = new TextField(20);

Label jLastName =new Label("Last Name");

TextField lLastName=new TextField(20);

p.setLayout(new GridLayout(3,1));

p.add(jFirstName);

p.add(lFirstName);

p.add(jLastName);

p.add(lLastName);

Button Submit=new Button("Submit");

p.add(Submit);

p1.add(p);

frm.add(p1,BorderLayout.NORTH);

Output

16. Program to show options

import java.awt.GridLayout;

import javax.swing.*;

class JOptionPaneTest {

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

String[] items = {"One", "Two", "Three", "Four", "Five"};

JComboBox combo = new JComboBox(items);

JTextField field1 = new JTextField("1234.56");

JTextField field2 = new JTextField("9876.54");

JPanel panel = new JPanel(new GridLayout(0, 1));

panel.add(combo);

panel.add(new JLabel("Field 1:"));

panel.add(field1);

panel.add(new JLabel("Field 2:"));

panel.add(field2);

int result = JOptionPane.showConfirmDialog(null, panel, "Test",

JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

if (result == JOptionPane.OK_OPTION) {

System.out.println(combo.getSelectedItem()

+ " " + field1.getText()

+ " " + field2.getText());

} else {

System.out.println("Cancelled");

27
Output

17. Program design dialog box

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class ShowMessageDialog{

JButton button;

public static void main(String[] args){

ShowMessageDialog md = new ShowMessageDialog();

public ShowMessageDialog(){

JFrame frame = new JFrame("Message Dialog Box");

button = new JButton("Show simple message dialog box");

button.addActionListener(new MyAction());

JPanel panel = new JPanel();

panel.add(button);

28
button = new JButton("Show \"Ok/Cancel\" message dialog box");

button.addActionListener(new MyAction());

panel.add(button);

button = new JButton("Show \"Yes/No/Cancel\" dialog box");

button.addActionListener(new MyAction());

panel.add(button);

frame.add(panel);

frame.setSize(400, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public class MyAction implements ActionListener{

public void actionPerformed(ActionEvent ae){

String str = ae.getActionCommand();

if(str.equals("Show simple message dialog box")){

JOptionPane.showMessageDialog(null, "This is the simple message dialog box.", "Laban's dialog


box", 1);

else if(str.equals("Show \"Ok/Cancel\" message dialog box")){

if(JOptionPane.showConfirmDialog(null, "This is the \"Ok/Cancel\" message dialog box.",


"Roseindia.net", JOptionPane.OK_CANCEL_OPTION) == 0)

JOptionPane.showMessageDialog(null, "You clicked on \"Ok\" button", "Laban's dialog box", 1);

else

JOptionPane.showMessageDialog(null, "You clicked on \"Cancel\" button", "Laban's dialog box",


1);

else if(str.equals("Show \"Yes/No/Cancel\" dialog box")){

29
JOptionPane.showConfirmDialog(null, "This is the \"Yes/No/Cancel\" message dialog box.");

Output

18. Program to design report editor

import java.awt.*;

import java.awt.event.*;

import java.io.File;

import java.io.FileReader;

import javax.swing.*;

public class basicFrame extends JFrame {

30
// Declare Variables

JScrollPane bildlauf = new JScrollPane();

JTextArea txtfeld = new JTextArea();

public basicFrame() {

super();

// Main window

setTitle("ReportEditor");

setBackground(Color.LIGHT_GRAY);

// components

try {

File datei = new File("report.Rnw");

FileReader in = new FileReader(datei);

txtfeld.read(in, datei);

in.close();

} catch (Exception e) {

System.out.println("Error !");

// setLayout(new GridLayout(2,2));

// Scroll Shizzle

31
bildlauf.getViewport().add(txtfeld, null);

getContentPane().add(bildlauf, BorderLayout.CENTER);

//txtfeld.setSize(500,680);

//add(txtfeld);

//this.getContentPane().add(txtfeld);

// close

addWindowListener(new WindowLauscher());

// event handlers...

protected static final class WindowLauscher extends WindowAdapter {

public void windowClosing(WindowEvent e) {

System.exit(0);

public static void main(String[] args) {

//Fesnter erzeugen und anzeigen, die main Sache halt

basicFrame hf = new basicFrame();

hf.setSize(500, 700);

hf.setLocation(100, 100);

hf.setVisible(true);

32
}

Output

33

You might also like