Java Swing etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Java Swing etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

12 Haziran 2009 Cuma

Translator

Bildiğiniz gibi bir süre önce Google yeni bir uygulamasını daha duyurdu: "Google Translate". Uygulamanın Türkçe dil desteği de var. Google'ın arama sayfasından çıkan sonuçların yanında yer alan "[ Bu sayfanın çevirisini yap ]" linkini tıkladığınızda mevcut sayfanın çevrisi karşınıza geliyor. Her ne kadar Türkçe çevirisinde sıkıntılar olsa da bu konuda yeni standartlar oluşturulacağına da inanıyorum. Aksi takdirde, örneğin kodların yer aldığı bir sitenin çevirisinde, "import ....." ifadesinin "ithal ...." çevirisi oldukça eğlenceli görünüyor.

Google'ın bir çeviri uygulaması da http://translate.google.com sitesinde yer alan metin çevirisi. 41 dilde sunulan destek oldukça iyi bir uygulama. Ki Google'ın ücretsiz sunduğu bu iki uygulama çeviri dünyasında yeni bir soluk getirecek.

Yine Google'ın Java Developer'lar için yazdığı bir de API'si mevcut. Bu yazıda sizlerle bu API'yı paylaşacağız. Bu API'yı kullanarak siz de ufak bir translator uygulaması geliştirebilirsiniz. Üstelik çeviriler Google'ın Ajax Dili API'sinin koştuğu siteden yapılıyor:

Başlamadan önce gerekli olan bazı jar'ları indirmeniz gerekiyor:
1- google-api-translate-java-0.53.jar
2- org.json.JSONObject

Bunları kullandığınız editor'deki "Libraries" klasörüne ekledikten sonra iki class'ı yazmanız gerekecek. Bunlardan ilki
Translate.java. Kodlar da aşağıda:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package webdestek.Language; //Kendi package'ınızı buraya belirtin...

/**
*
* @author Ömürhan
*/
/**
* Language.java
*
* Copyright (C) 2007, Richard Midwinter
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

import java.util.Arrays;
import java.util.List;

/**
* Defines language information for the Google Translate API.
*
* @author Richard Midwinter
*/

public final class Language {

public static final String ARABIC = "ar";
public static final String BULGARIAN = "bg";
public static final String CATALAN = "ca";
public static final String CHINESE = "zh";
public static final String CHINESE_SIMPLIFIED = "zh-CN";
public static final String CHINESE_TRADITIONAL = "zh-TW";
public static final String CROATIAN = "cr";
public static final String CZECH = "cs";
public static final String DANISH = "da";
public static final String DUTCH = "nl";
public static final String ENGLISH = "en";
public static final String FILIPINO = "tl";
public static final String FINNISH = "fi";
public static final String FRENCH = "fr";
public static final String GERMAN = "de";
public static final String GREEK = "el";
public static final String HEBREW = "iw";
public static final String HINDI = "hi";
public static final String INDONESIAN = "id";
public static final String ITALIAN = "it";
public static final String JAPANESE = "ja";
public static final String KOREAN = "ko";
public static final String LATVIAN = "lv";
public static final String LITHUANIAN = "lt";
public static final String NORWEGIAN = "no";
public static final String POLISH = "pl";
public static final String PORTUGESE = "pt";
public static final String ROMANIAN = "ro";
public static final String RUSSIAN = "ru";
public static final String SERBIAN = "sr";
public static final String SLOVAK = "sk";
public static final String SLOVENIAN = "sl";
public static final String SPANISH = "es";
public static final String SWEDISH = "sv";
public static final String TURKISH = "tr";
public static final String UKRANIAN = "uk";
public static final String VIETNAMESE = "vi";
public static final List validLanguages = Arrays.asList(new String[]{
ARABIC, BULGARIAN, CATALAN, CHINESE, CHINESE_SIMPLIFIED,
CHINESE_TRADITIONAL, CROATIAN, CZECH, DANISH, DUTCH,
ENGLISH, FILIPINO, FRENCH, GERMAN, GREEK, HEBREW,
ITALIAN, JAPANESE, KOREAN, LATVIAN, LITHUANIAN, NORWEGIAN,
POLISH, PORTUGESE, ROMANIAN, RUSSIAN, SERBIAN, SLOVAK,
SLOVENIAN, SPANISH, SWEDISH, TURKISH, UKRANIAN, VIETNAMESE
});

/**
* Checks a given language is available to use with Google Translate.
*
* @param language The language code to check for.
* @return true if this language is available to use with Google Translate, false otherwise.
*/
public static boolean isValidLanguage(String language) {
return validLanguages.contains(language);
}
}
-----
Yukarıda da söylediğimiz gibi Google'ın (şimdilik) 41 dilde desteği var. Yukarıdaki class'ta her ne kadar 37 dil gösteriliyor olsa da bu listeden kontrol ederek, Google'ın desteklediği diğer diller için de class'ta düzenleme yapabilirsiniz.

