Aklımda Kalası Kelimeler

* давайте работать вместе
* Zarf ve Mazruf, Zerafet(xHoyratlık) ile aynı kökten(za-ra-fe) gelir
* Bedesten
* Suç subuta ermiştir - Suç sabit olmuştur
Java etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Java etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

30 Temmuz 2013 Salı

IP ve Teamviewer ID çeken Java Applet

Aşağıdaki kodu Java project olarak derleyin ve jar a çevirerek sertifikalayın. Sunucuya yükleyin çalışsın.
import java.applet.Applet;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;

public class FirstApplet extends Applet
{
 public String lineSeparator = "";

 public void init()
 {
  lineSeparator = ff();
 }

 public void paint(Graphics g)
 {
  // Set the color to blue
  g.setColor(Color.blue);

  // Write the message to the web page
  int y = 10;
  for (String line : lineSeparator.split("\n")){
   g.drawString(line, 10, y += 15);
  }
 }

 public String ff()
 {
  String a = "";
  try
  {
   String query = "reg query \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\TeamViewer\\Version7\" /v ClientID";
   ArrayList<string> output = new ArrayList<string>();
   Process p = Runtime.getRuntime().exec(query);
   BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()), 8 * 1024);
   String s = null;
   while ((s = stdInput.readLine()) != null)
   {
    output.add(s);
   }

   String val = (output.get(2));
   String version = val.trim().split("   ")[2].trim();
   int iTeamviewerID = Integer.parseInt(version.substring(2), 16);
   a += "Teamviewer ID: " + iTeamviewerID;
  }
  catch (Exception e)
  {
   return null;
  }

  try
  {
   a += "\nAğ Adresleri:";
   Integer i = 0, j = 0;
   for (Enumeration<networkinterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
   {
    i++;
    NetworkInterface intf = en.nextElement();
    if (intf.isUp() && !intf.isLoopback() && !intf.isVirtual())
    {
     a += "\n   Görünen Ad: " + intf.getDisplayName();
     for (Enumeration<inetaddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
     {
      j++;
      String ip = enumIpAddr.nextElement().toString();
      if(ip.contains(".")){
       a += "\n        IP Adresi: " + ip.replace('/', ' ');
      }
     }
    }
   }
  }
  catch (SocketException e)
  {
  }
  return a;
 }
}

14 Mart 2013 Perşembe

Java'da Comparable ve Comparator ile kıyaslayarak sıralama


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class A implements Comparable<A>
{
 public int a;
 public String b;

 public A(int _a, String _b) {
  a = _a;
  b = _b;
 }

 @Override
 public int compareTo(A _kiyaslanan)
 {
  return this.a - _kiyaslanan.a;
 }

 @Override
 public String toString()
 {
  return a + ":" + b;
 }
}




public class test
{
 public static void main(String[] args)
 {
  A a = new A(10, "on");
  A b = new A(9, "dokuz");
  A c = new A(8, "sekiz");
  A d = new A(7, "yedi");
  A e = new A(6, "altı");




  final List list = new ArrayList<A>();
  list.add(a);
  list.add(c);
  list.add(b);
  list.add(e);
  list.add(d);




  System.out.println("// Kendi compareTo metoduyla sıralama");
  Collections.sort(list);
  yaz(list);
  System.out.println("// İnterface olarak eklenen compareTo metoduyla sıralama");
  Collections.sort(list, new Comparator<A>() {
   @Override
   public int compare(A a2, A a1)
   {
    // b, String tipinde ve String sınıfının compareTo metoduna göre
    // sıralama
    return a2.b.compareTo(a1.b);
   }
  });
  yaz(list);
 }




 public static void yaz(List list)
 {
  for (int i = 0; i < list.size(); i++)
  {
   System.out.println(list.get(i));
  }
 }
}

17 Temmuz 2011 Pazar

Bir sınıfa Parcelable uyarlamak


package cem.examples.reminder;

import java.util.ArrayList;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Html;
import android.text.Spanned;

