我在漸變 JPanel 之上有一個透明的 JList 和 JScrollPanel,其中每個的代碼如下所示:
JPanel midPanel = new JPanel() {
protected void paintComponent(Graphics g) {
Paint p = new GradientPaint(0.0f, 0.0f, new Color(233, 220, 0, 0),
getWidth(), getHeight(), new Color(239, 129, 91, 255), true);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
};
列出代碼
ArrayList<String> songs = new ArrayList<>(Arrays.asList(new String[] {elements...}));
DefaultListModel<String> model = new DefaultListModel<>();
model.addAll(songs);
JList<String> songList = new JList<String>(model);
songList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
songList.setLayoutOrientation(JList.VERTICAL);
songList.setVisibleRowCount(-1);
songList.setOpaque(false);
songList.setCellRenderer(new TransparentListCellRenderer());
JScrollPane scroller = new JScrollPane(songList);
scroller.setPreferredSize(new Dimension(400, 250));
scroller.setOpaque(false);
scroller.getViewport().setOpaque(false);
scroller.setBorder(BorderFactory.createEmptyBorder());
midPanel.add(scroller);
在觸摸任何東西之前,它看起來像這樣:

在選擇了東西或滾動串列的元素后,所有的元素都被涂抹并造成了這種混亂:
有誰知道如何解決這一問題?如果我不得不猜測出了什么問題,那將是漸變的問題,因為 paintComponet() 方法已被覆寫,因此無法正確重繪,但如果是這種情況,我不知道如何修復它。任何幫助深表感謝。
uj5u.com熱心網友回復:
答案是將面板包裹在一個透明的容器中。
public class AlphaContainer extends JComponent {
private JComponent component;
public AlphaContainer(JComponent component) {
this.component = component;
setLayout( new BorderLayout() );
setOpaque( false );
component.setOpaque( false );
add( component );
}
/**
* Paint the background using the background Color of the
* contained component
*/
@Override
public void paintComponent(Graphics g) {
g.setColor( component.getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/469512.html
上一篇:JavaSwing鍵盤格式不正確
