我正在尝试JComponent
在右侧边框中设置不透明的颜色。
我想制作一个具有我特定特征的对象,所以我使用的JComponent
可能是不透明的
这是因为我将创建一个库,并且我不想使用JPanel
或JLabel
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class ProbadorCodigos {
JFrame Frame=new JFrame();
JComponent BORDEDE=new JComponent() {private static final long serialVersionUID = 2222L;};
public ProbadorCodigos() {
Frame.setSize(500, 500);
Frame.setResizable(false);
Frame.setUndecorated(false);
Frame.setLayout(null);
Frame.setLocationRelativeTo(null);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.getContentPane().setBackground(Color.darkGray);
Format();
Action();
}
private void Format() {
BORDEDE.setBounds(Frame.getWidth()-100, 0, 100, Frame.getHeight());
BORDEDE.setOpaque(true);
BORDEDE.setVisible(true);
BORDEDE.setEnabled(true);
BORDEDE.setFocusable(true);
BORDEDE.setBackground(Color.red);
System.out.println(BORDEDE);
}
private void Action() {
Frame.add(BORDEDE);
}
public static void main(String[] args) {
ProbadorCodigos Ventana=new ProbadorCodigos();
Ventana.Frame.setVisible(true);
}
}
我不知道为什么它不显示不透明,如果我使用JLabel
作品,那么我会丢失什么呢?
感谢您的建议和答案
我的一般解决问题的建议是:使用JPanel。除非您有充分的理由不将其用作课堂上的基础,否则我仍然认为这是解决问题的最佳方法。否则,您将需要以下代码:
JComponent bordede = new JComponent() {
private static final long serialVersionUID = 2222L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
g.setColor(getBackground());
g.fillRect(0, 0, width, height);
}
};
如果您只是使用JPanel,那么这又是不必要的。
您的代码的其他问题:
setBounds(...)
这将导致创建难以增强和调试GUI的刚性布局。您应该避免使用这种类型的布局。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句