3
我不擅長這一點,我希望得到一些理解這個問題的人的更多幫助。JPanel的自定義繪畫
所以這裏是交易。在我的應用程序中有背景JPanel與圖像繪製在它上面。然後有一個小的JPanel,我正在試圖創建自定義繪畫。我想讓JPanel具有圓角和半透明背景,所以我修改了paintComponent方法來填充半透明的圓角矩形。但是當我像JComboBox那樣放置組件時,項目列表出現,並且我點擊其他地方關閉它JPanel以原始方式繪製它自己,使它半透明,但是用原始灰色背景顏色繪製小矩形。我發現它必須在其parrent或paintChildren上調用paintComponent,但我不知道如何組織這些方法或將它們放在哪裏。我也有問題,透明的顏色相互重疊。
下面是一個例子代碼:
public class RoundedPanel extends JPanel {
private final int radius;
public RoundedPanel(int cornerRadius) {
radius=cornerRadius;
}
public void paintComponent(Graphics g) {
Color bg = getBackground();
g.setColor(new Color(bg.getRed(),bg.getGreen(),bg.getBlue(),40));
g.fillRoundRect(0,0, getWidth()-1, getHeight()-1, radius, radius);
g.setColor(new Color(0,0,0,70));
g.drawRoundRect(0,0, getWidth()-1, getHeight()-1, radius, radius);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setLocation(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel();
JPanel wl = new JPanel();
JPanel el = new JPanel();
JPanel sl = new JPanel();
JPanel nl = new JPanel();
RoundedPanel rp = new RoundedPanel(50);
JComboBox combobox = new JComboBox();
frame.setContentPane(content);
content.setBackground(Color.red);
content.setLayout(new BorderLayout());
wl.add(new JButton("west"));
el.add(new JButton("east"));
sl.add(new JButton("south"));
nl.add(new JButton("north"));
content.add(wl,BorderLayout.WEST);
content.add(el,BorderLayout.EAST);
content.add(nl,BorderLayout.NORTH);
content.add(sl,BorderLayout.SOUTH);
content.add(rp,BorderLayout.CENTER);
rp.setBackground(Color.BLACK);
combobox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Třída 1.B", "Třída 1.C", "Třída 2.C" }));
rp.add(combobox);
frame.setVisible(true);
}
}
我希望有些會幫我:-)感謝
編輯:我發現的JComboBox(和它的彈出菜單)平如果彈出式菜單與包含JComboBox的JPanel外部重疊且具有自定義paintComponent方法,則會正確地執行此操作。
耶穌,我沒有嘗試這個,因爲我認爲RoundedPanel不會畫畫可言,我看不到它:-)非常感謝你,先生! – Martin 2010-09-17 13:34:36