gpt4 book ai didi

java - 面板 setBackground 弄乱了 JLabels 的颜色

转载 作者:太空宇宙 更新时间:2023-11-04 12:25:42 25 4
gpt4 key购买 nike

这是我的有问题的代码。问题是,如果我使用“白色”设置面板背景,“pic”JLabel 中图标的颜色会变得非常浅。如果我使用“黑色”,则 pic JLabel 的颜色是可见的。我在图片 JLabel 中使用什么颜色并不重要。一旦面板设置为白色,它们都会变亮。

是否有其他方法可以设置面板的背景颜色而不影响其中 JLabel 的颜色?

Color black = new Color( 20, 20, 20, 255 );
Color white = new Color( 255, 255, 255, 255 );

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize( 1200, 500 );
frame.setVisible(true);
frame.getRootPane().setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
frame.setLocationRelativeTo( null );
frame.setResizable( false );

JPanel panel= new JPanel();
frame.getContentPane().add( panel );
panel.setLayout( null );
panel.getAccessibleContext().setAccessibleName("panel");
panel.getAccessibleContext().setAccessibleDescription(" ");

// this is the line that causes problem
panel.setBackground( black );


JLabel pic = new JLabel( new ImageIcon( showBaseImage() ) );
panel.add( pic );
pic.setSize( 1200, 500 );
pic.setLocation( 1, 1);
pic.setBackground( black );


public BufferedImage showBaseImage(){
BufferedImage c = new BufferedImage( 1200, 500, BufferedImage.TYPE_INT_ARGB );
Graphics2D gg= c.createGraphics();
gg.setPaint( new Color( 125, 0, 125, 255 ));
gg.fillRect( 0,0, c.getWidth(), c.getHeight() );

gg.setPaint( new Color( 255, 255, 225, 255 ));
imgFont = new Font( "Arial", Font.BOLD, 45 );
gg.setFont( imgFont );

gg.drawString( "Write something", 20, 20 );
gg.dispose();
return c;
}

最佳答案

您可以使用 label.setOpaque(true) 来允许您的标签不透明。它的实现来自 JComponent,默认情况下为 false。

Note that labels are not opaque by default. If you need to paint the label's background, it is recommended that you turn its opacity property to "true". The following code snippet shows how to do this.

label.setOpaque(true);

https://docs.oracle.com/javase/tutorial/uiswing/components/label.html

关于java - 面板 setBackground 弄乱了 JLabels 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38419425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com