javaswing

Java Swing-04 Hodisalar

Java Swing da hodisalar bilan ishlash

Hodisalar har qanday FGM dasturning muhim qismidir. Barcha FGM dasturlar hodisalar orqali boshqariladi. Dastur o’zining hayoti davomida turli hil hodisalarga o’z munosabatini bildiradi. Hodisalar asosan foydalanuvchi tomonidan amalga oshiriladi. Lekin hodisalar boshqa tomondan ham kelishi mumkin, masalan internetga bog’lanish, oyna boshqaruvi, taymer va h.k. Hodisalar modeli uchga bo’linadi.

* hodisa manbai
* hodisa ob’ekti
* hodisa tinglovchisi

Hodisa manbai bu holati o’zgaruvchi ob’ektdir. Bu hodisalarni ishlab chiqaradi. Hodisa ob’ekti (Hodisa) hodisa manbaining o’zgarish holatlarini jamlaydi. Hodisa tinglovchisi ogohlantirilishni xohlovchi ob’ekt. Hodisa manbai ob’ekti hodisani tutuvchi topshiriqni hodisa tinglovchisiga vakil qilib yuboradi.

Java Swing da hodisa tutish uskunalari juda kuchli va mostlashuvchan qilib yo’lga qo’yilgan. Java Hodisa va’kili modelidan foydalanadi. Biz maxsus hodisa sodir bo’lganda ogohlantiriladigan ob’ektlarni aniqlaymiz.

HODISA OB’EKTI
Dasturda biror narsa sodir bo’lsa, hodisa ob’ekti yasaladi. Masalan, biz tugmaning ustiga chertgan yoki ro’yhatning biror qismini tanlagan vaqtimizda. Hodisalarning ko’p turi bor. ActionEvent, TextEvent, FocusEvent, ComponentEvent va boshq. Ularning har biri mahsus holatlarda yasaladi.

Hodisa ob’ektida sodir etilgan hodisa to’g’risidagi ma’lumot mavjud bo’ladi. Navbatdagi misolimizda ‘ActionEvent’ni batafsilroq tahlil qilamiz.
*****************************************************************************

[highlighter]

import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import javax.swing.DefaultListModel;
 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JList;
 import javax.swing.JPanel;
 import javax.swing.SwingUtilities;
 public class ActionEventgaMisol extends JFrame implements ActionListener {
 private JList royhat;
 private DefaultListModel model;
 public ActionEventgaMisol() {
 initFM();
 }
 public final void initFM() {
 JPanel panel = new JPanel();
 panel.setLayout(null);
 model = new DefaultListModel();
 royhat = new JList(model);
 royhat.setBounds(150, 30, 250, 150);
 JButton okTugma = new JButton("Ok");
 okTugma.setBounds(30, 35, 80, 25);
 okTugma.addActionListener(this);
 panel.add(okTugma);
 panel.add(royhat);
 add(panel);
 setTitle("Hodisa ob'ekti");
 setSize(450, 250);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 }
 public void actionPerformed(ActionEvent hodisa) {
 String hodisaVaqti = String.format("%tT", hodisa.getWhen());
 if (!model.isEmpty()) {
 model.clear();
 }
 if (hodisa.getID() == ActionEvent.ACTION_PERFORMED) {
 model.addElement(" Hodisa aniqlovchisi: ACTION_PERFORMED");
 }
 model.addElement(" Vaqt: " + hodisaVaqti);
 String manba = hodisa.getSource().getClass().getName();
 model.addElement(" Hodisa manbai: " + manba);
 int toldiruvchi = hodisa.getModifiers();
 StringBuffer bufer = new StringBuffer(" To'ldiruvchilar: ");
 if ((toldiruvchi & ActionEvent.ALT_MASK) > 0) {
 bufer.append("Alt ");
 }
 if ((toldiruvchi & ActionEvent.SHIFT_MASK) > 0) {
 bufer.append("Shift ");
 }
 if ((toldiruvchi & ActionEvent.META_MASK) > 0) {
 bufer.append("Meta ");
 }
 if ((toldiruvchi & ActionEvent.CTRL_MASK) > 0) {
 bufer.append("Ctrl ");
 }
 model.addElement(bufer);
 }
 public static void main(String[] args) {
 SwingUtilities.invokeLater(new Runnable() {
 public void run() {
 ActionEventgaMisol misol = new ActionEventgaMisol();
 misol.setVisible(true);
 }
 });
 }
 }