public class Information implements Parcelable {
public Spanned MTitle;
public Spanned MContent;
public List<String> MTags;

// Her property sırayla yazılır
public void writeToParcel(Parcel dest, int flag) {
dest.writeString(MTitle.toString());
dest.writeString(MContent.toString());
dest.writeStringList(MTags);
}

// Parcel tipinde içinde objemiz olan in parametresini yazdığımız sırada
// okuyacağız
void readFromParcel(Parcel in) {
MTitle = Html.fromHtml(in.readString()); // String tipini Spanned tipine
// HTML.fromHtml() metoduyla
// döndüreceğiz
MContent = Html.fromHtml(in.readString());

// Eğer MTags yaratılmamışsa hata almamak için yaratacağız
if (MTags == null) {
MTags = new ArrayList<String>();
}
// ve içine Parcel tipindeki in objemizde ne buluyorsak yazacağız
in.readStringList(MTags);
}

// Parcalable dan geliyor, nedir bilemiyorum şimdilik
public int describeContents() {
return 0;
}

// Bunu da şimdilik neden oluşturuyoruz bilemiyorum
public static final Parcelable.Creator<Information> CREATOR = new Creator<Information>() {

public Information[] newArray(int size) {
return new Information[size];
}

public Information createFromParcel(Parcel source) {
return new Information(source);
}
};

// Varsayılan yapıcı metodumu bu
public Information() {
}

// Bunu da Parcel objesinden Information objesine giderken kullanıyor
public Information(Parcel in) {
this();
readFromParcel(in);
}

public Information(String _title, String _content) {
MTitle = Html.fromHtml(_title);
MContent = Html.fromHtml(_content);
}

// Information sınıfına yazdığım metot
public void f_AddTag(String... _tags) {
if (MTags == null) {
MTags = new ArrayList<String>();
}

for (String tag : _tags) {
MTags.add(tag);
}
}

// Biraz objem olsun diye kullanacağım
static public ArrayList<Information> TestInfos() {
ArrayList<Information> infos = new ArrayList<Information>();

String title = "<font color='red'>Basics of Android Intents</font>";
String content = "Although an intent is easily understood as a mechanism to invoke components(activities, services, broadcast receivers, and content providers), Android folds multiple ideas into the concept of an intent. You can use intents to invoke external applications from your application. You can use intents to invoke internal or external components from your application. You can use intents to raise events so that others can respond in a manner similar to a publish-and-subscribe model. You can use intents to raise alarms.";
Information info = new Information(title, content);
info.f_AddTag("Intent", "invoke");

infos.add(info);

title = "<b>The list of components in Android</b>";
content = "The list of components in Android include <i>activities</i> (UI components), <i>services</i> (background code), <i>broadcast receivers</i> (code that responds to broadcast messages), and <i>content providers</i> (code that abstracts data)";
info = new Information(title, content);
info.f_AddTag("component", "Android", "service");

infos.add(info);

return infos;
}

// Information sınıfına yazdığım metot
static public ArrayList<Information> BagliBasliklar(String _tag) {
ArrayList<Information> infos = TestInfos();

for (Information info : infos) {
if (!info.MTags.contains(_tag)) {
infos.remove(info);
}
}

return infos;
}
}


Information sınıfını Parcelable olarak ayarladık.
Şimdi bir ArrayList<Information> değişkenini Bundle içine koyup bir sonraki aktiviteye gönderelim.

public void onClick(View v) {
// Butonun Text'inde etiket adı var ve BagliBasliklar metodundan bu etiketleri süzüyoruz
Button btnTag = (Button) v;
ArrayList<Information> infos = Information.BagliBasliklar(btnTag.getText().toString());

// Intent'din ilgili aktivitesini belirlemek için aynı uygulamada olduğundan Activity Sınıfının adıylada çalıştırabiliriz
// Ya da .manifest dosyasında <Intent-Filter> içinde <action> etiketinin içine "cem.examples.reminder.intent.action.INFO_LIST" yazarakta aktiviteyi bulmayı sağlayabiliriz.
//
// <activity android:name=".Liste">
// <intent-filter>
// <action android:name="cem.examples.reminder.intent.action.INFO_LIST" />
// <category android:name="android.intent.category.DEFAULT" />
// </intent-filter>
//</activity>
Intent baslikListe = new Intent("cem.examples.reminder.intent.action.INFO_LIST");

// Veri aktarımı için putXXX(YYY) metodunu kullanıyoruz.
// Bizimkisi jenerik(generic olduğu için Parcelable tipini atadan alan) bir ArrayList olduğu için
// putParcelableArrayListExtra metodunu kullanacağız.
baslikListe.putParcelableArrayListExtra("baslikListe", infos);

// ve aktiviteyi bulup çalıştırması için Android sistemine emanet edeceğiz
startActivity(baslikListe);
}


