2014-10-16 72 views
0

我試圖在右邊框中使JComponent不透明。使JComponent不透明

我希望做一個對象與我的具體特點,所以我正在使用JComponent,可以是不透明的

這是因爲我會讓一個圖書館,我不希望使用JPanelJLabel

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); 
    } 

} 

noo

我不知道爲什麼它不顯示不透明的,如果我用一個JLabel的作品,所以我錯過了什麼?

感謝您的建議和答案

+0

'「,這不是一個好主意使用大量的進口,所以我不想使用JPanel或JLabel」' - 嗯?請解釋一下,因爲它確實沒有意義?另外,你的組件如何行爲不端。你如何證明它不是不透明的? – 2014-10-16 16:58:12

+0

mmm我不想使用JPanel或JLabel,因爲他們有不需要的方法 – WearFox 2014-10-16 17:00:50

+0

這並不能說明你不想使用JPanel的動機,而JPanel本質上是不透明的。另外,請在我上面的評論中提及我的其他問題。你怎麼知道你的JComponent其實不是不透明的?你在它的'paintComponent(...)'方法中填充圖像還是背景顏色? – 2014-10-16 17:02:08

回答

2

我一般輕鬆解決你的問題的建議:使用一個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,那麼再次沒有必要。

的其他問題與您的代碼:

  • 您的代碼不符合Java的命名約定等會混淆其他Java程序員。
  • 您正在使用空佈局和setBounds(...),這將導致創建硬性增強和調試GUI。你應該避免使用這種類型的佈局。
+0

是它的作品現在..但我認爲我的reazon是好的「我想讓自己的JComponet我不想使用像JPanel或JLabel這樣的其他人,這些擴展了JComponent」 – WearFox 2014-10-16 17:24:37