*****************************************************************************

Misoldagi kod, tugma va ro’yhat komponentlaridan iborat oynani yasaydi. Agar tugmaga chertsak, hodisa to’g’risidagi ma’lumot ro’yhatga yoziladi. Bizning holatimizda, biz ActionEvent klassi haqida gaplashyapmiz. Ma’lumotlar hodisa sodir etilgan vaqt, hodisa aniqlovchisi, hodisa manbasi va to’ldiruvchilardan iborat.

public void actionPerformed(ActionEvent hodisa) {
 ActionEvent bu sodir etilgan hodisa.
String hodisaVaqti = String.format("%tT", hodisa.getWhen())

;

Bu yerda hodisa sodir etilgan vaqtni o’zlashtiyapmiz. ‘ActionEvent’ ning getWhen() metodi, hodisa bajarilgan vaqtni millisekundlarda javob qilib qaytaradi. Uni 24 soatlik formatda daqiqa va soniyalari bilan qo’shib chiqarish uchun Stringning format() statik metodidan foydalanildi.

String manba = hodisa.getSource().getClass().getName();
 model.addElement(" Hodisa manbai: " + manba);

Bu yerda hodisa manbai nomi ro’yharga qo’shildi. Bizning holatimizdagi manba JButton.

int toldiruvchi = hodisa.getModifiers();

Biz to’ldiruvchi orqali klavishalar bosilgandagi ma’lumotni.

if ((toldiruvchi & ActionEvent.ALT_MASK) > 0) {
 bufer.append("Alt ");
 }

Bu yerda Alt tugmasi ham bosilgan yoki yo’qligi aniqlanyapti. “to’ldiruvchi & ActionEvent.ALT_MASK”ni ko’rib hayron bo’layotgan bo’lishingiz mumkin. Bu bitwise VA operatori deyladi. U operandlarni baytlarda emas bitlarda solishtirib chiqadi, operandlar bir hil bo’lsa 1, bir hil bo’lmasa 0 bo’ladi. Masalan: 0&0=1, 0&1=0, 1&0=0 hamda 1&1=1 bo’ladi. Quyida bitwise VA operatori qanday hisoblanishi ko’rsatilgan: (72 & 184 = 8)

01001000 &
 10111000 =
 ------------
 00001000

Hozirgi holatimizda, JButton ga sichqonchani chap tugmasini chertsak to’ldiruvchimiz 16 ga teng bo’ladi, enterni bossak 0 ga. ActionEvent.ALT_MASK 8 ga teng. Shunday ekan Alt bilan sichqonchaning chap tugmasi qo’shib bosilsa to’ldiruvchimiz 24 ga teng bo’ladi (16+8=24) ActionEvent.SHIFT_MASK=1 bo’lganligidan, sichqoncahning chap tugmasi Shift bilan qo’shib bosilganda to’ldiruvchi 17 ga teng bo’ladi. Huddi shunga o’xshab, ActionEvent.CTRL_MASK=2 bo’lgani uchun sichqonchani chap tugmasi bilan Ctrl birga bosilsa to’ldiruvchi 18 bo’ladi. Buni esa bizning holatimizdagisi Alt ni ushlab sichqoncahning chap tugmasi bosilganda. to’ldiruvchi=24 bo’lishi va ActionEvent.ALT_MASK=8 ekanligidan “toldiruvchi & ActionEvent.ALT_MASK” qanday natija berishini hisoblab chiqaylik.

11000 & (24)
 01000 = (8)
 ---------
 01000 (8)

Demak Alt bilan bossak ((toldiruvchi & ActionEvent.ALT_MASK) > 0) ifoda (8>0) bilan bir hil bo’ladi va bu true javob qaytaradi, natijada esa shart bajariladi.

BAJARILISH
Java Swing da hodisalarni tutishning bir necha hil usullari bor.
* Nomsiz ichki klas
* Ichki klas
* Ajratib olingan klass

NOMSIZ ICHKI KLASS
Biz yuqoridagi tushunchalarni oddiy hodisa misolida ko’rib chiqamiz.
*******************************************************************************

[highlighter]

import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import javax.swing.SwingUtilities;
public class NomsizIchkiKlasgaMisol extends JFrame {
public NomsizIchkiKlasgaMisol() {
initFM();
 }
public final void initFM() {
JPanel panel = new JPanel();
 panel.setLayout(null);
JButton yopishTugmasi = new JButton("Yopish");
 yopishTugmasi.setBounds(40, 50, 80, 25);
yopishTugmasi.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent event) {
 System.exit(0);
 }
 });
