JButton getIcon () and setIcon () Method
JButton class is used to create labelled buttons.This class comes with several methods like setToolTipText ,addActionListener,getIcon,setIcon etc.
Today we are going to look into details on setIcon and getIcon JButton class methods.
Today we are going to look into details on setIcon and getIcon JButton class methods.
JButton getIcon and setIcon Methods:
[
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.ImageIcon; import javax.swing.JLabel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class JavaJButton { public static void main(String args[]) { JFrame frame=new JFrame("Jbutton Example"); JButton button=new JButton("Save"); button.setIcon(new ImageIcon(JavaJButton.class.getResource("save.png"))); ImageIcon icon=(ImageIcon)button.getIcon(); JLabel field=new JLabel(); field.setBounds(50,50, 150,20); frame.add(field); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { field.setIcon(icon); } }); button.setBounds(100,100,95,30); frame.add(button); frame.setSize(400,400); frame.setLocationRelativeTo(null); frame.setLayout(null); frame.setVisible(true); } }
]
Code Analysis
Code [button.setIcon(new ImageIcon(JavaJButton.class.getResource("save.png")));] is used to setIcon to the button.
Code [ImageIcon icon=(ImageIcon)button.getIcon();] is used to retrieve icon from JButton.
Code
[
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { field.setIcon(icon); } });
]
is used to add the icon to a JLabel when the button is clicked and actionListener class is invoked.