Yazmamız gereken ikinci class ise Translate.java adında. Uzun uzun anlatmaya gerek yok çünkü Google'ın bu hizmeti veren Ajax API'sının yer aldığı sayfadan sizin gönderdiğiniz data'nın eşleşmesini yapıyor ve console'da görüntülüyor.



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package webdestek.Language;
//Kendi package'ınızı buraya belirtin...

/**
*
* @author Ömürhan
*/
/**
* Translate.java
*
* Copyright (C) 2007, Richard Midwinter
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONObject;


/**
* Makes the Google Translate API available to Java applications.
*
* @author Richard Midwinter
* @author Emeric Vernat
* @author Juan B Cabral
*/
public class Translate {

private static final String ENCODING = "UTF-8";
private static final String URL_STRING = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=";
private static final String TEXT_VAR = "&q=";

/**
* Translates text from a given language to another given language using Google Translate
*
* @param text The String to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated String.
* @throws MalformedURLException
* @throws IOException
*/
public static String translate(String text, String from, String to) throws Exception {
return retrieveTranslation(text, from, to);
}

/**
* Forms an HTTP request and parses the response for a translation.
*
* @param text The String to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated String.
* @throws Exception
*/
private static String retrieveTranslation(String text, String from, String to) throws Exception {
try {
StringBuilder url = new StringBuilder();
url.append(URL_STRING).append(from).append("%7C").append(to);
url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
try {
String result = toString(uc.getInputStream());

JSONObject json = new JSONObject(result);
return ((JSONObject) json.get("responseData")).getString("translatedText");
} finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
uc.getInputStream().close();
if (uc.getErrorStream() != null) {
uc.getErrorStream().close();
}
}
} catch (Exception ex) {
throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
}
}

/**
* Reads an InputStream and returns its contents as a String. Also effects rate control.
* @param inputStream The InputStream to read from.
* @return The contents of the InputStream as a String.
* @throws Exception
*/
private static String toString(InputStream inputStream) throws Exception {
StringBuilder outputBuilder = new StringBuilder();
try {
String string;
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING));
while (null != (string = reader.readLine())) {
outputBuilder.append(string).append('\n');
}
}
} catch (Exception ex) {
throw new Exception("[google-api-translate-java] Error reading translation stream.", ex);
}
return outputBuilder.toString();
}
}

--------

Uygulamamız bu kadar. Bu uygulamayı geliştirmek sizin elinizde. Bir combobox koyup, desteklenen dilleri içinde yazdırıp, kullanıcının istediği kelimeyi hangi dilden hangi dile çevirmek istediği bilgisini alarak ekranda görüntülemek oldukça kolay. İlerleyen zamanlarda (gerekirse veya soru gelirse) buna yönelik bir uygulama daha koyabiliriz.

20 Nisan 2009 Pazartesi

Türkçe File Chooser

Java Swing' te rendering yaparken problem yaşayabilirsiniz. Bu sorunu UIManager kullanarak çözebiliriz. File Chooser tanımlamadan önce bir method tanımlayalım,