Peki Aktivite bu bilgiyi aldığında Parcelable veriyi nasıl açacak?

Bundle extras = getIntent().getExtras();
ArrayList<Information> infos = extras.getParcelableArrayList("baslikListe");

// InformationTagsAdapter Adapter sınıfından türettiğimiz Liste yi istediğimiz bileşenlerin içinde
// göstermek için customize(özelleştirebildiğimiz) edebildiğimiz bir sınıf.
// Bu sınıf gelen veriyi yazdığımız bilgilere göre ekrandaki elemanlara bağlayan bir sınıf olacak.
setListAdapter(new InformationTagsAdapter(this, infos));

5 Mart 2010 Cuma

Java ve Event Handling

Kaynaklar:
http://www.devshed.com/c/a/Java/Event-Handling-In-Java/
http://scatteredcode.wordpress.com/2011/11/24/from-c-to-java-events/

In life, you encounter events that force you to suspend other activities and respond to them immediately. In Java, events represent all activity that goes on between the user and the application. Java's Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.


You are leaving for work in the morning and someone rings the doorbell….

That is an event!

In life, you encounter events that force you to suspend other activities and respond to them immediately. In Java, events represent all activity that goes on between the user and the application. Java’s Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events. When the user interacts with a program let us say by clicking a command button, the system creates an event representing the action and delegates it to the event-handling code within the program. This code determines how to handle the event so the user gets the appropriate response.

In today’s tutorial we are going to learn event-driven programming, the event model of Java, and the different ways in which you can handle events.

Now lets taste our first cup of Java…

Components of an Event: Can be put under the following categories.

1. Event Object: When the user interacts with the application by clicking a mouse button or pressing a key an event is generated. The Operating System traps this event and the data associated with it. For example, info about time at which the event occurred, the event types (like keypress or mouse click). This data is then passed on to the application to which the event belongs. In Java, events are represented by objects, which describe the events themselves. And Java has a number of classes that describe and handle different categories of events.

2. Event Source: An event source is the object that generated the event. Example if you click a button an ActionEvent Object is generated. The object of the ActionEvent class contains information about the event.

3. Event-Handler: Is a method that understands the event and processes it. The event-handler method takes the Event object as a parameter. Java uses Event-Delegation Model :with JDK1.1 onwards; you can specify the objects that are to be notified when a specific event occurs. If the event is irrelevant, it is discarded. The four main components based on this model are Event classes, Event Listeners, Explicit event handling and Adapters. Let us take a closer look at them one by one.

Event Classes: The EventObject class is at the top of the event class hierarchy. It belongs to the java.util package. While most of the other event classes are present in java.awt.event package. The getSource() method of the EventObject class returns the object that initiated the event. The getId () method returns the nature of the event. For example, if a mouse event occurs, you can find out whether the event was click, a press, a move or release from the event object. AWT provides two conceptual types of events: Semantic and low-level events.

Semantic events are defined at a higher-level to encapsulate the semantics of user interface component’s model. Now let us see what are the various semantic event classes and what they generate:

• An ActionEvent object is generated when a component is activated

• An AdjustmentEvent Object is generated when scrollbars and other adjustment elements are used.

• A TextEvent object is generated when text of a component is modified.

• An ItemEvent is generated when an item from a list, a choice or checkbox is selected.

Low-Level Events is one that represents a low-level input or windows-system occurrence on a visual component on the screen. The various low-level event classes and what they generate are as follows:

• A ContainerEvent Object is generated when component are added or removed from container.

• A ComponentEvent object is generated when a component is resized, moved etc.

• A FocusEvent object is generated when component receives focus for input.

• A KeyEvent object is generated when key on keyboard is pressed, released etc.

• A WindowEvent object is generated when a window activity, like maximizing or close occurs.

• A MouseEvent object is generated when a mouse is used.

• A PaintEvent object is generated when component is painted.

