
static String path=System.getProperty("user.dir")+"\\WebRoot\\Img\\"
public static ImageIcon add(String ImageName){
ImageIcon icon = new ImageIcon(path+ImageName)
return icon
}
}
先定义一个方法,然后下面调用,注意把图片放在项目的WebRoot\\Img的目录下即可
final JLabel label = new JLabel()ImageIcon loginIcon=CreateIcon.add("backImg.jpg")
label.setIcon(loginIcon)
可以新建个面板,在面板里放入带图片的JLabel,填满面板即可。JPanel jp = new JPanel()//新建面板
jp.setLayout(new FlowLayout()) //设置面板布局
ImageIcon ii=new ImageIcon(getClass().getResource("/Picture/i.jpg"))
JLabel uppicture=new JLabel(ii)//往面板里加入JLabel
this.setVisible(true)
按钮只能是个矩形,按你是意思,应该是不显示按钮的边框,只显示图标是吧。你可以设置按钮背景为透明,设置边框为null
but.setBackground(new Color(255,255,255)) //but是按钮名称
but.setBorder(null)//but是按钮名称
我刚写的一个点击按钮交替变换图标的程序,代码如下:
import java.awt.Color
import java.awt.Container
import java.awt.Cursor
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.Icon
import javax.swing.ImageIcon
import javax.swing.JButton
import javax.swing.JFrame
//变换按钮图标
public class Button_Icon extends JFrame implements ActionListener{
private Container con
private JButton but
private Icon ic
public Button_Icon() {
this.setTitle("欢迎")
this.setBounds(200, 200, 200, 234)//标题栏高34
con=this.getContentPane()
con.setLayout(null)
Cursor cs=new Cursor(Cursor.HAND_CURSOR)
ic=new ImageIcon("j:\\Screenshot.png")
but=new JButton(ic)
but.setBounds(60, 70, 80, 60)
but.addActionListener(this)
but.setCursor(cs)
but.setBackground(new Color(255,255,255))
but.setBorder(null)
con.add(but)
this.setVisible(true)
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
public void actionPerformed(ActionEvent e) {
Icon ic2=but.getIcon()
if(ic2==null){but.setIcon(ic)}
else {but.setIcon(null)}
}
public static void main(String[] args) {
new Button_Icon()
}
}
你可以看下效果,看是不是你想要的。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)