Java – how to change UI based on combo box selection
•
Java
In the dialog box, if a combination is selected, one group of controls needs to be displayed, otherwise another group of controls will be displayed
thank you
Solution
CardLayout applies to this, as shown below
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.JCombo@R_482_2419@; 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 JCombo@R_482_2419@ combo = new JCombo@R_482_2419@(); 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) { JCombo@R_482_2419@ jcb = (JCombo@R_482_2419@) 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); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码