public void fileChooserTurkce(){

UIManager.put("FileChooser.openDialogTitleText", "Dosya Yükle");

UIManager.put("FileChooser.lookInLabelText", "Gözat");

UIManager.put("FileChooser.filesOfTypeLabelText", "Dosya Tipi");

UIManager.put("FileChooser.upFolderToolTipText", "Üst Dizin");

UIManager.put("FileChooser.fileNameLabelText", "Dosya Adı");

UIManager.put("FileChooser.homeFolderToolTipText", "Masa Üstü");

UIManager.put("FileChooser.newFolderToolTipText", "Yeni Klasör");

UIManager.put("FileChooser.listViewButtonToolTipText", "Listele");

UIManager.put("FileChooser.detailsViewButtonToolTipText", "Ayrıntılı Listele");

UIManager.put("FileChooser.saveButtonText", "Kaydet");

UIManager.put("FileChooser.openButtonText", "Aç");

UIManager.put("FileChooser.cancelButtonText", "İptal");

UIManager.put("FileChooser.updateButtonText", "Güncelle");

UIManager.put("FileChooser.helpButtonText", "Yardım");

UIManager.put("FileChooser.saveButtonToolTipText", "Kaydet");

UIManager.put("FileChooser.openButtonToolTipText", "Tamam");

UIManager.put("FileChooser.cancelButtonToolTipText", "İptal");

UIManager.put("FileChooser.updateButtonToolTipText", "Güncelle");

UIManager.put("FileChooser.helpButtonToolTipText", "Yardım");

}

Tanımlama yapmadan önce fonksiyonumuzu çağıralım ve bir filechooser tanımlayalım ve çağıralım.

fileChooserTurkce();

JFileChooser fileChooser = new JFileChooser();

File file= null;

fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

int returnVal = fileChooser.showOpenDialog(this);

if (returnVal == JFileChooser.APPROVE_OPTION) {

file = fileChooser.getSelectedFile();

filetext.setText(file.getPath());

}


Frame'i run ettiğimizde karşımıza türkçe FileChooser elde etmiş oluruz. Burada UIManager setlemelerini FileChooser' ı tanımlamadan önce yapmamız gerekiyor. Eğer bunu tüm paketlerde kullanacaksak main fonsiyonunda tanımlama yapmadan önce bu fonksiyonu çağırabilirsiniz.



17 Nisan 2009 Cuma

Dynamic JTree

Database'de iki table olduğunu varsayalım, child larımızı tuttuğumuz “guide” ve node ları tuttuğumuz “groupguide”

guide :
Long id ;
String name;
Long groupid;

groupguide
:
Long id;
String name;
veri tabanımıza verileri yükleyelim;

INSERT INTO `groupguide` (`id`, `name`) VALUES(1, 'group1'),(2, 'group2');

INSERT INTO `guide` (`id`, `name`, `groupid`) VALUES (1, 'Name1', 1), (2, 'Name2', 2);

Guide için bir class yazalım,

public class TreeSampleAction {
List treeSampleActionList= new ArrayList();
private Long id;
private String name;
DataBaseConnection conn= new DataBaseConnection();

// Bunları set ve get fonksiyonlarını yazalım

/**
*
* @param id
* @return
* veri tabanından çektiğimiz, gruba göre guide listesi döndürür.
*
*/
public List getDataById(Long id) {
try {
TreeSampleAction treeSampleAction = null;
treeSampleActionList = new ArrayList();
String str = "SELECT * FROM guide where groupid=" + id;
ResultSet rs = null;
rs = conn.get(str);
if (rs != null) {

while (rs.next()) {
treeSampleAction = new TreeSampleAction();
treeSampleAction.setId(rs.getLong("id"));
treeSampleAction.setName(rs.getString("name"));
getTreeSampleActionList().add(treeSampleAction);
}

}

rs.close();
conn.connClose();
} catch (SQLException ex) {
Logger.getLogger(TreeSampleAction.class.getName()).log(Level.SEVERE, null, ex);
}
return this.getTreeSampleActionList();
}
}

Group için bir class yazalım,