Event Listeners: An object delegates the task of handling an event to an event listener. When an event occurs, an event object of the appropriate type (as illustrated below) is created. This object is passed to a Listener. A listener must implement the interface that has the method for event handling. A component can have multiple listeners, and a listener can be removed using removeActionListener () method. Next question in your mind must be what is an interface?. An Interface contains constant values and method declaration. The difference between classes and interface is that the methods in an interface are only declared and not implemented, that is, the methods do not have a body. What is the Need for interface? Are interfaces are used to define behavior protocols (standard behavior) that can be implemented by any class anywhere in the class hierarchy. The java.awt.event package contains definitions of all event classes and listener interface. The semantic listener interfaces define by AWT for the above mentioned semantic events are:

• ActionListener

• AjdustmentListener

• ItemListener

• TextListener

The low-level event listeners are as follows:

• ComponentListener

• ContainerListener

• FocusListener

• KeyListener

• MouseListener

• MouseMotionListener

• WindowsListener.



ActionEvent using the ActionListener interface: The following illustrates the usage of ActionEvent and ActionListener interface in a Classic Java Application (Example I).

//Save the file with MyEvent.java file and compile it using javac, 
//once complied errors free execute it.
Import javax.swings.*;
Import java.awt.event.*;
Public class MyEvent extends JFrame
{
JButton b1;
// Main Method
Public static void main (String arg[])
{
MyEvent event = new MyEvent();
}
//Constructor for the event derived class
Public MyEvent()
{
Super(“Window Title: Event Handling”);
b1 = new Jbutton(“Click Me”);
//place the button object on the window
getContentPane().add(“center”,b1);
//Register the listener for the button
ButtonListener listen = new ButtonListener();
b1.addActionListener(listen);
//display the window in a specific size
setVisible(true);
setSize(200,200);
}
//The Listener Class
Class ButtonListener implements ActionListener
{
//Definition for ActionPerformed() method
Public void ActionPerformed(ActionEvent evt)
{
JButton source = (JButton)evt.getSource();
Source.setText(“Button Has Been Clicked, Guru!”);
}
}
}
How does the above Application work?


• The execution begins with the main method.

• An Object of the MyEvent class is created in the main method.

• Constructor of the MyEvent class is invoked.

• Super () method calls the constructor of the base class and sets the title of the window as given.

• A button object is created and placed at the center of the window.

• A Listener Object is created.

• The addActionListener() method registers the listener object for the button.

• SetVisible () method displays the window.

• The Application waits for the user to interact with it.

• When the user clicks on the button labeled “Click Me”: The “ActionEvent” event is generated. Then the ActionEvent object is created and delegated to the registered listener object for processing. The Listener object contains the actionPerformed() method which processes the ActionEvent In the actionPerformed() method, the reference to the event source is retrieved using getSource() method. The label of the button is changed to “Button has been clicked, Guru!” using setText() method.

Tools of the Trade: Since the ButtonListener class has been declared under MyEvent class. Therefore ButtonListener class is an inner class.

For those of you folks who are more into using Java Applets here is easy sample which works.Type in the following code (Example 2) and save it as ButtonEvent.java and the compile using javac and view it using appletviewer. A short cut to avoid compiling a java file and html file separately you can enclose the applet tag normally containing applet code, height, width, param tags etc. within /* and */. Then compile as one single file, because the HTML tag will be read as html automatically. And when compiled error free run using Appletviewer tag.

/*
<Applet code = "ButtonEvent.class" height = 400 width = 400>
</applet>
*/
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.Applet;
Public class ButtonEvent extends Applet implements ActionListener 
{
Private Button b;
Public void init() {
b = new Button("Click me");
b.addActionListener(this);
add (b);
}
Public void actionPerformed (ActionEvent e) {
// If the target of the event was our Button
// In this example, the check is not 
// Truly necessary as we only listen to
// A single button
If (e.getSource () == b) {
getGraphics().drawString("OUCH Buddy",20,20);
}
}
}
The above sample code pretty much does the same thing
as Example I only the applet starts with the init() method first the button is added using the add() method and is registered with ActionListener(). Once the user clicks it, The event is trapped using the getSource() and delegated to the appropriate listener. The getGraphics() method of the image class is used along with drawString() method to draw the text given by the specified string.

Mouse Events, MouseListener and MouseMotionListener:

These are generated when a mouse is moved, clicked, pressed and released etc. The MouseEvent class represents these events as six constant values and has methods to get the co-ordinates at which a mouse event occurred. The mouse move and mouse drag are treated differently from the rest four mouse pressed, mouse released, mouse entered and mouse exited. Hence there are two types of mouse event listeners- MouseListener and MouseMotionListener.

The following code illustrates the usage of mouse event listeners. Watch out for messages on the status line of applet as and when the user performs a mouse event. (Example 3 also shows the co-ordinates at which the event occurred.

// Example 3: MouseEvents & MouseListener
/*
<Applet code = "mouseEvent.class" height= 400 width = 400 >
</applet>
*/
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Public class mouseEvent extends JApplet implements MouseListener, MouseMotionListener
{
Public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
Public void mouseClicked(MouseEvent e)
{
showStatus("Mouse has been clicked at " + e.getX()+ "," + e.getY());
}
Public void mouseEntered(MouseEvent e)
{
showStatus("Mouse has been Entered at " + e.getX()+ "," + e.getY());
// For loop:to make sure mouse entered is on status bar for a few sec
For (int i= 0; i<1000000; i++);
} 
Public void mouseExited (MouseEvent e)
{
showStatus ("Mouse has been Exited at " + e.getX()+ "," + e.getY());
}
Public void mousePressed(MouseEvent e)
{
showStatus ("Mouse pressed at " + e.getX()+ "," + e.getY());
}
Public void mouseReleased(MouseEvent e)
{
showStatus("Mouse released at " + e.getX()+ "," + e.getY());
}
Public void mouseDragged(MouseEvent e)
{
showStatus("Mouse dragged at " + e.getX()+ "," + e.getY());
}
Public void mouseMoved(MouseEvent e)
{
showStatus("Mouse moved at " + e.getX()+ "," + e.getY());
}
}
Since the applet implements MouseListener and
MouseMotionListener it has to provide for the functionality of all their methods. Observe the mouseEntered() method has a small loop to ensure the mouse entered message remains on the status bar for a while. {mospagebreak title=Key Frienldy Codes} Keyboard Events and KeyListener: They are generated on pressing or releasing a key. The KeyEvent class contains constants to represent the keys pressed or typed. The event listener corresponding to these types of event is the KeyListener.

The following example puts forth key event handling. The applet contains a label and a text field. The recently typed in character in the text field is displayed in the status bar. Example 4.

// Key events and KeyListener.
/*
<applet code = "keyTest.class" width = 400 height = 400>
</applet>
*/
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.Applet;
Public class keyTest extends Applet implements KeyListener
{
Public void init()
{
Label lab = new Label ("Enter Characters :");
add(lab);
TextField tf = new TextField(20);
add(tf);
tf.addKeyListener(this);
}
Public void keyPressed(KeyEvent e)
{}
Public void keyReleased(KeyEvent e)
{}
Public void keyTyped(KeyEvent e)
{
showStatus(" Recently typed characters are : " + e.getKeyChar());
}
}
Here the text field delegates its key events to the
applet. The add() method adds the components Label and TextField to the applet.

A quick recap: Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. Swing components can generate many kinds of events.

Each event is represented by an object that gives information about the event and identifies the event source. Event sources are typically components, but other kinds of objects can also be event sources. Each event source can have multiple listeners registered on it. Conversely, a single listener can register with multiple event sources.

In the next part of the tutorial we will see about Explicit Event-handling and adapters.

2 Ocak 2010 Cumartesi

VS ve Java Generic Metot

Visual Studio 2008 de generic parametre alan bir metot şu şekilde:

vs

Çıktısı:

vsOut

Java’da :

java

javaout


Peki birden fazla generic tipte parametre alan metot nasıl olur?

Visual Studio 2008:

vsParam

Java’da:

javaParam

javaParam1

Java da T generic parametreleri derleme zamanında Object tipine çeviriliyor. Buna “erasure” deniyor. Hadi bir kayak:

http://java.sun.com/docs/books/tutorial/java/generics/erasure.html

Ama VS da durum bu değil. Peki ne? Bende bilmiyorum. Bilen olursa yazsın :)

Hadi birazda çıktılarına bakalım.

javaErasure vsErasure

25 Aralık 2009 Cuma

24 Aralık 2009 Perşembe

