我会忘记透明度的想法。只需将选项作为列表放在卡片面板的左侧(或右侧,或上方/下方)。我绝对不会将控件面板放在 CardPanel 本身上。应该在外面。
选择列表可以是单选按钮、按钮,或者在本例中,可以增长而不会弄乱布局的项目的 JList。例如:
/*
* CardLayoutDemo.java
*/
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
@SuppressWarnings("unchecked")
public class CardLayoutDemo implements Runnable
{
final static String CARD1 = "Gray Panel";
final static String CARD2 = "Blue Panel";
final static String CARD3 = "Green Panel";
JPanel cards;
CardLayout cl;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new CardLayoutDemo());
}
public void run()
{
final JList jList = new JList(new String[]{CARD1, CARD2, CARD3});
jList.setPrototypeCellValue("XXXXXXXXXXXX");
jList.setVisibleRowCount(5);
jList.setSelectedIndex(0);
jList.addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
String name = jList.getSelectedValue().toString();
cl.show(cards, name);
}
});
JScrollPane scroll = new JScrollPane(jList);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Dimension dim = new Dimension(300, 300);
JPanel card1 = new JPanel();
card1.setBackground(Color.GRAY);
card1.setPreferredSize(dim);
JPanel card2 = new JPanel();
card2.setBackground(Color.BLUE);
card2.setPreferredSize(dim);
JPanel card3 = new JPanel();
card3.setBackground(Color.GREEN);
card3.setPreferredSize(dim);
cl = new CardLayout();
cards = new JPanel(cl);
cards.add(card1, CARD1);
cards.add(card2, CARD2);
cards.add(card3, CARD3);
JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(scroll, BorderLayout.WEST);
f.add(cards, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
如果您想要选择的标签,只需制作一个包含 JLabel 和 JScrollPane 的“选择面板”(或使用您的按钮面板网格),并将其放入 Borderlayout.WEST(而不是直接添加 JScrollPane)。
另外,请考虑JTabbedPane
作为替代方案。