怎么给JLabel加下划线

怎么给JLabel加下划线,第1张

下面的程序可以御侍御直接运行

package com

import javax.swing.*

public class Test extends JFrame {

public static void main(String args[]) {

new Test()

}

public Test(){

super("JLabel Test")

//JLabel 里面的 Text 支持简单的 HTML 语言

JLabel label = new JLabel("<HTML>镇岩<U>这 是 下 划 线<谈猜/U></HTML>")

this.getContentPane().add(label)

this.setSize(300,200)

this.setVisible(true)

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

}

}

package c

import java.awt.BorderLayout

public class a extends JFrame {

private JPanel contentPane

private boolean isOn=false//判断鼠标是否按过

private JButton button

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

a frame = new a()

frame.setVisible(true)

} catch (Exception e) {

e.printStackTrace()

}

}

})

}

/**

* Create the frame.

*/

public a() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

setBounds(100, 100, 450, 300)

contentPane = new JPanel()

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5))

setContentPane(contentPane)

contentPane.setLayout(null)

final JLabel label = new JLabel("New label")

label.setBounds(0, 0, 430, 257)

label.setLayout(null)

button = new JButton("New button")

button.setBounds(0, 0, 43, 25)

label.addMouseMotionListener(new MouseMotionAdapter() {

@Override

public void mouseMoved(MouseEvent arg0) {

if(isOn==true) {button.setLocation(arg0.getX(), arg0.getY())

label.updateUI()

repaint()

}

}

})

button.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent arg0) {

isOn=isOn==false?true:false

}

})

label.add(button)

contentPane.add(label)

}

}

这里只实现了一个按租裤钮,不过不管多少个其实都是一样的,lz可以照着样子自弊指简己添加,不过注意多一个按钮就要多一个逗誉isOn和相关的判断。

如果还不明白的话hi我

我说个思路吧。

在你的新JLabel类里面设一个标志:boolean bUnderLine=false

在paint()方法里判断 bUnderLine,如果true,则绘制下划线,否则不画。

给这个 JLable 组件戚源添加鼠标监听器,MouseListener中有一搜仔雹个方法 public void mouseEntered(MouseEvent e) ,在鼠世帆标进入组件上时会调用这个方法,所以在这个方法中可以设置 bUnderLine=true,绘制时就会绘制下划线 。

相应地,MouseListener中还有一个方法 public void mouseExited(MouseEvent e) ,在鼠标离开组件时调用,在此方法中设置 bUnderLine=false 。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11988484.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存