panel.add(yopishTugmasi);
 add(panel);
setTitle("Nomsiz ichki klas");
 setSize(300, 200);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 }
public static void main(String[] args) {
 SwingUtilities.invokeLater(new Runnable() {
 public void run() {
 NomsizIchkiKlasgaMisol misol =
 new NomsizIchkiKlasgaMisol();
 misol.setVisible(true);
 }
 });
 }
 }

*******************************************************************************
Bu misolda, ustiga bosilganda oynani berkitadigan tugma yasadik.

JButton yopishTugmasi = new JButton("Yopish");
 yopishTugmasi hodisa manbai. Hodisalar shu tugmadan kelib chiqadi.
yopishTugmasi.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent event) {
 System.exit(0);
 }
 });

Bu yerda tugma uchun hodisa tinglovchi ro’yhatga olinyapti. Bu uslub bilan hodisalar hodisa mo’ljaliga yuboriladi. Bizning misolimizda hodisa mo’ljali ActionListener klasi. Bu kodda biz nomsiz ichki klasdan foydalandik.

ICHKI KLASS
Bu yerda biz misolimizni ichki ActionListener klasidan foydalanib bajaramiz.
******************************************************************

import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import javax.swing.SwingUtilities;
public class IchkiKlasgaMisol extends JFrame {
public IchkiKlasgaMisol() {
 initFM();
 }
public final void initFM() {
 JPanel panel = new JPanel();
 panel.setLayout(null);
JButton yopishTugmasi = new JButton("Yopish");
 yopishTugmasi.setBounds(40, 50, 80, 25);
yopishTugmasiTinglovchisi tinglovchi = new yopishTugmasiTinglovchisi();
 yopishTugmasi.addActionListener(tinglovchi);
panel.add(yopishTugmasi);
 add(panel);
setTitle("Ichki klasga misol");
 setSize(300, 200);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 }
class yopishTugmasiTinglovchisi implements ActionListener {
 public void actionPerformed(ActionEvent hodisa) {
 System.exit(0);
 }
 }
public static void main(String[] args) {
 SwingUtilities.invokeLater(new Runnable() {
 public void run() {
 IchkiKlasgaMisol misol = new IchkiKlasgaMisol();
 misol.setVisible(true);
 }
 });
 }
 }

*******************************************************************************************

Bizda panelda yopish tugmasi joylashgan. Tinglovchi nom berilgan (yopishTugmasiTinglovchisi) ichki klassda aniqlangan.

JButton yopishTugmasi = new JButton("Yopish");
 yopishTugmasi.setBounds(40, 50, 80, 25);

Mana bu nomsiz bo’lmagan ichki klassimiz.

class yopishTugmasiTinglovchisi implements ActionListener {
 public void actionPerformed(ActionEvent hodisa) {
 System.exit(0);
 }
 }

Tugmaning hodisa tinglovchisi shu yerda yasalgan.

TINGLOVCHINI BAJARTIRUVCHI AJRATIB OLINGAN KLASS
Quiydagi misolda komonentdan nasl olinib, klassning ichida hodisa tinglovchisi bajartirilgan.

*********************************************************************
[highlighter]

