0% found this document useful (0 votes)
0 views25 pages

Java Practice

The document contains various Java code snippets demonstrating different programming concepts such as user input, arrays, ArrayLists, method overloading, inheritance, polymorphism, and exception handling. It includes examples of using Scanner and JOptionPane for input, working with 2D arrays and ArrayLists, and implementing interfaces. Additionally, it showcases error handling with try-catch blocks and the use of constructors and the 'super' keyword in class inheritance.

Uploaded by

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

Java Practice

The document contains various Java code snippets demonstrating different programming concepts such as user input, arrays, ArrayLists, method overloading, inheritance, polymorphism, and exception handling. It includes examples of using Scanner and JOptionPane for input, working with 2D arrays and ArrayLists, and implementing interfaces. Additionally, it showcases error handling with try-catch blocks and the use of constructors and the 'super' keyword in class inheritance.

Uploaded by

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

import java.util.

Scanner;

Scanner input = new Scanner(System.in);


System.out.print("Enter your name : ");
String name = input.nextLine();

System.out.print("Enter your age : ");


int age = input.nextInt();

input.nextLine();
System.out.print("Your favourite food : ");
String food = input.nextLine();

System.out.println("My name is " + name);


System.out.println("I am " + age + " years old");
System.out.println("My fav food is " + food);

import javax.swing.JOptionPane;

public class Main{


public static void main(String[] args) {
// JOptionPane takes input as String
int age = Integer.parseInt(JOptionPane.showInputDialog("Enter your age: "));
JOptionPane.showMessageDialog(null, "Your age is "+ age);

String name = JOptionPane.showInputDialog("Enter your name: ");


JOptionPane.showMessageDialog(null,"Your name is "+name);

double price = Double.parseDouble(JOptionPane.showInputDialog("Enter your


dress cost: "));
JOptionPane.showMessageDialog(null, "Your dress costs "+ price+"$");
}
}

double x = 67.573;
double y = 25;
// round gives an int val 4.4= 4, 5.65=6
// floor gives int val 6.7 =6
// ceil gives int val 5.4 =6

double z = Math.ceil(x);
System.out.println(z);
z = Math.floor(x);
System.out.println(z);
z = Math.round(x);
System.out.println(z);

import java.util.Random;

Random random1 = new Random();


//int x = random1.nextInt(6)+1;
double x = random1.nextDouble();
System.out.println(x);

boolean z = random1.nextBoolean();
System.out.println(z);

// 2D Array
String[][] car = new String[][] {
{"Mustang", "BMW", "Camaro"},
{"Toyota", "Corvette", "Mercedes"},
{"Ranger","F-150","Ferrari"}
};

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


for (int j =0 ; j < car[i].length; j++) {
System.out.print(car[i][j]+"\t");
}
System.out.println();
}

import java.util.*;

// 2D ArrayList
ArrayList<ArrayList<String>> groceryList = new ArrayList<>();

ArrayList<String> bakeryList = new ArrayList<>();


bakeryList.add("Chilli");
bakeryList.add("Biscuits");
bakeryList.add("Donuts");

ArrayList<String> produceList = new ArrayList<>();


produceList.add("potatoes");
produceList.add("Peppers");
produceList.add("Potatoes");

ArrayList<String> drinksList = new ArrayList<>();


drinksList.add("Soda");
drinksList.add("7-up");

groceryList.add(bakeryList);
groceryList.add(produceList);
groceryList.add(drinksList);

System.out.println(groceryList.get(0));
System.out.println(groceryList.get(2).get(1));

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> food = new ArrayList<>();
food.add("Pizza");
food.add("Hot dog");
food.add("Pasta");
food.add("Chicken");

food.set(3, "Hamburger");
food.remove("Hamburger");
//food.remove(3)
for (int i = 0; i < food.size(); i++) {
System.out.println(food.get(i));
}
}
}

// String[] pets = {"Dog", "Cat", "Rabbit", "Guinea Pig", "Horse",


