java – 如何根据组合框选择更改UI

前端之家收集整理的这篇文章主要介绍了java – 如何根据组合框选择更改UI前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在对话框中,如果选中某个组合,则需要显示一组控件,否则显示另一组控件.
即我需要2层,我需要在选中/取消选中组合时在它们之间切换.我怎样才能做到这一点?

谢谢

解决方法

CardLayout适用于此,如下所示.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/questions/6432170 */
public class CardPanel extends JPanel {

    private static final Random random = new Random();
    private static final JPanel cards = new JPanel(new CardLayout());
    private static final JComboBox combo = new JComboBox();
    private final String name;

    public CardPanel(String name) {
        this.name = name;
        this.setPreferredSize(new Dimension(320,240));
        this.setBackground(new Color(random.nextInt()));
        this.add(new JLabel(name));
    }

    @Override
    public String toString() {
        return name;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                create();
            }
        });
    }

    private static void create() {
        JFrame f = new JFrame();
        f.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        for (int i = 1; i < 9; i++) {
            CardPanel p = new CardPanel("Panel " + String.valueOf(i));
            combo.addItem(p);
            cards.add(p,p.toString());
        }
        JPanel control = new JPanel();
        combo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox jcb = (JComboBox) e.getSource();
                CardLayout cl = (CardLayout) cards.getLayout();
                cl.show(cards,jcb.getSelectedItem().toString());
            }
        });
        control.add(combo);
        f.add(cards,BorderLayout.CENTER);
        f.add(control,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

猜你在找的Java相关文章