import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import javax.swing.SwingUtilities;
public class AjratibOlinganKlasgaMisol extends JFrame {
public AjratibOlinganKlasgaMisol() {
 initFM();
 }
public final void initFM() {
 JPanel panel = new JPanel();
 panel.setLayout(null);
MeningTugmam yopishTugmasi = new MeningTugmam("Yopish");
 yopishTugmasi.setBounds(40, 50, 80, 25);
panel.add(yopishTugmasi);
 add(panel);
setTitle("Ajratib olinganklas");
 setSize(300, 200);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 }
class MeningTugmam extends JButton implements ActionListener {
 public MeningTugmam(String matn) {
 super.setText(matn);
 addActionListener(this);
 }
public void actionPerformed(ActionEvent e) {
 System.exit(0);
 }
 }
public static void main(String[] args) {
 SwingUtilities.invokeLater(new Runnable() {
 public void run() {
 AjratibOlinganKlasgaMisol misol = new AjratibOlinganKlasgaMisol();
 misol.setVisible(true);
 }
 });
 }
 }

*********************************************************************

Bu misolda biz hodisa tinglovchini bajartiruvchi MeningTugmam klasini yasadik.

MeningTugmam yopishTugmasi = new MeningTugmam("Yopish");

Bu yerda biz MeningTugmam klasidan ob’ekt olyapmiz.

class MeningTugmam extends JButton implements ActionListener {
MeningTugmam klasi JButtondan nasl olib yasalgan. U esa ActionListener interfeysini bajartiradi. Shu yo’l bilan MeningTugmam klassida hodisa tutish nazoratga olingan.

addActionListener(this);

Bu yerda MeningTugmam klassiga hodisa tutuvchi qo’shyapmiz.

KO’P MANBALAR
Bitta tinglovchi bir nechta manbalarga ham ulanishi mumkin. Buni quyidagi misolda ko’ramiz.
**************************************************************

[highlighter]

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class KopManbalar extends JFrame {
JLabel statusbar;
public KopManbalar() {
initFM();
}
public final void initFM() {
JPanel panel = new JPanel();
statusbar = new JLabel(" Statusbar");
statusbar.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
panel.setLayout(null);
JButton yopishTugmasi = new JButton("Yopish");
yopishTugmasi.setBounds(40, 30, 80, 25);
yopishTugmasi.addActionListener(new TugmaTinglovchi());
JButton ochishTugmasi = new JButton("Ochish");
ochishTugmasi.setBounds(40, 80, 80, 25);
ochishTugmasi.addActionListener(new TugmaTinglovchi());
JButton topishTugmasi = new JButton("Topish");
topishTugmasi.setBounds(40, 130, 80, 25);
topishTugmasi.addActionListener(new TugmaTinglovchi());
JButton saqlashTugmasi = new JButton("Saqlash");
saqlashTugmasi.setBounds(40, 180, 80, 25);
saqlashTugmasi.addActionListener(new TugmaTinglovchi());
panel.add(yopishTugmasi);
panel.add(ochishTugmasi);
panel.add(topishTugmasi);
panel.add(saqlashTugmasi);
add(panel);
add(statusbar, BorderLayout.SOUTH);
setTitle("Ko'p manbalar");
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class TugmaTinglovchi implements ActionListener {
public void actionPerformed(ActionEvent hodisa) {
JButton tugma = (JButton) hodisa.getSource();
String label = tugma.getText();
statusbar.setText(" " + label + " tugmasi bosildi");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
KopManbalar km = new KopManbalar();
km.setVisible(true);
}
});
}
}

**************************************************************

Biz to’rtta tugma va statusbar yasadik. Statusbarga tugma ustiga cherilganli to’g’risidagi ma’lumotni chiqaramiz.

yopishTugmasi.addActionListener(new TugmaTinglovchi());
 ...
 ochishTugmasi.addActionListener(new TugmaTinglovchi());
 ...
 Har bir tugma TugmaTinglovchi klasiga ro'yhatga olinyapti.
