当前位置: 技术问答>java相关
如何实现右键单击按钮,按钮上出现图片。谢谢
来源: 互联网 发布时间:2015-03-24
本文导语: 我想做个扫雷,如何实现右键单击按钮,按钮上出现图片。谢谢 | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Frame1 extends Frame { public JButton b1 = new JButton(" b1 "); publi...
我想做个扫雷,如何实现右键单击按钮,按钮上出现图片。谢谢
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frame1 extends Frame {
public JButton b1 = new JButton(" b1 ");
public Frame1() {
this.setLayout(null);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(MouseEvent e) {
b1_mouseClicked(e);
}
});
b1.setBounds(new Rectangle(100, 39, 55, 22));
this.add(b1);
}
void b1_mouseClicked(MouseEvent e)
{
if(!SwingUtilities.isRightMouseButton(e))
return;
JButton jb=(JButton)e.getSource();
if(jb.getIcon()!=null)
return;
//hi.gif should be put under the same directory as the class file
jb.setIcon(new ImageIcon("hi.gif"));
}
public static void main(String[] args) {
Frame1 frame = new Frame1();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setSize(300, 400);
frame.setVisible(true);
}
}
import java.awt.event.*;
import javax.swing.*;
public class Frame1 extends Frame {
public JButton b1 = new JButton(" b1 ");
public Frame1() {
this.setLayout(null);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(MouseEvent e) {
b1_mouseClicked(e);
}
});
b1.setBounds(new Rectangle(100, 39, 55, 22));
this.add(b1);
}
void b1_mouseClicked(MouseEvent e)
{
if(!SwingUtilities.isRightMouseButton(e))
return;
JButton jb=(JButton)e.getSource();
if(jb.getIcon()!=null)
return;
//hi.gif should be put under the same directory as the class file
jb.setIcon(new ImageIcon("hi.gif"));
}
public static void main(String[] args) {
Frame1 frame = new Frame1();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setSize(300, 400);
frame.setVisible(true);
}
}