"Bird", "Fish"};
// for(String i : pets) {
// System.out.println(i);
// }
ArrayList<String> pet = new ArrayList<>();
pet.add("Dog");
pet.add("Cat");
pet.add("Bird");
pet.add("Horse");

for(String i : pet){
System.out.println(i);
}

// Method Overloading
public static void main(String[] args) {
int x = 5, y = 6, z = 7;
int sum = hello(x, y);
System.out.println("x + y = "+ sum);
sum = hello(x, y, z);
System.out.println("x + y + z = "+ sum);
double m = 3.14, n = 5.67;
double doubleSum = hello(m,n);
System.out.println("x + y = "+ doubleSum);
}
static int hello(int a, int b) {
return a + b;
}
static int hello(int a, int b, int c) {
return a + b + c;
}
static double hello(double a, double b) {
return a + b;
}
// printf() = an optional method to control, format, and display text to the
console window
// two arguments = format string + (object/variable/value)
// % [flags] [precision] [width] [conversion-character]
boolean myBoolean = true;
char myChar = '@';
String myString = "Minju";
int myInt = 50;
double myDouble = -12832.36762;

// [conversion-character]
//System.out.printf("%b",myBoolean);
//System.out.printf("%c",myChar);
//System.out.printf("%s",myString);
//System.out.printf("%d",myInt);
//System.out.printf("%f",myDouble);

//[width]
// minimum number of characters to be written as output
//System.out.printf("Hello %10s",myString);

//[precision]
// sets number of digits of precision when outputting floating-point values
//System.out.printf("You have this much money %.1f",myDouble);

// [flags]
// adds an effect to output based on the flag added to format specifier
// - : left-justify
// + : output a plus ( + ) or minus ( - ) sign for a numeric value
// 0 : numeric values are zero-padded
// , : comma grouping separator if numbers > 1000

//System.out.printf("You have this much money %,f",myDouble);


System.out.printf("%020f", myDouble);

// var declared 'final' can't be changed


// final var should be uppercase
final double pi = 3.1416;

// can't assign pi = 628;


System.out.println(pi);

for (int i= 0; i < 5 ; i++) {


if (i%2 ==0 ) {
for (int j = 0; j <= i; j++) {
if (j%2 ==0 ) {
System.out.print(1);
} else
System.out.print(0);
}
}
else {
for (int j = 0; j <= i; j++) {
if (j%2 ==0 ) {
System.out.print(0);
} else
System.out.print(1);
}
}
System.out.println();
}

public Class1() {
Random random = new Random();
int number = 0;
// local var of constructor
// so pass as args
roll(random, number);
}
public void roll(Random random, int number) {
number = random.nextInt(6)+1;
System.out.println(number);
}

Class1 name = new Class1("Minju", "Disha", "Nupur");


// toString is a built-in method for every obj like constructor but has a
string return type ans can be manipulated
System.out.println(name.toString());

public Class1(String name1, String name2, String name3) {


this.name1 = name1;
this.name2 =name2;
this.name3 =name3;
}
public String toString() {
String ans = name1 +","+ name2+","+ name3+ " lives together.";
return ans;
}

Class1 food1 = new Class1("Pizza");


Class1 food2= new Class1("Hamburger");
Class1 food3 = new Class1("Hot dog");
Class1 food4 = new Class1("Noodles");

Class1[] foods = {food1, food2, food3, food4};

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

System.out.println(foods[i].foodName);
}
// for (Class1 i: foods) {
//
// System.out.println(i.foodName);
// }

// passion objects as arguments


Class1 garage = new Class1();
car car1 = new car("Mercedes");
garage.parked(car1);

car car2 = new car("Toyota");


garage.parked(car2);

---------
public class Class1 {

public void parked(car aName) {


System.out.println("your "+aName.name+" has been parked.");
}

car Car1 = new car("Tesla");


System.out.println(Car1.name+ Car1.features()+" and "+Car1.property());

//Inheritance & overiding


public class Class1 {
public String features() {
return " Has a nice color" ;
}
public String property() {
return "Belongs to Donald trump." ;
}
}
public class car extends Class1{
public String name;
car(String name) {
this.name = name;
}
// common practice, not necessary
@Override
public String property() {
return "Belongs to Me." ;
}

// use of super keyword


Class2 Car1 = new Class2("Tesla", "2nd", "Semi");
Class2 Car2 = new Class2("Mercedes", "1st","Y");
System.out.println(Car2.toString());
*****
// super class
public class Class1 {
String Generation;
String Model;

Class1(String Generation, String Model) {


this.Generation = Generation ;
this.Model = Model;
}

public String toString() {


return " \nGeneration: "+Generation+ " \nModel: "+ Model ;
}
}
****
public class Class2 extends Class1 {
String name;
Class2 (String name,String Generation, String Model) {
// super must be used first in constructor
super(Generation, Model);
this.name = name;
}

public String toString() {


return "Name: "+ name + super.toString() ;
}
}

package Package1;
import Package2.*;

public class A {
public static void main(String[] args) {
// Here A,C cls is in package1, Asub, B is in package2
// package is a collection of classes
//default- can be accessed by classes in the same package
//public- can be accessed by classes every package
//protected- can be accessed by classes in the same package and
subclasses in other package
//private- can be accessed by classes in the same package

C cls1 = new C();


System.out.println(cls1.defaultMessage1);
B cls2 = new B();
System.out.println(cls2.publicMessage2);
}
}

package Package1;
import Package2.*;
public class C {
String defaultMessage1 = "I am learning Java.";
}

public class A {
public static void main(String[] args) {
// using getter/setter to access private attributes
C c1 = new C("Chervolet","Camaro", 2021);

c1.setYear(2022);
System.out.println(c1.getMake());
System.out.println(c1.getModel());
System.out.println(c1.getYear());
}
}
--------------------------
public class C extends A {
private String make;
private String model;
private int year;

C(String name, String dept, int ID) {


setName(name);
setDept(dept);
setID(ID);
}

public String getMake() {


return make;
}

public String getModel() {


return model;
}

public int getYear() {


return year;
}

public void setMake(String make) {


this.make = make;
}
public void setModel(String model) {
this.model = model;
}

public void setYear(int year) {


this.year= year;
}
}
public class A {
public static void main(String[] args) {
// stu1, stu2 refer to diff objs but have same attribute
C stu1 = new C("Minju","CSE", 49);
C stu2 = new C(stu1);
//C stu2 = new C("Poushi","CSE", 45);
System.out.println(stu1);
System.out.println(stu2);
System.out.println();

System.out.println(stu1.getName());
System.out.println(stu1.getDept());
System.out.println(stu1.getID());
System.out.println();
// copy stu1 and paste it to stu2
//stu2.copy(stu1);
System.out.println(stu2.getName());
System.out.println(stu2.getDept());
System.out.println(stu2.getID());
}
}
----------------------
public class C extends A {
private String name ;
private String dept;
private int ID ;

C(String name, String dept, int ID) {


setName(name);
setDept(dept);
setID(ID);
}
C(C x) {
copy(x);
}

public String getName() {


return name;
}
public String getDept() {
return dept;
}
public int getID() {
return ID;
}
public void setName(String name) {
this.name = name;
}
public void setDept(String dept) {
this.dept = dept;
}
public void setID(int ID) {
this.ID = ID;
}

public void copy(C x) {


setName(x.getName());
setDept(x.getDept());
setID(x.getID());
}
}

public static void main(String[] args) {


// interface is like a template
// interface has pre-defined methods
// classes can implement interface
//just like subclass can extend superclass

Fish fish = new Fish();


fish.hunt();
fish.flee();

}
----------------------
public class Fish implements Prey, Predator {
@Override
public void hunt() {
System.out.println("*The fish hunting a small fish.*");
}
// implementing Prey interface and overriding pre-defined methods
// classes can implement multiple interfaces
@Override
public void flee() {
System.out.println("*The fish fleeing from the shark.*");
}
}
------------------------
//This is an interface
public interface Prey {
void flee();
}
-----------------------------
//This is an interface
public interface Predator {

void hunt();

public static void main(String[] args) {


// Polymorphism
Fish fish = new Fish();
Cat cat = new Cat();
Rabbit rabbit = new Rabbit();

Animals[] Animal = { fish, rabbit, cat};

for( Animals i: Animal) {


i.eats();
}
}
-----------------------------------
public class Animals {
public void eats() {
}

}
---------------------------------
public class Rabbit extends Animals {
@Override
public void eats() {
System.out.println("*Rabbits eats.*");
}
}

public static void main(String[] args) {


// Dynamic Polymorphism
Scanner input = new Scanner(System.in);
Animals Animal;

System.out.println("What animal do you want? ");


System.out.print("(1 = Cat) or (2 = Fish) ");
int choice = input.nextInt();

if(choice == 1) {
Animal = new Cat();
Animal.speaks();
} else if ( choice == 0 ) {
Animal = new Fish();
Animal.speaks();
} else {
Animal = new Animals();
System.out.println("Invalid choice.");
Animal.speaks();
}
-----------------------------------
public class Animals {
public void speaks() {
System.out.println("*Mara Kha* in animal language!!!");
}
}
public class Fish extends Animals {
@Override
public void speaks() {
System.out.println("Fish goes *Wiggle*");
}

}
public class Cat extends Animals {
@Override
public void speaks() {
System.out.println("Cat goes *Meow*");
}
}
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);

try {
System.out.print("Enter an integar number : ");
int x = input.nextInt();
System.out.print("Enter an integar number : ");
int y = input.nextInt();

int z = x/y ;
System.out.println("z : "+ z);
}
catch(ArithmeticException i) {
System.out.println("It's an ArithmeticException");
}
catch (InputMismatchException e) {
System.out.println("It's an InputMismatchException");
}
catch(Exception e) {
System.out.println("Invalid Input.Check again.");
}
finally {
input.close();
}
}
}

public class Main {

public static void main(String[] args) {


// if it's not within same project then
// File file1 = new
File("C:/Users/user/Desktop/secret_text.txt");
// Alternate: "C:\\Users\\user\\Desktop\\secret_text.txt"

File file1 = new File("secret_text.txt");

if(file1.exists()) {
System.out.println("That file exists.");
System.out.println(file1.getPath());
System.out.println(file1.getAbsolutePath());
file1.delete();
}
else {
System.out.println("That file doesn't exist.");
}
}
}
// File writing
import java.io.FileWriter;
import java.io.IOException;

public class Main {

public static void main(String[] args) {

try {
FileWriter writer = new FileWriter("poem.txt");
writer.write("Hello, My name is Fatema Islam\n");
writer.write("I am in CSE dept.\n");
writer.append("I am in Dhaka.");
writer.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main{


public static void main(String[] args) throws IOException {

FileReader reader;
try {
reader = new FileReader("art.txt");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
}
}

import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.*;
import java.io.File;

public class Main{


public static void main(String[] args ) throws UnsupportedAudioFileException,
IOException, LineUnavailableException {
Scanner input = new Scanner(System.in);
File file = new File("Adriana_Lima_CC_by_Kottie_Paid(AIF).wav");
AudioInputStream audiostream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audiostream);
clip.start();
String response = input.next();
}
}

// Java Audio
import java.util.Scanner;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class Main {


public static void main(String[] args) throws
UnsupportedAudioFileException, IOException, LineUnavailableException {

Scanner input = new Scanner(System.in);


File file = new File("sweater_weather.wav");

AudioInputStream audiostream =
AudioSystem.getAudioInputStream(file);

Clip clip = AudioSystem.getClip();

clip.open(audiostream);

String choice = "";


while(!choice.equals("Q")) {
System.out.print("Enter your choice: ");
choice = input.nextLine();
choice = choice.toUpperCase();

switch(choice) {
case "P" : clip.start();
break;

case "S" : clip.stop();


break;

case "R" : clip.setMicrosecondPosition(1000);


break;

case "Q" : clip.close();


break;

default : System.out.println("Invalid input.");


}
}
}
}

import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Color;
// init, visibility, size, title, resize,image, close, backgrnd, color
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(420, 500);
frame.setResizable(false);
frame.setTitle("GUI Practice");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon("maki 8.jpg");
frame.setIconImage(icon.getImage());
//frame.getContentPane().setBackground(Color.pink);
frame.getContentPane().setBackground(new Color(0xFFFFFF));
frame.setVisible(true);

}
}

public class Main {


public static void main(String[] args) {
new GUI();
}
}
------------------------
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Color;

public class GUI extends JFrame {


public GUI() {
this.setSize(420, 500);
this.setResizable(false);
this.setTitle("GUI Practice");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon("maki 8.jpg");
this.setIconImage(icon.getImage());
this.getContentPane().setBackground(new Color(0x000000));
this.setVisible(true);
}

import javax.swing.*;
import java.awt.*;
import javax.swing.border.Border;

// JFrame label = editing GUI Display area


// label init,txt,
public class Main {
public static void main(String[] args) {
JLabel label = new JLabel();
ImageIcon image = new ImageIcon("itachi.jpg");
JFrame frame = new JFrame();
Border border = BorderFactory.createLineBorder(Color.RED, 3);
label.setBorder(border);

label.setText("Hello");
label.setIcon(image);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
label.setIconTextGap(10);
label.setForeground(Color.GREEN);
label.setBackground(Color.DARK_GRAY);
label.setOpaque(true);
label.setVerticalAlignment(JLabel.CENTER);
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
//label.setBounds(185,115, 630, 420);// border within frame backgrnd

frame.setTitle("New GUI Window");


ImageIcon icon = new ImageIcon("maki 8.jpg");
frame.setIconImage(icon.getImage());
//frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setSize(1000, 670);
frame.getContentPane().setBackground(new Color(0x000000));
frame.add(label);
frame.pack();// add after add(label) method
frame.setVisible(true);
}
}

//Label
public static void main(String[] args) {
JFrame frame = new JFrame();
ImageIcon image = new ImageIcon("maki 8.jpg");
ImageIcon imageIcon = new ImageIcon("download 1.png");
Border border = BorderFactory.createLineBorder(Color.CYAN, 4); // border color,
thickness

Image n = imageIcon.getImage().getScaledInstance(80,80, Image.SCALE_DEFAULT);


imageIcon = new ImageIcon(n);

JLabel label = new JLabel();


label.setBounds(50, 50, 420 , 420);
label.setText("Can u code?");
label.setIcon(imageIcon);
label.setVerticalTextPosition(JLabel.TOP);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setForeground(Color.GREEN); // set label text color
label.setFont(new Font("Comic Sans MS", Font.ITALIC, 20));
label.setIconTextGap(10);
label.setBackground(Color.BLACK);
label.setOpaque(true);
// display label Background
label.setVerticalAlignment(JLabel.CENTER);
label.setHorizontalAlignment(JLabel.CENTER);

label.setBorder(border);
frame.add(label);

frame.setTitle("Hello");
frame.setIconImage(image.getImage());
frame.setSize(528,528);
frame.setLayout(null);
//if set layout to null then have to set bounds
frame.getContentPane().setBackground(Color.BLACK);
// if pack is used default layout is used by default, frame sie, bound not needed
//frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {


JFrame frame = new JFrame();
ImageIcon image = new ImageIcon("maki 8.jpg");

ImageIcon image1 = new ImageIcon("maki 8.jpg");


Image n1 = image1.getImage().getScaledInstance(80,80,Image.SCALE_DEFAULT);
image1 = new ImageIcon(n1);
JLabel label = new JLabel();
label.setText("Maki Zen'in");
label.setVerticalTextPosition(JLabel.TOP);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setIcon(image1);
label.setBounds(200, 65, 100,120);
// Vertical , HOrizontal allignment not needed during flow layout
label.setBackground(Color.ORANGE);
label.setOpaque(true);

JPanel cyanPanel = new JPanel();


cyanPanel.setBackground(Color.CYAN);
cyanPanel.setBounds(0,0,250,250);
cyanPanel.setLayout(null);

JPanel pinkPanel = new JPanel();


pinkPanel.setBackground(Color.PINK);
pinkPanel.setBounds(250,0,250,250);
pinkPanel.setLayout(null);

JPanel bluePanel = new JPanel();


bluePanel.setBackground(Color.BLUE);
bluePanel.setBounds(0,250,500,250);
bluePanel.setLayout(null);

// frames have border layout


// panel have flowlayout
frame.setTitle("Hello");
frame.setIconImage(image.getImage());
frame.setSize(750,650);
frame.setLayout(null); // have to set bounds
frame.getContentPane().setBackground(Color.BLACK);

frame.add(cyanPanel);
frame.add(pinkPanel);
bluePanel.add(label);
frame.add(bluePanel);

frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public class Main {


public static void main(String[] args ) {
new GUI();
}
}
---------------------------------------------------
import javax.swing.*;
import javax.sound.sampled.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import static javax.sound.sampled.AudioSystem.getAudioInputStream;


import static javax.sound.sampled.AudioSystem.getClip;

public class GUI extends JFrame implements ActionListener {

JButton button;
GUI () {
button =new JButton();
button.setBounds(200,100,100,50);
button.setText("Start music");
button.addActionListener(this);

this.setTitle("GUI Window");
ImageIcon image = new ImageIcon("maki 8.jpg");
this.setIconImage(image.getImage());
this.setLayout(null);
this.setSize(750, 630);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.add(button);
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
System.out.println(“Hello”);

}
}
}

//GUI Button Tutorial

public class Main {


public static void main(String[] args ) {
new GUI();
}
}
---------------------------------------------------
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GUI extends JFrame implements ActionListener {


JButton button;
JLabel label;
GUI () {
label = new JLabel();
ImageIcon image1 = new ImageIcon("maki 1.jpg");
Image n1 = image1.getImage().getScaledInstance(440,650,
Image.SCALE_DEFAULT);
image1 = new ImageIcon(n1);

label.setBounds(200,0,750,650);
label.setIcon(image1);
label.setVisible(false);

ImageIcon image = new ImageIcon("maki 8.jpg");


Image n = image.getImage().getScaledInstance(150,200,
Image.SCALE_DEFAULT);
image = new ImageIcon(n);

button =new JButton();


button.setBounds(0,0,200,250);
button.setText("Start music");
button.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
button.setIcon(image);
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.TOP);
button.setFocusable(false);
button.addActionListener(this);
button.setForeground(Color.DARK_GRAY);
button.setBackground(Color.GRAY);
button.setBorder(BorderFactory.createRaisedSoftBevelBorder());

this.setTitle("GUI Window");
ImageIcon image2 = new ImageIcon("maki 8.jpg");
this.setIconImage(image2.getImage());
this.setLayout(null);
this.setSize(750, 650);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.add(button);
this.add(label);
this.setResizable(false);
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
label.setVisible(true);
}
}
}

public static void main(String[] args) {


ImageIcon imageIcon = new ImageIcon("maki 8.jpg");
JFrame frame = new JFrame();
frame.setTitle("GUI Window");
frame.setIconImage(imageIcon.getImage());
frame.setSize(500,500);
frame.setLayout(new BorderLayout(5,5));

JPanel panel1 = new JPanel();


JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();

panel1.setBackground(Color.GRAY);
panel2.setBackground(Color.LIGHT_GRAY);
panel3.setBackground(Color.DARK_GRAY);
panel4.setBackground(Color.CYAN);
panel5.setBackground(Color.PINK);
panel2.setLayout(new BorderLayout());

panel1.setPreferredSize(new Dimension(50,50));
panel2.setPreferredSize(new Dimension(50,50));
panel3.setPreferredSize(new Dimension(50,50));
panel4.setPreferredSize(new Dimension(50,50));
panel5.setPreferredSize(new Dimension(50,50));
// --------------------------sub panels-----------------------

JPanel panel6 = new JPanel();


JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
JPanel panel9 = new JPanel();
JPanel panel10 = new JPanel();

panel6.setBackground(Color.BLUE);
panel7.setBackground(Color.ORANGE);
panel8.setBackground(Color.RED);
panel9.setBackground(Color.BLACK);
panel10.setBackground(Color.YELLOW);

panel6.setPreferredSize(new Dimension(50,50));
panel7.setPreferredSize(new Dimension(50,50));
panel8.setPreferredSize(new Dimension(50,50));
panel9.setPreferredSize(new Dimension(50,50));
panel10.setPreferredSize(new Dimension(50,50));

panel2.add(panel6, BorderLayout.EAST);
panel2.add(panel7, BorderLayout.WEST);
panel2.add(panel8, BorderLayout.CENTER);
panel2.add(panel9, BorderLayout.NORTH);
panel2.add(panel10, BorderLayout.SOUTH);

// --------------------------sub panels ----------------------

frame.add(panel4, BorderLayout.EAST);
frame.add(panel5, BorderLayout.WEST);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel3, BorderLayout.SOUTH);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String[] args) {


ImageIcon imageIcon = new ImageIcon("maki 8.jpg");
JFrame frame = new JFrame();
frame.setTitle("GUI Window");
frame.setIconImage(imageIcon.getImage());
frame.setSize(500,500);

JPanel panel = new JPanel();


panel.setBackground(Color.LIGHT_GRAY);
panel.setPreferredSize(new Dimension(100,250));
// panels use flow layout by default
panel.setLayout(new FlowLayout());
//FlowLayout.LEADING ,TRAILING where should the button start in a row
// horizontal, vertical spacing
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 10,10));
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
panel.add(new JButton("6"));
panel.add(new JButton("7"));
panel.add(new JButton("8"));
panel.add(new JButton("9"));

