Sunday, January 31, 2016
Creating a C# application from idea to finished product / Demo /
https://www.youtube.com/watch?v=YxewTI4H2mY
Thursday, January 28, 2016
C# programming Basic 2
// Basic
static void Main(string[] args)
{
string userValue = Console.ReadLine();
string msg = (userValue == "1") ? "new car" : "new job";
Console.WriteLine("You won a {0}", msg);
string zig = "You can get what you want out of life " +
"if you help enough other people get what they want.";
char[] charArray = zig.ToCharArray();
Array.Reverse(charArray);
foreach (char z in charArray)
Console.Write(z + " ");
Console.ReadLine();
}
// Read File
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("Values.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
Console.WriteLine(line);
}
myReader.Close();
Console.ReadLine();
}
// Working with String
static void Main(string[] args)
{
// string myString = "Go to your c:\\drive";
// string myString1 = "My \"so called\" life";
// string myString = string.Format("{0}!", "Bonzai");
// $ string myString = string.Format("{0:C}", 123.45);
// phone number string myString = string.Format("Phone number: {0:(###) ###-###}", 1234567890);
/* string myString = "";
for (int i = 0; i < 100; i++)
{
myString = myString + "--" + i.ToString();
} */
/* StringBuilder myString = new StringBuilder();
for (int i = 0; i < 100; i++)
{
myString.Append("--");
myString.Append(i);
} */
string myString = "That summer we took threes across the board";
/*
myString = myString.Substring(5, 14);
myString = myString.ToUpper();
myString = myString.Replace(" ", "--");
*/
myString = String.Format("Length before: {0} -- After: {1}",
myString.Length, myString.Trim().Length);
Console.WriteLine(myString);
Console.ReadLine();
}
// Working with DateTime
static void Main(string[] args)
{
DateTime myValue = DateTime.Now;
Console.WriteLine(myValue.ToString());
Console.WriteLine(myValue.ToShortDateString());
Console.WriteLine(myValue.ToShortTimeString());
Console.WriteLine(myValue.ToLongDateString());
Console.WriteLine(myValue.ToLongTimeString());
Console.WriteLine(myValue.AddDays(3).ToLongDateString());
Console.WriteLine(myValue.AddHours(3).ToShortTimeString());
Console.WriteLine(myValue.Month.ToString());
DateTime mybirthday = new DateTime(1991, 12, 05);
Console.WriteLine(mybirthday.ToShortDateString());
DateTime myB = DateTime.Parse("05/12/1991");
TimeSpan myA = DateTime.Now.Subtract(myB);
Console.WriteLine(myA.TotalHours);
Console.ReadLine();
}
// Understanding Object
class Program
{
static void Main(string[] args)
{
Car mycar1 = new Car();
mycar1.Make = "Ford";
mycar1.Model = "Raptor";
mycar1.Color = "Red";
mycar1.Year = 2008;
Truck myTruck = new Truck();
myTruck.Make = "Ford";
myTruck.Model = "F969";
myTruck.Year = 2006;
myTruck.Color = "Black";
myTruck.To = 1200;
Console.WriteLine("Here are the Car's details: {0}", mycar1.FormatMe());
Console.WriteLine("Here are the Truck's details: {0}", myTruck.FormatMe());
Console.ReadLine();
}
}
abstract class Vehicle
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string Color { get; set; }
public abstract string FormatMe();
}
sealed class Truck : Vehicle
{
public int To { get; set; }
public override string FormatMe()
{
return String.Format("{0}-{1}-{2}",
this.Make,
this.Model,
this.To);
}
}
class Car : Vehicle
{
public override string FormatMe()
{
return String.Format("{0}-{1}-{2}-{3}",
this.Make,
this.Model,
this.Color,
this.Year);
}
}
// Enum Type
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Type in a superhero's name to see his nickname:");
string userValue = Console.ReadLine();
SuperHero myValue;
if (Enum.TryParse<SuperHero>(userValue, true, out myValue))
{
switch (myValue)
{
case SuperHero.Batman:
Console.WriteLine("Batmaan!");
break;
case SuperHero.Superman:
Console.WriteLine("Man of Steel");
break;
case SuperHero.Green:
Console.WriteLine("Emerald Knight");
break;
default: break;
}
}
Console.ReadLine();
}
}
enum SuperHero
{
Batman,
Superman,
Green
}
}
static void Main(string[] args)
{
string userValue = Console.ReadLine();
string msg = (userValue == "1") ? "new car" : "new job";
Console.WriteLine("You won a {0}", msg);
string zig = "You can get what you want out of life " +
"if you help enough other people get what they want.";
char[] charArray = zig.ToCharArray();
Array.Reverse(charArray);
foreach (char z in charArray)
Console.Write(z + " ");
Console.ReadLine();
}
// Read File
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("Values.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
Console.WriteLine(line);
}
myReader.Close();
Console.ReadLine();
}
// Working with String
static void Main(string[] args)
{
// string myString = "Go to your c:\\drive";
// string myString1 = "My \"so called\" life";
// string myString = string.Format("{0}!", "Bonzai");
// $ string myString = string.Format("{0:C}", 123.45);
// phone number string myString = string.Format("Phone number: {0:(###) ###-###}", 1234567890);
/* string myString = "";
for (int i = 0; i < 100; i++)
{
myString = myString + "--" + i.ToString();
} */
/* StringBuilder myString = new StringBuilder();
for (int i = 0; i < 100; i++)
{
myString.Append("--");
myString.Append(i);
} */
string myString = "That summer we took threes across the board";
/*
myString = myString.Substring(5, 14);
myString = myString.ToUpper();
myString = myString.Replace(" ", "--");
*/
myString = String.Format("Length before: {0} -- After: {1}",
myString.Length, myString.Trim().Length);
Console.WriteLine(myString);
Console.ReadLine();
}
// Working with DateTime
static void Main(string[] args)
{
DateTime myValue = DateTime.Now;
Console.WriteLine(myValue.ToString());
Console.WriteLine(myValue.ToShortDateString());
Console.WriteLine(myValue.ToShortTimeString());
Console.WriteLine(myValue.ToLongDateString());
Console.WriteLine(myValue.ToLongTimeString());
Console.WriteLine(myValue.AddDays(3).ToLongDateString());
Console.WriteLine(myValue.AddHours(3).ToShortTimeString());
Console.WriteLine(myValue.Month.ToString());
DateTime mybirthday = new DateTime(1991, 12, 05);
Console.WriteLine(mybirthday.ToShortDateString());
DateTime myB = DateTime.Parse("05/12/1991");
TimeSpan myA = DateTime.Now.Subtract(myB);
Console.WriteLine(myA.TotalHours);
Console.ReadLine();
}
// Understanding Object
class Program
{
static void Main(string[] args)
{
Car mycar1 = new Car();
mycar1.Make = "Ford";
mycar1.Model = "Raptor";
mycar1.Color = "Red";
mycar1.Year = 2008;
Truck myTruck = new Truck();
myTruck.Make = "Ford";
myTruck.Model = "F969";
myTruck.Year = 2006;
myTruck.Color = "Black";
myTruck.To = 1200;
Console.WriteLine("Here are the Car's details: {0}", mycar1.FormatMe());
Console.WriteLine("Here are the Truck's details: {0}", myTruck.FormatMe());
Console.ReadLine();
}
}
abstract class Vehicle
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string Color { get; set; }
public abstract string FormatMe();
}
sealed class Truck : Vehicle
{
public int To { get; set; }
public override string FormatMe()
{
return String.Format("{0}-{1}-{2}",
this.Make,
this.Model,
this.To);
}
}
class Car : Vehicle
{
public override string FormatMe()
{
return String.Format("{0}-{1}-{2}-{3}",
this.Make,
this.Model,
this.Color,
this.Year);
}
}
// Enum Type
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Type in a superhero's name to see his nickname:");
string userValue = Console.ReadLine();
SuperHero myValue;
if (Enum.TryParse<SuperHero>(userValue, true, out myValue))
{
switch (myValue)
{
case SuperHero.Batman:
Console.WriteLine("Batmaan!");
break;
case SuperHero.Superman:
Console.WriteLine("Man of Steel");
break;
case SuperHero.Green:
Console.WriteLine("Emerald Knight");
break;
default: break;
}
}
Console.ReadLine();
}
}
enum SuperHero
{
Batman,
Superman,
Green
}
}
Sunday, January 24, 2016
C# programming Basic 1
// BASIC
static void Main(string[] args)
{
string name2 = "Zoloo";
string name3 = null;
string randStr = "Here are some random character";
Console.WriteLine("Whats your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
var aname = "Tom";
Console.WriteLine("var is: {0}", aname.GetTypeCode());
Console.ReadKey();
if (aname.GetTypeCode().ToString() == "String")
goto Cute;
Cute: Console.WriteLine("Hehe");
do
{
Console.WriteLine("Enter number:");
name = Console.ReadLine();
}
while (!name.Equals("15"));
foreach (char c in randStr)
{
Console.Write(c + " ");
}
Console.WriteLine("is empty " + String.IsNullOrEmpty(name3));
Console.WriteLine("is empty " + String.IsNullOrWhiteSpace(name2));
StringBuilder sb = new StringBuilder();
sb.Append("This is the first sentence.");
sb.AppendFormat("My name is {0} and I live in {1}", "Derek", "Pennsylvania");
sb.Replace("a", "e");
sb.Remove(5, 7);
Console.WriteLine(sb.ToString());
int[] randNumArr;
int[] randNum = new int[5];
int[] arr2 = { 1, 2, 3, 4, 5 };
Console.WriteLine("Where is 1 " + Array.IndexOf(arr2, 1));
string[] names = { "Tom", "Paul", "Sally" };
string nameStr = string.Join(",", names);
Console.WriteLine(names.ToString());
// exit
Console.ReadKey();
}
// LIST EXAMPLE
static void Main(string[] args)
{
List<int> numList = new List<int>();
numList.Add(5);
numList.Add(15);
numList.Add(25);
int[] array = { 1, 2, 3, 4, 5 };
numList.AddRange(array);
List<int> numList2 = new List<int>(array);
List<int> numList3 = new List<int>(new int[] { 1, 2, 3, 4 });
numList.Insert(1, 10);
numList.Remove(25); /*
numList.RemoveAt(2); */
for (int i = 0; i < numList.Count; i++)
Console.Write(numList[i] + " ");
Console.Write("\nList 2:\n");
for (int i = 0; i < numList3.Count; i++)
Console.Write(numList3[i] + " ");
Console.ReadKey();
}
// FILE EXAMPLE
static void Main(string[] args)
{
string[] custs = new string[] { "Tom", "Paul", "Greg" };
using (StreamWriter sw = new StreamWriter("custs.txt"))
{
foreach (string cust in custs)
sw.WriteLine(cust);
}
string custName = "";
using (StreamReader sr = new StreamReader("custs.txt"))
{
while ((custName = sr.ReadLine()) != null)
Console.WriteLine(custName);
}
Console.ReadKey();
}
static void Main(string[] args)
{
string name2 = "Zoloo";
string name3 = null;
string randStr = "Here are some random character";
Console.WriteLine("Whats your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
var aname = "Tom";
Console.WriteLine("var is: {0}", aname.GetTypeCode());
Console.ReadKey();
if (aname.GetTypeCode().ToString() == "String")
goto Cute;
Cute: Console.WriteLine("Hehe");
do
{
Console.WriteLine("Enter number:");
name = Console.ReadLine();
}
while (!name.Equals("15"));
foreach (char c in randStr)
{
Console.Write(c + " ");
}
Console.WriteLine("is empty " + String.IsNullOrEmpty(name3));
Console.WriteLine("is empty " + String.IsNullOrWhiteSpace(name2));
StringBuilder sb = new StringBuilder();
sb.Append("This is the first sentence.");
sb.AppendFormat("My name is {0} and I live in {1}", "Derek", "Pennsylvania");
sb.Replace("a", "e");
sb.Remove(5, 7);
Console.WriteLine(sb.ToString());
int[] randNumArr;
int[] randNum = new int[5];
int[] arr2 = { 1, 2, 3, 4, 5 };
Console.WriteLine("Where is 1 " + Array.IndexOf(arr2, 1));
string[] names = { "Tom", "Paul", "Sally" };
string nameStr = string.Join(",", names);
Console.WriteLine(names.ToString());
// exit
Console.ReadKey();
}
// LIST EXAMPLE
static void Main(string[] args)
{
List<int> numList = new List<int>();
numList.Add(5);
numList.Add(15);
numList.Add(25);
int[] array = { 1, 2, 3, 4, 5 };
numList.AddRange(array);
List<int> numList2 = new List<int>(array);
List<int> numList3 = new List<int>(new int[] { 1, 2, 3, 4 });
numList.Insert(1, 10);
numList.Remove(25); /*
numList.RemoveAt(2); */
for (int i = 0; i < numList.Count; i++)
Console.Write(numList[i] + " ");
Console.Write("\nList 2:\n");
for (int i = 0; i < numList3.Count; i++)
Console.Write(numList3[i] + " ");
Console.ReadKey();
}
// FILE EXAMPLE
static void Main(string[] args)
{
string[] custs = new string[] { "Tom", "Paul", "Greg" };
using (StreamWriter sw = new StreamWriter("custs.txt"))
{
foreach (string cust in custs)
sw.WriteLine(cust);
}
string custName = "";
using (StreamReader sr = new StreamReader("custs.txt"))
{
while ((custName = sr.ReadLine()) != null)
Console.WriteLine(custName);
}
Console.ReadKey();
}
Tuesday, January 19, 2016
C programming Basic 1
Basic IO:
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
char password[15];
printf("Enter your password:");
fgets(password, 15, stdin);
//
scanf("%s", password);
printf("The password is :");
puts(password);
return 0;
}
Random operator:
#include <stdio.h>
#include <stdlib.h>
int main()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r;
srand((unsigned)time(NULL));
r = rand();
printf("%d is a random
number.\n",r);
return 0;
}
Do …. While:
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
char a, b;
puts("Enter letter: ");
scanf("%c", &b);
a = 'a';
do{
putchar(a);
if(a==b) break;
a++;
} while(a!='z'+1);
return 0;
}
Work with char:
#include
<stdio.h>
#include
<stdlib.h>
#include
<ctype.h>
int main()
{
int ch;
do{
ch=getchar();
ch = toupper(ch);
putchar(ch);
} while (ch!='\n');
return 0;
}
Working with char:
#include
<stdio.h>
#include
<stdlib.h>
#include
<ctype.h>
int main()
{
int ch;
char st[100];
int len;
fgets(st, 100, stdin);
len = strlen(st);
printf("%d", len);
return 0;
}
Working with array:
#include
<stdio.h>
#include
<stdlib.h>
#include
<ctype.h>
int main()
{
char first[] = "I would like to go
USA";
int n=0;
while(first[n]!='\0')
{
putchar(first[n]);
n++;
}
return 0;
}
Get value press enter:
#include <stdio.h>Get value press enter:
int main ( void ){
int a[100], i=0;
int j;
char again;
while (again != '\n') {
scanf("%d", &a[i++]);
again=getchar();
}
for(j = 0; j<i; j++) printf("%d ", a[j]);
return 0;
}
Struct Example:
#include <stdio.h>
int main ( void ){
struct date{
int year;
int month;
int day;
};
struct record {
char name[32];
struct date birthday;
};
struct record president;
strcpy(president.name,"Brad Pit");
president.birthday.year = 1991;
president.birthday.month = 6;
president.birthday.day = 1;
printf("My friend %s was born on %d/%d/%d\n", president.name, president.birthday.year,
president.birthday.month, president.birthday.day);
return 0;
}
Time:
#include <stdio.h>
#include <time.h>
int main ( void ){
time_t now;
struct tm *right_now;
time(&now);
right_now=localtime(&now);
printf("Today is %d/%d at %d:%d\n", right_now->tm_mon+1,
right_now->tm_mday, right_now->tm_hour, right_now->tm_min);
return 0;
}
Pointer and Array:
example 1: #include <stdio.h>
#include <time.h>
int main ( void ){
int array[]={11, 12, 13, 14};
int x;
int *aptr;
aptr = array;
for(x = 0; x<4; x++)
printf("Element %d: %d\n", x+1, *aptr++);
aptr = array;
*(aptr +2) = 0;
for(x = 0; x<4; x++)
printf("Element %d: %d\n", x+1, array[x]);
return 0;
}
example 2:
#include <stdio.h>
#include <time.h>
int main ( void ){
char *string="I'm just a normal string.\n";
int x =0;
while(*string)
{
putchar(*string++);
}
return 0;
}
Pointer Function:
example 1:
example 1: #include <stdio.h>
#include <time.h>
int main ( void ){
int array[]={11, 12, 13, 14};
int x;
int *aptr;
aptr = array;
for(x = 0; x<4; x++)
printf("Element %d: %d\n", x+1, *aptr++);
aptr = array;
*(aptr +2) = 0;
for(x = 0; x<4; x++)
printf("Element %d: %d\n", x+1, array[x]);
return 0;
}
example 2:
#include <stdio.h>
#include <time.h>
int main ( void ){
char *string="I'm just a normal string.\n";
int x =0;
while(*string)
{
putchar(*string++);
}
return 0;
}
Pointer Function:
example 1:
#include <stdio.h>
#include <time.h>
void minus10(int *v){
*v = *v - 10;
}
int main ( void ){
int v = 100;
printf("Value is %d\n", v);
minus10(&v);
printf("Value is %d\n", v);
return 0;
}
example 2:
#include <stdio.h>
#include <string.h>
char *longer(char *s1){
while(*s1){
*s1 = toupper(*s1);
*s1++;
}
}
int main ( void ){
char string[64];
printf("Type some text:");
fgets(string, 64, stdin);
printf("You typed:\n%s\n", string);
longer(string);
printf("If you were shouting, you'd typed: \n%s\n", string);
return 0;
}
example 3:
#include <stdio.h>
#include <string.h>
char *encrypt(char *input){
static char output[64];
int x=0;
while(*input){
if(isalpha(*input))
output[x]=*input+1;
else output[x]=*input;
x++;
input++;
}
return output;
}
int main ( void ){
char *instructions = "Deliver the package to Berlin";
printf("Here are your secret instructions:\n%s\n",encrypt(instructions));
return 0;
}
#include <stdio.h>
#include <string.h>
char *encrypt(char *input){
static char output[64];
int x=0;
while(*input){
if(isalpha(*input))
output[x]=*input+1;
else output[x]=*input;
x++;
input++;
}
return output;
}
int main ( void ){
char *instructions = "Deliver the package to Berlin";
printf("Here are your secret instructions:\n%s\n",encrypt(instructions));
return 0;
}
Linked List Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stats{
int account;
float balance;
struct stats *next;
};
void fill_structure(struct stats *s);
struct stats *create(void);
int main ( void ){
struct stats *first;
struct stats *current;
struct stats *new;
int x;
first = create();
current = first;
for(x = 0; x<5; x++){
if(x==0){
first=create();
current=first;
}
else {
new = create();
current->next = new;
current = new;
}
fill_structure(current);
}
current->next=NULL;
current = first;
while(current){
printf("Account %05d:\t$%0.2f\n",current->account, current->balance);
current=current->next;
}
return 0;
}
void fill_structure(struct stats *s){
printf("Account number:");
scanf("%d", &s->account);
printf("Balance: $");
scanf("%f", &s->balance);
s->next=NULL;
}
struct stats *create(void){
struct stats *baby;
baby = (struct stats *)malloc(sizeof(struct stats));
if(baby ==NULL){
puts("Memory error");
exit(1);
}
return baby;
};
#include <stdlib.h>
#include <string.h>
struct stats{
int account;
float balance;
struct stats *next;
};
void fill_structure(struct stats *s);
struct stats *create(void);
int main ( void ){
struct stats *first;
struct stats *current;
struct stats *new;
int x;
first = create();
current = first;
for(x = 0; x<5; x++){
if(x==0){
first=create();
current=first;
}
else {
new = create();
current->next = new;
current = new;
}
fill_structure(current);
}
current->next=NULL;
current = first;
while(current){
printf("Account %05d:\t$%0.2f\n",current->account, current->balance);
current=current->next;
}
return 0;
}
void fill_structure(struct stats *s){
printf("Account number:");
scanf("%d", &s->account);
printf("Balance: $");
scanf("%f", &s->balance);
s->next=NULL;
}
struct stats *create(void){
struct stats *baby;
baby = (struct stats *)malloc(sizeof(struct stats));
if(baby ==NULL){
puts("Memory error");
exit(1);
}
return baby;
};
Sunday, January 10, 2016
Java basic project: Pizza ordering system
Энэ удаагийн пост бичлэгээр Жава дээр Тред ашиглан хялбар прожест хийлээ. Энэхүү прожест нь пизза захиалгын систем ба хэрэглэгч ирээд пиззагаас захиалгаад өгөхөд тухайн пизза захиалгын дагуу тогоочид очиж боловсруулсаны дараа хэрэглэгчид тухайн заасан хугацаа / тред / -ны дараа хэрэглэгчид очих юм.
Бидэнд нийт 3 класс, 1 интерфэйс хэрэгтэй болно.
Класс:
1. Тогооч класс - Chef class
2. Пизза класс - Pizza class
3. Хэрэглэгчийн хүлээн класс - UI class
2. Пизза класс - Pizza class
3. Хэрэглэгчийн хүлээн класс - UI class
Интерфэйс:
1. Тогоочын хүлээн авах интерфэйс - ChefListener interface
1. Pizza class
public class Pizza {
private String name;
private double price;
private double cookingTime; // in seconds
public Pizza(String name, double price, double cookingTime) {
this.name = name;
this.price = price;
this.cookingTime = cookingTime;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public double getCookingTime() {
return cookingTime;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public void setCookingTime(double cookingTime) {
this.cookingTime = cookingTime;
}
}
2. Chef class - Тредээс удамшина
public class Chef extends Thread{
Pizza pizza;
ChefListener listener;
public Chef(Pizza pizza, ChefListener listener) {
this.pizza = pizza;
this.listener = listener;
}
@Override
public void run() {
try {
Thread.sleep((long) (pizza.getCookingTime() * 1000));
} catch (InterruptedException ex) {
ex.printStackTrace();
}
listener.pizzaCooked(pizza);
}
}
3. ChefListener interface
public interface ChefListener {
public void pizzaCooked( Pizza pizza );
}
4. UI class нь ChefListener -с удамшина
public class UI implements ChefListener {
public static void main(String[] args) {
UI ui = new UI();
for (int i = 0; i < 3; i++) {
ui.prompt();
}
}
public void prompt() {
Pizza ct = new Pizza("Cheese and Tomato", 2, 5);
Pizza bbq = new Pizza("BBQ", 5, 10);
Pizza vs = new Pizza("Vegetarian Supreme", 12, 8);
Pizza[] availablePizzas = new Pizza[]{ct, bbq, vs};
System.out.println("Please choose which pizza do you want: ");
for (Pizza p : availablePizzas) {
System.out.println(p.getName());
}
int choice = Integer.parseInt(JOptionPane.showInputDialog("Choose your pizza: "));
Pizza selection = availablePizzas[choice];
Chef chef = new Chef(selection, this);
chef.start();
}
@Override
public void pizzaCooked(Pizza pizza) {
System.out.println(pizza.getName() + " pizza has been cooked. Enjoy!");
}
}
C# basic Notepad Example 1
Form1 class:
namespace NotepadTutorial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sv = new SaveFileDialog();
sv.Filter = "Text Document(*.txt)|*.txt|All Files(*.*)|*.*";
if (sv.ShowDialog() == DialogResult.OK)
richTextBox1.SaveFile(sv.FileName, RichTextBoxStreamType.PlainText);
this.Text = sv.FileName;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Paste();
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Undo();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Redo();
}
private void fontToolStripMenuItem1_Click(object sender, EventArgs e)
{
FontDialog fd = new FontDialog();
fd.Font = richTextBox1.SelectionFont;
if (fd.ShowDialog() == DialogResult.OK)
richTextBox1.SelectionFont = fd.Font;
}
private void backgroundColorToolStripMenuItem_Click(object sender, EventArgs e)
{
ColorDialog cr = new ColorDialog();
if (cr.ShowDialog() == DialogResult.OK)
richTextBox1.BackColor = cr.Color;
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Ver 1.0.0\nCreated by Zoloo");
}
}
}
Result:
namespace NotepadTutorial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sv = new SaveFileDialog();
sv.Filter = "Text Document(*.txt)|*.txt|All Files(*.*)|*.*";
if (sv.ShowDialog() == DialogResult.OK)
richTextBox1.SaveFile(sv.FileName, RichTextBoxStreamType.PlainText);
this.Text = sv.FileName;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Paste();
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Undo();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Redo();
}
private void fontToolStripMenuItem1_Click(object sender, EventArgs e)
{
FontDialog fd = new FontDialog();
fd.Font = richTextBox1.SelectionFont;
if (fd.ShowDialog() == DialogResult.OK)
richTextBox1.SelectionFont = fd.Font;
}
private void backgroundColorToolStripMenuItem_Click(object sender, EventArgs e)
{
ColorDialog cr = new ColorDialog();
if (cr.ShowDialog() == DialogResult.OK)
richTextBox1.BackColor = cr.Color;
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Ver 1.0.0\nCreated by Zoloo");
}
}
}
Result:
C# connect to Local Database Example 2
1. Шинэ прожест үүсгэнэ
2. Add Server-based Database - Database.mdf
3. Add new Table
Form1 class:
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\zoljargal\documents\visual studio 2012\Projects\LocalDatabaseTutorial2\LocalDatabaseTutorial2\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
cn.Open();
cmd.CommandText = "insert into Info(Id, Name) values('" + textBox1.Text +"', '" + textBox2.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record inserted!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
public void loadList()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "select * from info";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
loadList();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textBox1.Text = listBox1.SelectedItem.ToString();
textBox2.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
cn.Open();
cmd.CommandText = "delete from info where Id ='" + textBox1.Text + "' and Name = '" + textBox2.Text + "'";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record deleted!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "" && listBox1.SelectedIndex != -1)
{
cn.Open();
cmd.CommandText = "update info set Id = '" + textBox1.Text + "', Name = '" + textBox2.Text + "' where Id = '" + listBox1.SelectedItem.ToString() + "' and Name = '" + listBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record Updated!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
}
}
Result:
2. Add Server-based Database - Database.mdf
3. Add new Table
Form1 class:
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\zoljargal\documents\visual studio 2012\Projects\LocalDatabaseTutorial2\LocalDatabaseTutorial2\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
cn.Open();
cmd.CommandText = "insert into Info(Id, Name) values('" + textBox1.Text +"', '" + textBox2.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record inserted!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
public void loadList()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "select * from info";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
loadList();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textBox1.Text = listBox1.SelectedItem.ToString();
textBox2.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
cn.Open();
cmd.CommandText = "delete from info where Id ='" + textBox1.Text + "' and Name = '" + textBox2.Text + "'";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record deleted!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "" && listBox1.SelectedIndex != -1)
{
cn.Open();
cmd.CommandText = "update info set Id = '" + textBox1.Text + "', Name = '" + textBox2.Text + "' where Id = '" + listBox1.SelectedItem.ToString() + "' and Name = '" + listBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record Updated!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
}
}
Result:
C# connect to Local Database Example 1
1. Шинэ прожест үүсгэнэ.
2. Add Local Database - Database.sdf
3. Add new Table
4. Add static class
SQLFunctions static class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
using System.Windows.Forms;
namespace LocalDatabaseTutorial
{
static class SQLFunctions
{
static private SqlCeConnection connection = new SqlCeConnection(@"Data Source=|DataDirectory|\Database.sdf");
static public void Refresh(DataGridView dgv)
{
try
{
connection.Open();
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter("select * from [Table]", connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dgv.DataSource = dataTable;
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Insert(string username)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("insert into[Table] values(@username)", connection);
commandInsert.Parameters.Add("@username", username);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Delete(string username)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("delete from [Table] where username = @username", connection);
commandInsert.Parameters.Add("@username", username);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Update(string oldname, string newname)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("update [Table] set username = @newname where username = @oldname", connection);
commandInsert.Parameters.Add("@newname", newname);
commandInsert.Parameters.Add("@oldname", oldname);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
}
}
Form1 class:
private void Form1_Load(object sender, EventArgs e)
{
SQLFunctions.Refresh(this.dataGridView1);
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
SQLFunctions.Insert(textBox1.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text != "")
{
SQLFunctions.Delete(textBox2.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox3.Text != "" && textBox4.Text != "")
{
SQLFunctions.Update(textBox3.Text, textBox4.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
}
}
Result:
2. Add Local Database - Database.sdf
3. Add new Table
4. Add static class
SQLFunctions static class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
using System.Windows.Forms;
namespace LocalDatabaseTutorial
{
static class SQLFunctions
{
static private SqlCeConnection connection = new SqlCeConnection(@"Data Source=|DataDirectory|\Database.sdf");
static public void Refresh(DataGridView dgv)
{
try
{
connection.Open();
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter("select * from [Table]", connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dgv.DataSource = dataTable;
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Insert(string username)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("insert into[Table] values(@username)", connection);
commandInsert.Parameters.Add("@username", username);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Delete(string username)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("delete from [Table] where username = @username", connection);
commandInsert.Parameters.Add("@username", username);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
static public void Update(string oldname, string newname)
{
try
{
connection.Open();
SqlCeCommand commandInsert = new SqlCeCommand("update [Table] set username = @newname where username = @oldname", connection);
commandInsert.Parameters.Add("@newname", newname);
commandInsert.Parameters.Add("@oldname", oldname);
commandInsert.ExecuteNonQuery();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
}
}
}
}
Form1 class:
private void Form1_Load(object sender, EventArgs e)
{
SQLFunctions.Refresh(this.dataGridView1);
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
SQLFunctions.Insert(textBox1.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text != "")
{
SQLFunctions.Delete(textBox2.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox3.Text != "" && textBox4.Text != "")
{
SQLFunctions.Update(textBox3.Text, textBox4.Text);
SQLFunctions.Refresh(this.dataGridView1);
}
}
}
}
Result:
Monday, January 4, 2016
Java File Example
1: How to reaad text file
public class javareadfile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String line = null;
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
2: How to read and write text files
public class myFile {
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
}
}
3: How to copy, move and delete files in Java
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
// file exists?
System.out.println("file exists?: " + Files.exists(pathtoFile));
Path pathtoFile2 = Paths.get("file2.txt");
// move file
Files.move(pathtoFile, pathtoFile2, StandardCopyOption.REPLACE_EXISTING);
System.out.println("file exists?: " + Files.exists(pathtoFile));
// copy file
Files.copy(pathtoFile2, pathtoFile);
// delete file
Files.delete(pathtoFile);
Files.delete(pathtoFile2);
}
}
4: How to get free, available and total disk space in Java
public class javadisk {
public static void main(String[] args) throws IOException{
FileStore fs = Files.getFileStore(Paths.get("c:/"));
long totalSpaceInBytes = fs.getTotalSpace();
long freeSpaceInBytes = fs.getUsableSpace();
long usedSpaceInBytes = totalSpaceInBytes - freeSpaceInBytes;
System.out.println("total space in GB: " + (totalSpaceInBytes/1024/1024/1024));
System.out.println("free space in GB: " + (freeSpaceInBytes/1024/1024/1024));
System.out.println("used space in GB: " + (usedSpaceInBytes/1024/1024/1024));
}
}
public class javareadfile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String line = null;
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
2: How to read and write text files
public class myFile {
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
}
}
3: How to copy, move and delete files in Java
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
// file exists?
System.out.println("file exists?: " + Files.exists(pathtoFile));
Path pathtoFile2 = Paths.get("file2.txt");
// move file
Files.move(pathtoFile, pathtoFile2, StandardCopyOption.REPLACE_EXISTING);
System.out.println("file exists?: " + Files.exists(pathtoFile));
// copy file
Files.copy(pathtoFile2, pathtoFile);
// delete file
Files.delete(pathtoFile);
Files.delete(pathtoFile2);
}
}
4: How to get free, available and total disk space in Java
public class javadisk {
public static void main(String[] args) throws IOException{
FileStore fs = Files.getFileStore(Paths.get("c:/"));
long totalSpaceInBytes = fs.getTotalSpace();
long freeSpaceInBytes = fs.getUsableSpace();
long usedSpaceInBytes = totalSpaceInBytes - freeSpaceInBytes;
System.out.println("total space in GB: " + (totalSpaceInBytes/1024/1024/1024));
System.out.println("free space in GB: " + (freeSpaceInBytes/1024/1024/1024));
System.out.println("used space in GB: " + (usedSpaceInBytes/1024/1024/1024));
}
}
Java Thread Example 2
Using Thread
Concurrency and simple thread synchronization
/ Тред зэрэг ачаалах /
/ Тред зэрэг ачаалах /
Энгийн хэвлэх функц:
public synchronized void doStuff(String threadname){
jTextArea1.append(threadname + " access started...\n");
jTextArea1.append("Doing stuff...\n");
jTextArea1.append(threadname + " access finished...\n");
}
Товчны дарах үзэгдэл дээр бичих:
for(int i = 0; i<10; i++){
Thread t1 = new Thread(){
public void run() { doStuff("thread1"); } };
Thread t2 = new Thread(){
public void run(){ doStuff("thread2"); } };
t1.start();
t2.start();
}
Үр дүн:
synchronized ашиглаагүй:
synchronized ашиглаагүй:
Sunday, January 3, 2016
Java Thread Example 1
1: How to Create Threads in Java by Extending Thread Class
class MyClass extends Thread{
public void run(){
for(int i = 0; i<10; i++)
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class JavaThreadExample {
public static void main(String[] args) {
// TODO code application logic here
MyClass mc = new MyClass();
mc.start();
MyClass mc1 = new MyClass();
mc1.start();
}
}
2: Creating Java Threads by implementing Runnable Interface
class MyClass implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyClass());
Thread t2 = new Thread(new MyClass());
t1.start();
t2.start();
// How to create thread inside main class
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
t3.start();
}
}
3: Java Thread.join() Method and Synchronized Method
public class MyThreadJoin {
private static int count = 0;
public synchronized static void counter() {
count++;
}
public static void main(String[] args) {
try {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Value:" + count);
} catch (InterruptedException ex) {
Logger.getLogger(MyThreadJoin.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class MyClass extends Thread{
public void run(){
for(int i = 0; i<10; i++)
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class JavaThreadExample {
public static void main(String[] args) {
// TODO code application logic here
MyClass mc = new MyClass();
mc.start();
MyClass mc1 = new MyClass();
mc1.start();
}
}
2: Creating Java Threads by implementing Runnable Interface
class MyClass implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyClass());
Thread t2 = new Thread(new MyClass());
t1.start();
t2.start();
// How to create thread inside main class
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
t3.start();
}
}
3: Java Thread.join() Method and Synchronized Method
public class MyThreadJoin {
private static int count = 0;
public synchronized static void counter() {
count++;
}
public static void main(String[] args) {
try {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i++) {
counter();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Value:" + count);
} catch (InterruptedException ex) {
Logger.getLogger(MyThreadJoin.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Java GUI Basic 3
EXAMPLE 1:
private ArrayList<ArrayList<String>> md = new ArrayList<ArrayList<String>>();
private int trust;
public HybridMD(int trust){
this.trust = trust;
}
public void addRow(ArrayList<String> row){
if(row.size() == trust) md.add(row);
else throw new IllegalArgumentException("Row ist't trusted. Should contain values: " + trust);
}
public String get(int row, int column){
return md.get(row).get(column);
}
public int getRowCount(){
return md.size();
}
public int getColumnCount(){
return trust;
}
}
NEWJFRAME
HybridMD md = new HybridMD(3);
Button:
String name = jTextField1.getText();
String surname = jTextField2.getText();
String age = jTextField3.getText();
ArrayList<String> row = new ArrayList<String>();
row.add(name);
row.add(surname);
row.add(age);
// error Row ist't trusted. Should contain values: 3
// row.add(age);
md.addRow(row);
jTextArea1.setText("");
for(int i = 0; i<md.getRowCount(); i++){
for(int j = 0; j<md.getColumnCount(); j++)
jTextArea1.append(md.get(i, j) + "\t");
jTextArea1.append("\n");
}
Result:

EXAMPLE 2:
Using String Tokenizer Example:
Гараас оруулсан текстийн таслалын тоог арилгаж хэвлэх:
Creating Secure Dynamic Multi-Dimensional Array
public class HybridMD {private ArrayList<ArrayList<String>> md = new ArrayList<ArrayList<String>>();
private int trust;
public HybridMD(int trust){
this.trust = trust;
}
public void addRow(ArrayList<String> row){
if(row.size() == trust) md.add(row);
else throw new IllegalArgumentException("Row ist't trusted. Should contain values: " + trust);
}
public String get(int row, int column){
return md.get(row).get(column);
}
public int getRowCount(){
return md.size();
}
public int getColumnCount(){
return trust;
}
}
NEWJFRAME
HybridMD md = new HybridMD(3);
Button:
String name = jTextField1.getText();
String surname = jTextField2.getText();
String age = jTextField3.getText();
ArrayList<String> row = new ArrayList<String>();
row.add(name);
row.add(surname);
row.add(age);
// error Row ist't trusted. Should contain values: 3
// row.add(age);
md.addRow(row);
jTextArea1.setText("");
for(int i = 0; i<md.getRowCount(); i++){
for(int j = 0; j<md.getColumnCount(); j++)
jTextArea1.append(md.get(i, j) + "\t");
jTextArea1.append("\n");
Result:

EXAMPLE 2:
Using String Tokenizer Example:
Гараас оруулсан текстийн таслалын тоог арилгаж хэвлэх:
Товчны дарах
үзэгдэл дээр:
String inp =
JOptionPane.showInputDialog("Enter keywords separated by comma:");
StringTokenizer st = new StringTokenizer(inp, ",");
JOptionPane.showMessageDialog(this, st.countTokens());
while(st.hasMoreTokens()){
jTextArea1.append(st.nextToken().trim() + " "); }
jTextArea1.append("\n");
Үр дүн:
Үр дүн:
Java GUI Basic 2
Example 1:
Өнөөдрийн пост бичлэгээр netbeans ашиглан хялбархан програм хийх талаар оруулъя. Уг програм нь JFrame form ашиглан JTable-д өгөгдөл нэмэх, засах, устгах жишээ юм.
Өнөөдрийн пост бичлэгээр netbeans ашиглан хялбархан програм хийх талаар оруулъя. Уг програм нь JFrame form ашиглан JTable-д өгөгдөл нэмэх, засах, устгах жишээ юм.
1. Эхлээд дараах кодыг бичъе: / DemoTable бол классын нэр юм. /
String[] data = new String[2];
DefaultTableModel model;
public
DemoTable() {
initComponents();
model = new DefaultTableModel();
model.addColumn("Name");
model.addColumn("Team");
}
2. Нэмэх товчны код:
data[0] = JOptionPane.showInputDialog("Enter
name:");
data[1] =
JOptionPane.showInputDialog("Enter team:");
model.addRow(new Object[]{data[0],
data[1]});
jTable1.setModel(model);
3.
Засах товчны код:
data[0] =
JOptionPane.showInputDialog("Change name:");
data[1] =
JOptionPane.showInputDialog("Change team:");
jTable1.getModel().setValueAt(data[0],
jTable1.getSelectedRow(), 0);
jTable1.getModel().setValueAt(data[1],
jTable1.getSelectedRow(), 1);
4. Устгах товчны код:
//
//
//
//
//
//
Одоо дараах
програмыг өөр хэлбэрээр / массив ашиглан динамик шинжтэй / дахин зохиоё.
1.
Дараах хоёр хувьсагчийг гишүүн хувьсагчаар
нэмлээ.
Object[][] data = null;
String[] columnNames = new String[2];
Object[][] data = null;
String[] columnNames = new String[2];
2.
Хүснэгт
үүсгэх товчны код: / instantiate table button /
columnNames[0] = "Name";
columnNames[1] = "Team";
data = new Object[1][2];
data[0][0] = JOptionPane.showInputDialog("Enter name:");
data[0][1] = JOptionPane.showInputDialog("Enter team:");
jTable1.setModel(new DefaultTableModel(data, columnNames));
columnNames[0] = "Name";
columnNames[1] = "Team";
data = new Object[1][2];
data[0][0] = JOptionPane.showInputDialog("Enter name:");
data[0][1] = JOptionPane.showInputDialog("Enter team:");
jTable1.setModel(new DefaultTableModel(data, columnNames));
3.
Мөр
нэмэх товчны код:
Object[][] temp = new Object[data.length+1][2];
for( int i = 0; i<data.length; i++){
Object[][] temp = new Object[data.length+1][2];
for( int i = 0; i<data.length; i++){
temp[i][0] = data[i][0];
temp[i][1] = data[i][1];
}
temp[data.length][0] = JOptionPane.showInputDialog("Enter name:");
temp[data.length][0] = JOptionPane.showInputDialog("Enter name:");
temp[data.length][1] =
JOptionPane.showInputDialog("Enter team:");
data = temp;
jTable1.setModel(new
DefaultTableModel(temp, columnNames));
4.
Мөр
засах товчны код:
if(jTable1.getSelectedRow()>=0){
if(jTable1.getSelectedRow()>=0){
String name = JOptionPane.showInputDialog("Change
name:");
String team =
JOptionPane.showInputDialog("Change team:");
data[jTable1.getSelectedRow()][0] = name;
data[jTable1.getSelectedRow()][1] = team;
jTable1.setModel(new
DefaultTableModel(data, columnNames));
//
jTable1.getModel().setValueAt(name, jTable1.getSelectedRow(), 0);
//
jTable1.getModel().setValueAt(team , jTable1.getSelectedRow(), 1);
}
else {
JOptionPane.showMessageDialog(this, "You must select row!");
}
5.
Мөр
устгах:
int pos = jTable1.getSelectedRow();
int pos = jTable1.getSelectedRow();
Object[][] temp = new
Object[data.length - 1][2];
for(int i = 0; i<pos; i++)
{
temp[i][0] = data[i][0];
temp[i][1] = data[i][1];
}
for( int i = pos+1;
i<data.length; i++){
temp[i-1][0] =
data[i][0];
temp[i-1][1] =
data[i][1];
}
data = temp;
jTable1.setModel(new
DefaultTableModel(data, columnNames));
Example 2:
Using JMenubar:
Using JMenubar:
Save Menu Click:
JOptionPane.showMessageDialog(this, "Saved!");
JMenuItem itm
= new JMenuItem("Exit");
itm.addActionListener(new ActionListener() {
@Override
public
void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Tut30.this, "Exit!");
System.exit(0);
}
});
jMenu1.add(itm);
Using
MouseClickListener:
Button -> MouseReleased
if(evt.getButton() == MouseEvent.BUTTON1)
if(evt.getButton() == MouseEvent.BUTTON1)
JOptionPane.showMessageDialog(this, "Left Clicked!");
else if
(evt.getButton() == MouseEvent.BUTTON2)
JOptionPane.showMessageDialog(this, "Middle Clicked!");
else if
(evt.getButton() == MouseEvent.BUTTON3)
JOptionPane.showMessageDialog(this, "Right Clicked!");
Using JPopupMenu:
private void
jButton1MouseReleased(java.awt.event.MouseEvent evt) {
if
(evt.getButton() == MouseEvent.BUTTON3)
{
jPopupMenu1.removeAll();
JMenuItem
itm = new JMenuItem("Copy");
itm.addActionListener(new ActionListener() {
@Override
public
void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Tut30.this,
"Copied!");
}
});
jPopupMenu1.add(itm);
jPopupMenu1.show(jButton1, evt.getX(), evt.getY());
}
}
Subscribe to:
Posts (Atom)