Javada InnerClass lar


  • non-static variable this cannot be referenced from a static context:
    Statik bir noktadan statik olmayan bir değişkene erişilemez. Ama inner class olmayan A sınıfından bir obje türetmek sorunsuz olarak tamamlanıyor.
  • inner classes cannot have static declarations:
    Alt sınıflar statik tanımlamalara sahip olamaz


(alt sınıflı)Java kodunu derleme




public class Book {

private int pageNumber;

private class BookReader {

public int getPage() {
return pageNumber;
}
}
}


Path ayarlarını kalıcıda yapabiliriz.


Artık sadece "javac javaKodumuz.java" diyerek kodumuzu derleyebiliriz.

10 Aralık 2009 Perşembe

Swing ile programlama 4 - ActionListener


Ref:




import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;

public class Main {

public static void main(String[] args) {
Pencere pencere = new Pencere();
}
}
// JFrame den türetiyoruzki ana kabımız olsun diğer bileşenleri taşıyan
class Pencere extends JFrame {

JTextField txt;
JButton btn;
JLabel lbl;

public Pencere() {
// Taşıyıcı penceremiz
JFrame jfr = new JFrame("Taşıyıcı pencere");

// Bu pencerenin boyutları
jfr.setSize(400, 150);

// Kapatma çarpısına basıldığında uygulamadan çıkılsın
jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Yerleşim için FlowLayout kullanıyoruz.
jfr.getContentPane().setLayout(new FlowLayout());

// Metin kutusunu ve Düğmemizi oluşturup en başada Etiket koyalım.
lbl = new JLabel("Lutfen isminizi girin.");
jfr.getContentPane().add(lbl);
txt = new JTextField(10);
jfr.getContentPane().add(txt);
btn = new JButton("Tamam");
jfr.getContentPane().add(btn);

btn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {
lbl.setText("Merhaba " + txt.getText());
btn.setVisible(false);
txt.setVisible(false);
}
});

btn.addMouseListener(new MouseListener() {

public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(rootPane, "Tıklandı");
}

public void mousePressed(MouseEvent e) {
JOptionPane.showMessageDialog(rootPane, "Basıldı");
}

public void mouseReleased(MouseEvent e) {
JOptionPane.showMessageDialog(rootPane, "Bırakıldı");
}

public void mouseEntered(MouseEvent e) {
JOptionPane.showMessageDialog(rootPane, "Girildi");
}

public void mouseExited(MouseEvent e) {
JOptionPane.showMessageDialog(rootPane, "Çıkıldı");
}
});

txt.addKeyListener(new KeyListener() {

public void keyTyped(KeyEvent e) {
JOptionPane.showMessageDialog(rootPane, "Key Typed");
}

public void keyPressed(KeyEvent e) {
JOptionPane.showMessageDialog(rootPane, "Key Pressed");
}

public void keyReleased(KeyEvent e) {
JOptionPane.showMessageDialog(rootPane, "Key Released");
}
});
jfr.setVisible(true);
}
}

9 Aralık 2009 Çarşamba

Swing ile programlama 3 - ActionListener

GUI de öncelikle bir pencere(window) ye ihtiyacımız vardı. Ki bu window diğer bileşenlerimizi içersin. İşte javada barındırıcı penceremiz (container) JFrame den hazırlanmıştı. Şimdi de bu ana penceredeki bileşenlerin üreteceği olayları(event) nasıl yakalarız ve nasıl sonuç üretiriz onu yazalım.

Bunun içinde bir yerlerden ActionListener kullanmamız gerektiğini duymuş olalım.

Önce ActionListener nedir?
  • Sınıf mıdır? Arayüz müdür? Soyut mudur?
  • Ne yapar bizim için?



public interface ActionListener extends EventListener {

/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e);

}


Arayüzmüş. Demek ki bundan sınıflar türetebiliriz. Bu güzel. Peki nedir ActionListener?

Swing’de, görsel bileşenlerden (ui components) tetiklenen olaylara (action) dinleyici (listener) eklemek için bu komut kullanılır. Örneğin bir butona eklenen dinleyiciyle, butona tıklama olayından sonra butonun işini yapmasını sağlayabilirsiniz. Ufak bir de not, bir görsel bileşene birden fazla dinleyici eklenebilir, böylece bir olaydan tetiklenen sayısız iş yaptırılabilir. Referans:Kayıp Şehir


