Tugmalar va yozuvlar Tugma bu biron bir amalni bajarish uchun foydalanuvchi ruxsatini olish uchun ishlatiladigan
element xisoblanadi. Java dasturlash tilida tugmalarni
JButton
klassi andozasi yordamida yaratib
olish mumkin. Masalan:
JButton button = new JButton();
Dastur kodi yangi tugma yaratib uni button o’zgaruvchisiga biriktirib beradi. Yuqoridagi
dastur kodi xech qanday yozuvga ega bo’lmagan tugmani yaratib beradi. Ammo, foydalanishni
osonlashtirish maqsadida xar bir tugma bajaradigan amaliga asosan nomga ega bo’lishi kerak.
Nomga ega tugmani yaratib olish uchun quyidagi dastur kodidan foydalanish mumkin:
JButton button = new JButton(“OK”);
Ushbu dastur kodi quyidagi tugmani yaratib beradi
JButton
klassi yordamida yaratilgan tugma JButton
klassi tugmalarga matndan tashqari rasm joylashtirish imkonini xam beradi.
Rasmni fayldan yuklash uchun
ImageIcon
klassidan foydalaniladi. Masalan:
import java.awt.*;
import javax.swing.*;
public class RasmliTugma{
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
Icon icon = new ImageIcon("search.png");
JButton button = new JButton("OK", icon);
panel.add(button);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
frame.setVisible(true);
}
}
Ushbu dastur quyidagi oynani ekranga chiqarib beradi:
JButton
klassi yordamida yaratilgan rasmli tugma Java dasturlash tilida tugma bosilganda
ActionEvent
xodisasi xosil qilinadi. Ushbu xodisani
qabul qilish uchun dastur xodisalarni nazorat qiluvchi
ActionListener
interfeysini bajarishi va
uning
actionPerformed()
metodini qayta yaratishi kerak bo’ladi.
actionPerformed()
metodi
ichiga tugma bosilganda bajarilishi kerak bo’ladigan amallar kiritiladi. Masalan:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TugmaAmali
{
JPanel panel;
Color backgroundColor = Color.YELLOW;
JButton button;
String tugmaMatni = "Sariq";
public static void main(String[] args)
{
TugmaAmali ta = new TugmaAmali();
ta.go();
}
public void go()
{
JFrame frame = new JFrame("TugmaAmali");
panel = new JPanel();
panel.setBackground(backgroundColor);
button = new JButton(tugmaMatni);
button.addActionListener(new ButtonListener());
panel.add(button);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
frame.setVisible(true);
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(backgroundColor == Color.YELLOW)
{
backgroundColor = Color.RED;
tugmaMatni = "Qizil";
}else{
backgroundColor = Color.YELLOW;
tugmaMatni = "Sariq";
}
panel.setBackground(backgroundColor);
button.setText(tugmaMatni);
}
}
}
Yuqoridagi dastur tugma bosilganda oyna rangi sariq rangdan qizil rangga o’zgaradi.
Tugma xosil qilgan xodisa asosida amal bajarish