Java is specially designed for GUI programming. So we here start our chapter with making GUI........
To work with GUI we need a main window to work with. In Java we can use JFrame, JApplet, or JPanel to create GUI. The best practice is to use JFrame.
Here we have a sample class which make a GUI with JFrame....
To work with GUI we need a main window to work with. In Java we can use JFrame, JApplet, or JPanel to create GUI. The best practice is to use JFrame.
Here we have a sample class which make a GUI with JFrame....
Sample GUI class in Java :
// package
package mpc;
// imports
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
// class extends jframe or jpanel
public class App extends JFrame{
// constructors
public App() {
initComp();
}
// main method
public static void main(String[] args) {
new App();
}
// initComp method
void initComp() {
this.myBtn();
this.myLbl();
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setBounds(10, 10, 300, 350);
this.setVisible(true);
}
// 1st component’s method
void myBtn() {
btn=new JButton();
btn.setText("Click");
btn.setBounds(5, 5, 100, 25);
btn.setVisible(true);
this.add(btn);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
myBtnActionPerformed(e);}
});
}
// 1st component’s event handler
void myBtnActionPerformed(ActionEvent e){
lbl.setText("Hello.");
}
// 2nd component’s method
void myLbl() {
lbl=new JLabel();
lbl.setText("");
lbl.setBounds(7, 30, 100, 35);
lbl.setVisible(true);
this.add(lbl);
}
// variable and component dec.
JLabel lbl;
JButton btn;
}
this will work,start today........
ReplyDelete