JButton tugma = (JButton) hodisa.getSource();
 String label = tugma.getText();
 Shu yerda qaysi tugma bosilganini aniqlab olyapmiz.
statusbar.setText(" " + label + " tugmasi bosildi");

 

Bu ifoda status bardagi yozuvni yangilaydi.

KO’P SONLI TINGLOVCHILAR
Biz bitta hodisa uchun bir nechta qaydlar ham yasashimiz mumkin.
****************************************************************************
[highlighter]

import java.awt.BorderLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.util.GregorianCalendar;
import javax.swing.BorderFactory;
 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JPanel;
 import javax.swing.JSpinner;
 import javax.swing.SpinnerModel;
 import javax.swing.SpinnerNumberModel;
 import javax.swing.SwingUtilities;
 import javax.swing.border.EtchedBorder;
public class KopSonliTinglovchilar extends JFrame {
private JLabel statusbar;
 private JSpinner aylantirgich;
 private static int sanoq = 0;
public KopSonliTinglovchilar() {
 initFM();
 }
public final void initFM() {
 JPanel panel = new JPanel();
 statusbar = new JLabel("0");
statusbar.setBorder(BorderFactory.createEtchedBorder(
 EtchedBorder.RAISED));
panel.setLayout(null);
JButton qoshishTugma = new JButton("+");
 qoshishTugma.setBounds(40, 30, 80, 25);
 qoshishTugma.addActionListener(new TugmaTinglovchi1());
 qoshishTugma.addActionListener(new TugmaTinglovchi2());
GregorianCalendar kalendar = new GregorianCalendar();
 int joriyYil = kalendar.get(kalendar.YEAR);
SpinnerModel yilModel = new SpinnerNumberModel(joriyYil,
 joriyYil - 100,
 joriyYil + 100,
 1);
aylantirgich = new JSpinner(yilModel);
 aylantirgich.setEditor(new JSpinner.NumberEditor(aylantirgich, "#"));
aylantirgich.setBounds(190, 30, 80, 25);
panel.add(qoshishTugma);
 panel.add(aylantirgich);
add(panel);
 add(statusbar, BorderLayout.SOUTH);
setTitle("Kop sonli tinglovchilar");
 setSize(300, 200);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 }
class TugmaTinglovchi1 implements ActionListener {
 public void actionPerformed(ActionEvent hodisa) {
 Integer qiymat = (Integer) aylantirgich.getValue();
 aylantirgich.setValue(++qiymat);
 }
 }
class TugmaTinglovchi2 implements ActionListener {
 public void actionPerformed(ActionEvent e) {
 statusbar.setText(Integer.toString(++sanoq));
 }
 }
public static void main(String[] args) {
 SwingUtilities.invokeLater(new Runnable() {
 public void run() {
 KopSonliTinglovchilar kst = new KopSonliTinglovchilar();
 kst.setVisible(true);
 }
 });
 }
 }

****************************************************************************

Bu misolimizda oynaga tugma, aylantirgich, va statusbar joyladik. Biz bitta hodisa uchun ikkita tinglovchidan foydalandik. Tugmaga bir martta chertilishi natijasida aylantirgich komponentiga 1 qiymat qo’shiladi, va status bardagi ma’lumot yangilanadi. ‘statusbar’da tugmaga necha martta chertilgani ko’rinib turadi.

qoshishTugma.addActionListener(new TugmaTinglovchi1());
qoshishTugma.addActionListener(new TugmaTinglovchi2());

Biz ikkita tugma tinglovchisi qayd qildik

SpinnerModel yilModel = new SpinnerNumberModel(joriyYil,
 joriyYil - 100,
 joriyYil + 100,
 1);
 aylantirgich = new JSpinner(yilModel);

Bu yerda aylantirgich komponenti yasaldi. Bu yil modeli aylantirgichini ishlatdik. SpinnerNumberModel argumentlari dastlabki, minimum, maksimum qiymatlar va qadamni o’z ichiga oladi.