public class TreeSampleGroupAction {
List treeSampleActionGroupList= new ArrayList();
DataBaseConnection conn= new DataBaseConnection();
private Long id;
private String name;
// Bunları set ve get fonksiyonlarını yazalım
/**
*
* @param id
* @return
* veri tabanından çektiğimiz grub listesi döndürür.
*
*/

public List getData() {
try {
TreeSampleGroupAction treeSampleGroupAction = null;
treeSampleActionGroupList = new ArrayList();
String str = "SELECT * FROM groupguide";
ResultSet rs = null;
rs = conn.get(str);
if (rs != null) {

while (rs.next()) {
treeSampleGroupAction = new TreeSampleGroupAction();
treeSampleGroupAction.setId(rs.getLong("id"));
treeSampleGroupAction.setName(rs.getString("name"));
treeSampleActionGroupList.add(treeSampleGroupAction);
}


}

rs.close();
conn.connClose();
} catch (SQLException ex) {
Logger.getLogger(TreeSampleGroupAction.class.getName()).log(Level.SEVERE, null, ex);
}


return this.treeSampleActionGroupList;
}
}

JTree'i gösterebileceğimiz bir Frame yaratalım,

public class TreeSampleFrame extends javax.swing.JFrame {
/**
* Kullandığımız Değişkenler
*/

Vector vect;
Vector rightVect;
DefaultMutableTreeNode rootNode;
DefaultMutableTreeNode childNode, grandchildNode;
DefaultTreeModel treeModel;
TreeSampleAction treeSampleAction;
List treeSampleActionList;
TreeSampleGroupAction treeSampleGroupAction;
List treeSampleGroupActionList;

/** TreeSampleFrame Türünde Yeni Bir Form Oluşturalım */

public TreeSampleFrame() {
initComponents();
// Tree 'i oluşturup verilerimizi set lemek için kullandığımız metod
SetTreeValues();

}

/**
* JTree ye verilermizi setlediğimiz metod
*/

public void SetTreeValues() {
//grupları tutacağımız liste tanımlayalım
List treeSampleGroupActionList = new ArrayList();
// guideları tutacağımız liste tanımlayalım
List treeSampleActionList = new ArrayList();
//group için bir nesne tanımlayalım
TreeSampleGroupAction treeSampleGroupAction = new TreeSampleGroupAction();
// guide için bir nesne tanımlayalım
TreeSampleAction treeSampleAction = new TreeSampleAction();
Vector vect = new Vector(); // child ları ekleyeceğimiz Vector
//Node ları tutacağımız bir root Node tanımlayalım
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Tree Sample");
// veri tabanında sakladığımız grup verilerini tanımladığımız grup listesine ekleyelim
treeSampleGroupActionList = treeSampleGroupAction.getData();

for (TreeSampleGroupAction treeGroup : treeSampleGroupActionList) {
//her bir grubu bir node olarak tanımlayalım
DefaultMutableTreeNode node = new DefaultMutableTreeNode(treeGroup);
// her bir grubun üyelerini yani guide listesini veri tabanından çekelim
treeSampleActionList = treeSampleAction.getDataById(treeGroup.getId());

if (treeSampleActionList.size() != 0) {
// her bir guide'ı vector' e ekleyelim
for (TreeSampleAction branch : treeSampleActionList) {
vect.add(branch);
}
// her bir vector u Node lara ekleyelim yani grubun altına guide ları ekleyelim
JTree.DynamicUtilTreeNode.createChildren(node, vect); //this is the hard one
// oluşturulan node 'u Root Node' a ekleyelim
rootNode.add(node);
}
//vector'ü ve Guide listesini temizleyelim
vect.removeAllElements();
treeSampleActionList.clear();
}
// Oluşturduğumuz Root Node ile TreeModel'i oluşturalım.
treeModel = new DefaultTreeModel(rootNode);
// JTree' e treeModel i setleyelim
jTree.setModel(treeModel);
}

Frame 'i run ettiğimizde karşımıza aşağıdaki ekran çıkacaktır.



burada eklediğimiz node ve child lar da görülecek isimler istediğimiz formatta olmayabilir bunun için toString metodu tanımlamamız gerekiyor. Bu metod u oluşturduğumuz “TreeSampleGroupAction” ve “TreeSampleAction” class larımıza ekleyelim.

@Override
public String toString() {
return this.getName();
}
Frame'i tekrar run ettiğimizde,