是否可以使JButton透明(包括边框)但不透明文本?我扩展了swing的JButton并覆盖了它:
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0));
super.paint(g2);
g2.dispose();
}但它使一切都变得透明,包括文本。谢谢。
发布于 2011-01-04 00:01:56
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);发布于 2011-01-04 00:03:48
下面的代码应该可以解决这个问题。
public class PlainJButton extends JButton {
public PlainJButton (String text){
super(text);
setBorder(null);
setBorderPainted(false);
setContentAreaFilled(false);
setOpaque(false);
}
// sample test method
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel pane = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.add(new PlainJButton("HI!!!!"));
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
}发布于 2021-02-11 00:35:33
你的程序的用户不能将你的按钮定义为按钮。使用时可以认为它是一个标签。所以我的解决方案是半透明的,有显示和消失的边界。
这个代码是改进的,改进的代码,更好,更好的性能,更美观,更适合。
import java.awt.Color;
import static java.awt.Color.blue;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class Test extends JFrame {
Test() {
setLayout(null);
JButton testButton = new JButton("Test_Button");
testButton.setBounds(200, 200, 200, 20);
testButton.setOpaque(false); // Must add
testButton.setContentAreaFilled(false); // No fill
testButton.setFocusable(false); // I'd like to set focusable false to the button.
testButton.setBorderPainted(true); // I'd like to enable it.
testButton.setBorder(null); // Border (No border for now)
add(testButton);
testButton.addMouseListener(new MouseAdapter(){
@Override
public void mouseEntered(MouseEvent e){
testButton.setBorder(BorderFactory.createLineBorder(blue, 2,true));
//When enter we can not know our mouse successfully entered to the button. So I'd like to add Border
}
@Override
public void mouseExited(MouseEvent e){
testButton.setBorder(null);
//When mouse exits no border.
}
});
// For a half of transparent I'd like a add JPanel behind JButton
JPanel backPanel = new JPanel();
backPanel.setBounds(testButton.getBounds()); // Same to buttons bounds.
backPanel.setBackground(new Color(0, 0, 0, 50)); // Background with transeparent
add(backPanel);
JLabel icon = new JLabel();
icon.setBounds(0, 0, 3840, 2160);
icon.setIcon(new ImageIcon(getClass().getResource("wallpaper_16105238065ffea49e5ec9d2.04136813.jpeg")));
add(icon);
//Background image for test up it.
testButton.addActionListener((ActionEvent e) -> {
testButton.setBorder(null); // When mouse clicked border will dissaprear.
System.out.println("Button clicked!");
//For check the button works correctly.
});
setSize(800, 500);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}https://stackoverflow.com/questions/4585867
复制相似问题