aylantirgich.setEditor(new JSpinner.NumberEditor(aylantirgich, “#”));
Bu qatordagi ifoda mingliklar guruhini ajratilishini bekor qilish uchun kerak. Chunki oddiy holda aylantirgi raqamlarni yuzliklar, mingliklar va h.k guruhlarga ajratib ko’rsatadi.

Integer qiymat = (Integer) aylantirgich.getValue();
aylantirgich.setValue(++qiymat);
Bu yerda biz yilning qiymatini orttiryapmiz.

TINGLOVCHILARNI O’CHIRISH
Java Swing uskunalari yordamida qayd etilgan tinglovchilarni o’chirish imkoniyatimiz ham bor.
************************************************************************
[highlighter]

import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.awt.event.ItemEvent;
 import java.awt.event.ItemListener;
import javax.swing.JButton;
 import javax.swing.JCheckBox;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JPanel;
 import javax.swing.SwingUtilities;
public class TinglovchiOchirishgaMisol extends JFrame {
private JLabel matn;
 private JButton qoshish;
 private JCheckBox faollik;
 private TugmaTinglovchi tinglovchi;
 private static int sanoq = 0;
public TinglovchiOchirishgaMisol() {
 JPanel panel = new JPanel();
panel.setLayout(null);
qoshish = new JButton("+");
 qoshish.setBounds(20, 30, 80, 25);
 tinglovchi = new TugmaTinglovchi();
faollik = new JCheckBox("Tinglovchini faollashtirish");
 faollik.setBounds(110, 30, 200, 25);
faollik.addItemListener(new ItemListener() {
 public void itemStateChanged(ItemEvent event) {
 if (faollik.isSelected()) {
 qoshish.addActionListener(tinglovchi);
 } else {
 qoshish.removeActionListener(tinglovchi);
 }
 }
 });
matn = new JLabel("0");
 matn.setBounds(40, 80, 80, 25);
panel.add(qoshish);
 panel.add(faollik);
 panel.add(matn);
add(panel);
setTitle("Tinglovchini o'chirish");
 setSize(310, 200);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 }
class TugmaTinglovchi implements ActionListener {
 public void actionPerformed(ActionEvent e) {
 matn.setText(Integer.toString(++sanoq));
 }
 }
public static void main(String[] args) {
 SwingUtilities.invokeLater(new Runnable() {
 public void run() {
 TinglovchiOchirishgaMisol misol = new TinglovchiOchirishgaMisol();
 misol.setVisible(true);
 }
 });
 }
 }

************************************************************************

Panelga 3 ta komponent o’rnatildi. Tugma, Checkbox va Label. Checkboxga chertib tugmaga tinglovchi qo’shishimiz yoki o’chirishimiz mumkin.

tinglovchi = new TugmaTinglovchi();

Keyinchalik tinglovchini o’chirishga zarurat tug’ilganda, uning nomini ko’rsatish kerak bo’ladi. Shuning uchun nomsiz bo’lmagan tinglovchi yasab oldik.

if (faollik.isSelected()) {
 qoshish.addActionListener(tinglovchi);
 } else {
 qoshish.removeActionListener(tinglovchi);
 }

Checkbox tanlangan yoki yo’qligini tekshirib, unga ko’ra tinglovchini qo’shib yoki o’chiryapmiz.

OYNANI SURISH
Quyidafi misol oynaning ekrandagi joylashgan o’rnini kuzatib boradi.
*******************************************************************************
[highlighter]

import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class OynaSurishgaMisol extends JFrame
implements ComponentListener {
private JLabel labelX;
private JLabel labelY;
public OynaSurishgaMisol() {
initFM();
}
public final void initFM() {
JPanel panel = new JPanel();
panel.setLayout(null);
labelX = new JLabel("x: ");
labelX.setFont(new Font("Serif", Font.BOLD, 14));
labelX.setBounds(20, 20, 60, 25);
labelY = new JLabel("y: ");
labelY.setFont(new Font("Serif", Font.BOLD, 14));
labelY.setBounds(20, 45, 60, 25);
panel.add(labelX);
panel.add(labelY);
add(panel);
addComponentListener(this);
setTitle("OynaSurish");
setSize(310, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void componentResized(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
int x = e.getComponent().getX();
int y = e.getComponent().getY();
labelX.setText("x: " + x);
labelY.setText("y: " + y);
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
OynaSurishgaMisol misol = new OynaSurishgaMisol();
misol.setVisible(true);
}
});
}
}

*******************************************************************************

Bu misol oynaning joriy koordinatalarini panelda ko’rsatadi. Oynaning o’rni to’g’risidagi ma’lumotlarni olishda ComponentListener dan foydalandik.

labelX.setFont(new Font("Serif", Font.BOLD, 14));

Komponentlarning shrift razmeri odatda kichikroq bo’ladi. Biz shu yo’l bilan uni kattalashtirdik.

int x = e.getComponent().getX();
int y = e.getComponent().getY();

Bu yerda oynaning x va y koordinatalari qiymatini oldik.

Shuni yodda tutingki, biz ComponentListenerni implement qilishga va’da berganimizdan keyin, garchi hammasidan foydalanmasak-da uning to’rtala metodini ham bajartirishimiz shart.

ADAPTERLAR
Adapterlar juda qulay klasslar.Avvalgi misoldagi kodimizda, hatto foydalanmasak ham, ComponentListener ning hamma, to’rtala metodini bajartirdik. Zaruratsiz narsalarga kod yozishdan qochish uchun, adapterlardan foydalanganimiz ma’qul. Adapterlar barcha zaruriy metodlarni bajartiradigan klasslardir. Ular aslida bo’sh. Biz faqat o’zimizga zarur metodlarni ishlatamiz. Tugmani cheritilishj hodisasi uchun adapter klass yo’q. Chunki unda o’zi faqat actionPerformed() metodini bajartiramiz holos. Biz adapterlarni zaruratsiz, birdan ortiq metodlarni bajartirishimiz kerak bo’lib qolganda ishlatamiz.
Quyidagi misol avvalgi misoldagi ishning aynan o’zini ComponentAdapter klassidan foydalanib qiladi.
*************************************************************************
[highlighter]

import java.awt.Font;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class AdaptergaMisol extends JFrame {
private JLabel labelX;
private JLabel labelY;
public AdaptergaMisol() {
initFM();
}
public final void initFM() {
JPanel panel = new JPanel();
panel.setLayout(null);
labelX = new JLabel("x: ");
labelX.setFont(new Font("Serif", Font.BOLD, 14));
labelX.setBounds(20, 20, 60, 25);
labelY = new JLabel("y: ");
labelY.setFont(new Font("Serif", Font.BOLD, 14));
labelY.setBounds(20, 45, 60, 25);
panel.add(labelX);
panel.add(labelY);
add(panel);
addComponentListener(new SurilishAdapteri());
setTitle("Adapterga misol");
setSize(310, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class SurilishAdapteri extends ComponentAdapter {
public void componentMoved(ComponentEvent hodisa) {
int x = hodisa.getComponent().getX();
int y = hodisa.getComponent().getY();
labelX.setText("x: " + x);
labelY.setText("y: " + y);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AdaptergaMisol misol = new AdaptergaMisol();
misol.setVisible(true);
}
});
}
}

*************************************************************************

Ushbu misolda avvalgi misol qaytadan yozildi. Bu yerda miz ‘ComponentAdapter’ dan foydalanyapmiz

addComponentListener(new SurilishAdapteri());

Bu yerda komponent tinglovchisi qayd etildi.

class SurilishAdapteri extends ComponentAdapter {
 public void componentMoved(ComponentEvent hodisa) {
 int x = hodisa.getComponent().getX();
 int y = hodisa.getComponent().getY();
 labelX.setText("x: " + x);
 labelY.setText("y: " + y);
 }
 }

SurilishAdapteri ichki klassi ichida componentMoved() metodiga kod yozdik. Boshqa barcha metodlar bo’sh qoldirildi.

Java Swing qo’llanmasining bu qismida Swing hodisalari bilan tanishdik.

(257 marta o'qilgan, bugun 1 marta o'qildi)

O'xshash maqolalar: