我正在尝试使 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。除非你有充分的理由不使用它作为你的类(class)的基础,否则它在我看来仍然是解决你的问题的最佳解决方案。否则,您将需要一些代码,例如:
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,那么这也是不必要的。
代码的其他问题:
- 您的代码不符合 Java 命名约定,因此会让其他 Java 程序员感到困惑。
- 您正在使用空布局和
setBounds(...)
,这将导致创建一个难以增强和调试的严格 GUI。您应该避免使用这种类型的布局。
关于java - 使 JComponent 不透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26409885/