Bir bileşen üzerinde gerçekleşen hareket durumunu (action event) almak ve işlemek için oluşturacağımız objenin sınıfı bu arayüzü kullanır. Şimdi bizim bir nesneye ihtiyacımız var. Bu nesneyi frame üzerindeki bileşenin birine kaydedeceğiz. Yani, diyeceğizki nesnemize, bu bileşeni sen marke edeceksin. Nesnemiz, ilgili bileşenin karıştığı bir hareket durumunu (action event) yakalayacak ve ait olduğu sınıftan aldığı metodu tetikleyecektir.


package javaapplication;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main {

public static void main(String[] args) {
JFrame frame = new JFrame("Başlıkta görünsün");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 450);
frame.setVisible(true);

int iYatayBosluk = 5;
int iDikeyBosluk = 15;
LayoutManager layoutMgr = new FlowLayout(FlowLayout.CENTER, iYatayBosluk, iDikeyBosluk);

// javax.swing paketindeki rootpanecontainer interface'inin bir metodu.
// Kısaca top-level container'ların contentpane'ine erişmek için kullanılır.
Container enUsttekiKap = frame.getContentPane();

enUsttekiKap.setLayout(layoutMgr);

// Frame üzerine koymak istediğimiz JLabel bileşenini oluşturup
JLabel lbl = new JLabel();
// Metnini değiştiriyoruz
lbl.setText("İsim: ");
// JLabel sınıfından oluşturduğumuz lbl nesnesini ekliyoruz.
enUsttekiKap.add(lbl);


// 5 kolonluk bir genişlikte metin kutusu oluştur.
final JTextField txt = new JTextField(5);
enUsttekiKap.add(txt);

txt.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
txt.setBackground(Color.red);
}
});

// Bir de düğme ekleyelim.
final JButton btn = new JButton("GÖNDER");
enUsttekiKap.add(btn);

ActionListener alBtn = new ActionListener() {

public void actionPerformed(ActionEvent e) {
btn.setText("Düğmeye basıldı");
}
};

btn.addActionListener(alBtn);
}
}




Swing ile programlama 2 - LayoutManager ile frame tasarımı

Birden fazla bileşeni Frame üzerine yerleştirmeye çalıştığımızda bileşenlerin frame üzerinde duruşlarını belirlememiz gerekecektir.

Başlarken bir önceki makalemizde yazdıklarımızın üzerine bir şeyler ilave etmeye çalışalım.

Şimdi bir şekilde öğrendik ki; Java'da Swing bileşenleri ile bir GUI(Graphical User Interface) oluştururken bileşenleri barındıracak nesnenin(container) Layout'unun tanımlanması gerekiyor. Bu set etme işini de aşağıdaki kodla yapabiliriz.
frame.getContentPane().setLayout(........)



Bu da LayoutManager arayüzünün açıklaması:


AWT ve Swing içinde 8 farklı Layout vardır ve hepside LayoutManager arayüzünü uygularlar.



FlowLayout için LayoutManager arayüzünün uyarlanışı:
public class FlowLayout extends Object implements LayoutManager, Serializable

FlowLayout sınıfından bir nesne türetelim ve LayoutManager olarak setLayout metoduna parametre olarak gönderelim. Bunun için FlowLayout sınıfının yapıcı metotlarından 3. sünü kullanalım.




Artık bundan sonrası frame üzerinde bileşenlerin nasıl durduğunu görmek (frame üstüne bileşen eklemenin nasıl olduğunu bundan önceki makalemizde görmüştük). Bu kısım için en güzel kaynak: Sun'ın java bağlantılarıdır.

Frame üzerine birkaç bileşen ekleyelim ve son durumunu görelim.


Ve bu yazdıklarımızın yazı hali:

