0
如何從組合框中選定的卡上獲取字符串並在fractalChooser
combobox
上使用getSelectedItem
方法並將結果轉換爲字符串?目前它只顯示一個對象。如何顯示所有Cardlayouts
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FractalDriver
{
private static final int WIDTH = 350;
private static final int HEIGHT = 300;
private static final String CANTOR = "Cantor";
private static final String CIRCLE = "Circle";
private static final String MANDELBROT = "Mandelbrot";
private static final String SIERPINSKI = "Sierpinski";
private static final String[] allFractals = {CANTOR, CIRCLE, MANDELBROT, SIERPINSKI};
private JFrame frame;
private CardLayout cardLayout;
private JPanel fractalCards;
private JComboBox<String> fractalChooser;
public FractalDriver()
{
makeFrame();
}
private void makeFrame()
{
frame = new JFrame("Fractals!");
frame.setSize(WIDTH, HEIGHT);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createContents();
frame.setVisible(true);
}
private void createContents()
{
JScrollPane cantorPane = new JScrollPane(new CantorPanel(6));
JScrollPane circlePane = new JScrollPane(new CirclesPanel(6));
JScrollPane mandelbrotPane = new JScrollPane(new MandelbrotPanel(6));
JScrollPane sierpinskiPane = new JScrollPane(new SierpinskiPanel(6));
cardLayout = new CardLayout();
fractalCards = new JPanel();
fractalCards.setLayout(cardLayout);
fractalCards.add(cantorPane, CANTOR);
fractalCards.add(circlePane, CIRCLE);
fractalCards.add(mandelbrotPane, MANDELBROT);
fractalCards.add(sierpinskiPane, SIERPINSKI);
fractalChooser = new JComboBox<String> (allFractals);
fractalChooser.addActionListener(new ComboListener());
frame.add(fractalChooser, BorderLayout.NORTH);
frame.add(fractalCards, BorderLayout.CENTER);
}
private class ComboListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
fractalChooser.getSelectedItem();
cardLayout.show(fractalCards, SIERPINSKI);
}
}
public static void main(String[] args)
{
new FractalDriver();
}
}
可能有另一種方式來實現的操作方法?我從來沒有想過要使用和「如果」的說法。 – Anthropy
那麼,getSelectedItem可以返回null,所以你總是檢查它:) – MadProgrammer