frame.add(panel);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setLayout(new GridLayout(3,3,10,10));

frame.add(new JButton("1"));
frame.add(new JButton("2"));
frame.add(new JButton("3"));
frame.add(new JButton("4"));
frame.add(new JButton("5"));
frame.add(new JButton("6"));
frame.add(new JButton("7"));
frame.add(new JButton("8"));
frame.add(new JButton("9"));

frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

public static void main(String[] args) {


JLabel label1 = new JLabel();
label1.setOpaque(true);
label1.setBackground(Color.BLUE);
label1.setBounds(50,50,200,200);

JLabel label2 = new JLabel();


label2.setOpaque(true);
label2.setBackground(Color.CYAN);
label2.setBounds(100,100,200,200);

JLabel label3 = new JLabel();


label3.setOpaque(true);
label3.setBackground(Color.PINK);
label3.setBounds(150,150,200,200);

JLabel label4 = new JLabel();


label4.setOpaque(true);
label4.setBackground(Color.LIGHT_GRAY);
label4.setBounds(200,200,200,200);

// adds like stack


JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0,0,500,500);
layeredPane.add(label3, Integer.valueOf(2));
layeredPane.add(label2, Integer.valueOf(1));
layeredPane.add(label4, Integer.valueOf(3));
layeredPane.add(label1, Integer.valueOf(0));