package javaapplication;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main {

public static void main(String[] args) {
JFrame frame = new JFrame("Başlıkta görünsün");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 450);
frame.setVisible(true);

int iYatayBosluk = 5;
int iDikeyBosluk = 15;
LayoutManager layoutMgr = new FlowLayout(FlowLayout.CENTER, iYatayBosluk, iDikeyBosluk);

// javax.swing paketindeki rootpanecontainer interface'inin bir metodu.
// Kısaca top-level container'ların contentpane'ine erişmek için kullanılır.
Container enUsttekiKap = frame.getContentPane();

enUsttekiKap.setLayout(layoutMgr);

// Frame üzerine koymak istediğimiz JLabel bileşenini oluşturup
JLabel lbl = new JLabel();
// Metnini değiştiriyoruz
lbl.setText("İsim: ");
// JLabel sınıfından oluşturduğumuz lbl nesnesini ekliyoruz.
enUsttekiKap.add(lbl);


// 5 kolonluk bir genişlikte metin kutusu oluştur.
JTextField txt = new JTextField(5);
enUsttekiKap.add(txt);

// Bir de düğme ekleyelim.
JButton btn = new JButton("GÖNDER");
enUsttekiKap.add(btn);
}
}


Ve uygulama:

Swing ile programlama 1

Swing ile basit bir form oluşturmak dedik. Aslında bildiğiniz üzere bir java ya da c# uygulaması (sınıfı)
static void Main(String[] args)
imzalı bir metoda sahip olmak zorundadır. Biz bu sınıfımızı çalıştırılabilir olarak derledikten sonra "yüklendiğinde sınıfın ilk okunacak metodu bu olsun" dediğimiz main metoduna
- form/frame oluştur
- çeşitli buton, label, grid v.s. bileşenleri oluştur ve bu form/frame in üzerine ekle diyoruz.

Hadi sırayla görelim ne nasıl oluyor:






Peki bir de label ekleyelim formumuza:




Sonuçta kodumuz budur:

package javaapplication;

import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {

public static void main(String[] args) {
JFrame frame = new JFrame("Başlıkta görünsün");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(250, 450);

frame.setVisible(true);

// javax.swing paketindeki rootpanecontainer interface'inin bir metodu.
// Kısaca top-level container'ların contentpane'ine erişmek için kullanılır.
Container enUsttekiKap = frame.getContentPane();

// Frame üzerine koymak istediğimiz JLabel bileşenini oluşturup
JLabel lbl = new JLabel();

// Metnini değiştiriyoruz
lbl.setText("Buda içeriği olsun");

// JLabel sınıfından oluşturduğumuz lbl nesnesini ekliyoruz.
enUsttekiKap.add(lbl);
}
}

5 Aralık 2009 Cumartesi

ServletContext

Kaynak 1: http://www.oop-reserch.com/servlet_context.html


ServletContext, javax.servlet den türetilmiş bir interfacetir.

Bir servlet'in, servlet container'ı ile iletişime geçebilmesine yarayan metotlara sahiptir(bir dosyanın MIME tipini bulmak, istekleri dağıtmak veya bir log dosyasına yazmak gibi).

Her web uygulaması için bir tane context vardır.

ServletContext objesi ServletConfig objesi barındırır ve web server servleti başlattığında erişilebilir.

Unicode

Önce ASCII tablosunu bir hatırlayalım:


İyi ama hiragana harflerimiz nerede?
Bir de UNICODE tablosuna bakalım:

Tabii gördüğümüz sadece bir kısmı. Bir karakteri artık 16 bit içinde tutarsak bu da bize iki üzeri 16 karakteri daha tutabilme imkânı verir.

Hadi bir de java kodumuza bakalım:

public class Karakter {

public static void main(String[] args) {

System.out.println(Character.toChars(65)); // A

System.out.print("'");
System.out.print(Character.toChars(0)); // ' '
System.out.println("'");

System.out.println(Character.toChars(53532)); // 턜

// UNICODE karakterler
System.out.println(Character.toChars(0x401)); // Ё 0x401 = 1025
System.out.println(Character.toChars(0x402)); // Ђ 0x402 = 1026
System.out.println(Character.toChars(0x403)); // Ѓ 0x403 = 1027
System.out.println(Character.toChars(1028)); // Є 0x404 = 1028
}
}



Hadi birde resim halinde kodumuzu görelim (daha derli toplu olsun diye):

Buradan da javanın neden bir karakteri 16 bit olarak tanımladığını hızlıca anlıyoruz.

UTF-8 Tablosu: http://doc.infosnel.nl/extreme_utf-8.html
Jeol Spolsky' den: http://turkish.joelonsoftware.com/Articles/Unicode.html
Sahiplerinden: http://www.cs.bell-labs.com/sys/doc/utf.pdf