【问题标题】:How to display all Cardlayouts如何显示所有卡片布局
【发布时间】:2015-05-29 05:49:15
【问题描述】:

如何从组合框上的选定卡片中获取字符串,并使用fractalChooser combobox 上的getSelectedItem 方法并将结果转换为字符串?目前它只显示一个对象。

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();
 }
}

【问题讨论】:

    标签: java swing layout-manager jcombobox cardlayout


    【解决方案1】:

    getSelectedItemString 的结果的简单案例...

    private class ComboListener implements ActionListener {
    
        public void actionPerformed(ActionEvent e) {
    
            String name = (String)fractalChooser.getSelectedItem();
    
            if (name != null) {
                cardLayout.show(fractalCards, name);
            }
    
        }
    }
    

    【讨论】:

    • 能不能有另一种方式来实现action方法?我从没想过要使用 and "if" 语句。
    • 好吧,getSelectedItem 可以返回 null,所以你总是检查它:)
    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2016-07-16
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多