JFrame frame = new JFrame("JLayeredPane");


frame.add(layeredPane);
frame.setSize(500,500);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public class Main {


public static void main(String[] args) {
launchPage page = new launchPage();
}
}
--------------------------------
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class launchPage implements ActionListener {


JFrame frame = new JFrame();
JButton button= new JButton("New Window");

launchPage() {
button.setBounds(100, 160, 200, 40);
button.setFocusable(false);
button.addActionListener(this);

frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(420, 420);
frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
frame.dispose();
NewWindow myWindow = new NewWindow();
}
}
}
-------------------------------------
import javax.swing.*;
import java.awt.*;

public class NewWindow {


JFrame frame = new JFrame();
JLabel label = new JLabel("Maki Zen'in");
ImageIcon imageIcon = new ImageIcon("maki 8.jpg");
Image n = imageIcon.getImage().getScaledInstance(150,200,Image.SCALE_DEFAULT);

NewWindow() {
imageIcon = new ImageIcon(n);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
label.setIcon(imageIcon);
label.setBounds(110,85,200,250);
label.setFont(new Font(null, Font.PLAIN, 25));
frame.add(label);

frame.setLayout(null);
frame.setSize(420,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
frame1.setSize(420, 420);
frame1.setResizable(false);
frame1.setVisible(true);
}
}

import javax.swing.*;
import java.awt.*;

public class Main {


public static void main(String[] args ) {
JOptionPane jOptionPane = new JOptionPane();
JOptionPane.showMessageDialog(null, "Hello","title",
JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null, "Hello","title",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Hello","title",
JOptionPane.QUESTION_MESSAGE);
JOptionPane.showMessageDialog(null, "Hello","title",
JOptionPane.WARNING_MESSAGE);
JOptionPane.showMessageDialog(null, "Hello","title",
JOptionPane.ERROR_MESSAGE);

System.out.println(JOptionPane.showConfirmDialog(null, "Are you a student?",


"Question Title", JOptionPane.YES_NO_CANCEL_OPTION));;

String confirm = JOptionPane.showInputDialog("Are you an adult?");


JOptionPane.showMessageDialog(null, "Answer : "+ confirm);
// creating custom options
String[] responses = {"Yes, I am","No, I am not", "Mai Zenin"};
ImageIcon image = new ImageIcon("maki 8.jpg");
Image n = image.getImage().getScaledInstance(40,50, Image.SCALE_DEFAULT);
image = new ImageIcon(n);

JOptionPane.showOptionDialog(null,
"Maki Zenin?",
"Message",JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE,image,
responses,0);

}
}

JButton button;
JTextField textField;
NewWindow() {
button = new JButton("submit");
button.addActionListener(this);
button.setFocusable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
textField = new JTextField();
textField.setPreferredSize(new Dimension(250,50));
textField.setFont(new Font("Comic Sans MS", Font.PLAIN, 35));
textField.setForeground(Color.MAGENTA);
textField.setBackground(Color.PINK);
textField.setCaretColor(Color.PINK);
this.add(button);
this.add(textField);
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println(textField.getText());
}

public class launchPage implements ActionListener {

JFrame frame = new JFrame();


JButton button = new JButton("New Window");

launchPage() {
button.setBounds(100,160,200,40);
button.setFocusable(false);
button.addActionListener(this);

frame.add(button);
frame.setLayout(null);

frame.setSize(420,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()== button) {
frame.dispose();
NewWindow myWindow = new NewWindow();
}
}
------------------------------------
public class NewWindow extends JFrame implements ActionListener{
JButton button ;
JCheckBox checkBox;
ImageIcon icon1 = new ImageIcon("maki 8.jpg");
ImageIcon icon2 = new ImageIcon("maki 1.jpg");
Image n1 = icon1.getImage().getScaledInstance(65,80,Image.SCALE_DEFAULT);
Image n2 = icon2.getImage().getScaledInstance(55,80,Image.SCALE_DEFAULT);

NewWindow() {
icon1 = new ImageIcon(n1);
icon2 = new ImageIcon(n2);

button = new JButton();


button.setText("Submit");
button.addActionListener(this);
button.setFocusable(false);

checkBox = new JCheckBox();


checkBox.setText("I am Minju");
checkBox.setFocusable(false);
checkBox.setFont(new Font("Comic Sans MS",Font.PLAIN, 25));
checkBox.setIcon(icon2);
checkBox.setSelectedIcon(icon1);

this.add(button);
this.add(checkBox);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println(checkBox.isSelected());
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy