import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
public class MainPanel extends javax.swing.JPanel{
int count=0;
MainFrame mf;
public MainPanel(MainFrame mf){
this.mf=mf;
setLayout(null);
actionListenerButton(50,60);
mouseListenerButton(50,90);
setBackground(Color.WHITE);
}
/**create a button that implemented action listener
*
*/
public void actionListenerButton(int x,int y){
final JButton btn=new JButton("Action Listener");
//set mouse location x-axis and y-axis, width and height
//setBounds(x-axis,y-axis,width,height)
btn.setBounds(x,y,150,25);
//implement action to button by using action listener
btn.addActionListener(new ActionListener(){
//perform an action after click(press and release) the button
public void actionPerformed(ActionEvent e){
//write button action here
count++;
repaint();
}
});
add(btn);
}
/**create a button that implemented mouse listener
*
*/
public void mouseListenerButton(int x,int y){
final JButton btn=new JButton("Mouse Listener");
//set mouse location x-axis and y-axis, width and height
//setBounds(x-axis,y-axis,width,height)
btn.setBounds(x,y,150,25);
//implement action to button by using mouse listener
btn.addMouseListener(new MouseListener(){
Color defaultBG=btn.getBackground();
//perform an action when the cursor/pointer exit/move away from the button
public void mouseExited(MouseEvent e){
btn.setText("Mouse Listener");
//reset button background
btn.setBackground(defaultBG);
}
//perform an action when the cursor/pointer enter/move into the button
public void mouseEntered(MouseEvent e){
btn.setText("Mouse Entered");
btn.setBackground(Color.YELLOW);
}
//perform an action when the mouse has been released on the button
public void mouseReleased(MouseEvent e){
btn.setText("Mouse Released");
//reset button background
btn.setBackground(defaultBG);
}
//perform an action when the mouse has been pressed on the button
public void mousePressed(MouseEvent e){
btn.setText("Mouse Pressed");
btn.setBackground(Color.YELLOW);
}
//perform an action after click(press and release) the button
public void mouseClicked(MouseEvent e){
//write button action here
count++;
repaint();
}
});
add(btn);
}
public void paint (Graphics g){
super.paint(g);
g.drawString(String.format("Count++ = %d",count),30,45);
}
}