Jbutton is an important component for event handling , lets get best use from it
1. A Simple JButton Example
|
public class JButtonExample extends JFrame {
public JButtonExample() {
this.setTitle("SimpleExample");
this.setBounds(600, 200, 300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pnlOuter = new JPanel();
pnlOuter.setBackground(Color.GRAY);
this.setLayout(new BorderLayout());
JButton btnTest = new JButton("Simple Test");
btnTest.setBounds(10,
20, 80, 40);
pnlOuter.add(btnTest);
this.add(pnlOuter, BorderLayout.CENTER);
}
public static void
main(String[] args) {
JButtonExample testFrame
= new JButtonExample();
testFrame.setVisible(true);
}
}
|
2. JButton with Image
ImageIcon
starIcon = new ImageIcon("images/star.jpg");
JButton btnTest2 = new JButton("Star",starIcon);
btnTest.setBounds(10, 80, 80, 40);
pnlOuter.add(btnTest2);
|
3. JButton with HTML (It can be used as image with text)
This code can be used to display text along with image.This text can be change programatically as well which help to get more control over components
ImageIcon
titleIcon= new ImageIcon("images/titleIcon.jpg");
JButton
btnTest = new JButton("<HTML><BODY><I><U>Test</U> <FONT
color=red >Look</FONT> </I></BODY></HTML>",titleIcon);
btnTest.setBounds(10, 20, 80, 40);
pnlOuter.add(btnTest);
|
4. Jbutton with only image (no border)
This can be used as fancy button.
ImageIcon
titleIcon= new ImageIcon("images/starIcon2.jpg");
JButton
btnTest3 = new JButton();
btnTest3.setIcon(starIcon2);
btnTest3.setBorder(new EmptyBorder(0, 0, 0, 0));
btnTest.setLocation(80, 120);
pnlOuter.add(btnTest3);
|
5. Code with all images
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class JButtonExample extends JFrame {
public JButtonExample() {
this.setTitle("JButton Example");
this.setBounds(600, 200, 300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon titleIcon = new ImageIcon("images/titleIcon.png");
this.setIconImage(titleIcon.getImage());
JPanel pnlOuter = new JPanel();
pnlOuter.setBackground(Color.GRAY);
this.setLayout(new
BorderLayout());
JButton btnTest = new JButton("<HTML><BODY><I><U>Test</U>
<FONT color=red >Look</FONT>
</I></BODY></HTML>",titleIcon);
btnTest.setBounds(10, 20, 80, 40);
pnlOuter.add(btnTest);
ImageIcon starIcon = new ImageIcon("images/star.jpg");
JButton btnTest2 = new JButton("Star",starIcon);
btnTest.setBounds(10, 80, 80, 40);
pnlOuter.add(btnTest2);
ImageIcon starIcon2 = new ImageIcon("images/star2.jpg");
JButton btnTest3 = new JButton();
btnTest3.setIcon(starIcon2);
btnTest3.setBorder(new EmptyBorder(0, 0, 0, 0));
btnTest.setLocation(80, 120);
pnlOuter.add(btnTest3);
this.add(pnlOuter, BorderLayout.CENTER);
}
public static void main(String[] args) {
JButtonExample testFrame = new JButtonExample();
testFrame.setVisible(true);
}
}
|
No comments:
Post a Comment