如何将Combobox值设置为列表中的一个选项

时间:2015-06-18 18:58:47

标签: java swing

我需要更改当前JComboBox值的值。

我在Main.class使用的Settings gui类中得到了这个:

package com.tominocz.cookieclicker;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

@SuppressWarnings({ "serial", "rawtypes", "unchecked" })
public class Settings extends JFrame {

    private String[] choiceList = { "Default (Arial)", "Comic Sans MS" };

    public class ChoiceComboListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            JComboBox cb = (JComboBox) ev.getSource();
            String currentComboSelection = (String) cb.getSelectedItem();
            if (currentComboSelection.equals(choiceList[0])) {
                Main.SelectedFont = "Arial";
                Main.refreshGame();
                Main.opt.setSize(240, 105);
                Save.saveGame(Main.save);
            }
            if (currentComboSelection.equals(choiceList[1])) {
                Main.SelectedFont = "Comic Sans MS";
                Main.refreshGame();
                Main.opt.setSize(240, 107);
                Save.saveGame(Main.save);
            }
        }
    }

    public Settings() {
        super("Settings");
        setLayout(new FlowLayout());

        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) (((screen.getWidth()) - this.getWidth()) / 2 - 200);
        int y = (int) (((screen.getHeight()) - this.getHeight()) / 2 - 100);
        this.setLocation(x, y);
        this.setAlwaysOnTop(true);

        this.setIconImage(((ImageIcon) Main.SettingsIcon).getImage());

        JPanel northPanel = new JPanel();
        northPanel.setIgnoreRepaint(true);
        northPanel.setBorder(new LineBorder(Color.GRAY));
        this.getContentPane().add(northPanel, BorderLayout.NORTH);
        JComboBox choiceCombo = new JComboBox(choiceList);
        northPanel.add(Main.ChooseFont);
        northPanel.add(choiceCombo);
        choiceCombo.addActionListener(new ChoiceComboListener());

        // LOOK HEREEEEEEEEEEEEEEEEEEEEEEE
        if (Main.SelectedFont.equals("Comic Sans MS")) {
            [the current JComboBox value(may be the default one - choiceList[0])] = choiceList[1];
        }
        // LOOK HEREEEEEEEEEEEEEEEEEEEEEEE

        Main.OK.setBorder(null);
        Main.OK.setBorderPainted(false);
        Main.OK.setContentAreaFilled(false);
        add(Main.OK);
        Main.OK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Object source = e.getSource();
                if (source instanceof JButton) {
                    Main.opt.dispose();
                }
            }
        });
    }
}

现在,如果我无法在以下情况下使用它,如何更改currentComboSelection值:

公开设置(){

...

2 个答案:

答案 0 :(得分:4)

建议:

  • 您可以通过以下两种方式之一设置JComboBox所选项目:通过setSelectedIndex(int index)setSelectedItem(Object item)第一种方式,您可以选择所需选择的索引以及您选择的第二种方式JComboBox持有的对象(这里是字符串)应该被选中。

其他问题:

  • 您希望通过直接访问字段来获取Main类中的数据,可能是该字段的静态字段。不要这样做,因为它会使你的代码紧密耦合,设置难以发现的错误,并且难以增强或改变。改为使用严格控制的getter方法。即,给Main一个public Font getSelectedFont()方法,以便这个类可以以非静态的方式调用方法而不直接摆弄Main字段,而不会使Main字段静态不应该是静态的。
  • 您在此设置类中直接更改Main状态也是如此 - 由于上述相同原因,这不是如何安全地执行Java。好的OOP原则不会因为您正在创建事件驱动的GUI而被抛到窗外。
  • 看起来这应该是从主GUI窗口显示的辅助窗口。如果是这样,它应该显示为对话框,例如JDialog或JOptionPane而不是JFrame。这将阻止在OS工具栏上显示另一个图标,保证此窗口位于主窗口的顶部,并且如果需要,将允许以模态方式显示此窗口。
  • 您已将contentPane的布局设置为FlowLayout,但您尝试将JPanel添加到其BorderLayout.NORTH位置。这显然不会奏效。

例如,类似于您的简单代码,它使用JOptionPane作为辅助对话框窗口:

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class TestSettingsPanel {

   private static void createAndShowGui() {
      MainPanel mainPanel = new MainPanel();

      JFrame frame = new JFrame("Test Settings");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class MainPanel extends JPanel {
   private static final long serialVersionUID = 1L;
   public static final String[] CHOICE_LIST = { "Default (Arial)",
         "Comic Sans MS", "Courier", "Times New Roman" };
   private static final int PREF_W = 500;
   private static final int PREF_H = 400;
   private JTextField fontField = new JTextField(10);
   private SettingsPanel settingsPanel;

   public MainPanel() {
      fontField.setFocusable(false);
      fontField.setText(CHOICE_LIST[0]);

      add(new JLabel("Font: "));
      add(fontField);
      add(new JButton(new SettingsAction("Change Settings")));
   }

   @Override // let's make this bigger
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class SettingsAction extends AbstractAction {
      private static final long serialVersionUID = 1L;

      public SettingsAction(String name) {
         // give our button / Action some text
         super(name);
         int mnemonic = (int) name.charAt(0);
         putValue(MNEMONIC_KEY, mnemonic); // set alt-key combination short-cut
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // create our settingsPanel in a lazy fashion
         if (settingsPanel == null) {
            settingsPanel = new SettingsPanel();
         }

         // set the combo selection by calling the setSetting method:
         settingsPanel.setSetting(fontField.getText());

         // create a JOptionPane and dsiplay the settingsPanle inside of it
         Component parentComponent = MainPanel.this;
         String title = "Change Font Settings";
         int optionType = JOptionPane.OK_CANCEL_OPTION;
         int messageType = JOptionPane.PLAIN_MESSAGE;
         // display JOptionPane here
         int result = JOptionPane.showConfirmDialog(parentComponent,
               settingsPanel, title, optionType, messageType);
         // find out what button user pressed
         if (result == JOptionPane.OK_OPTION) {
            // if OK button pressed, extract information from settingsPanel
            String fontType = settingsPanel.getFontType();
            fontField.setText(fontType);
         }
      }
   }
}

// note that SettingsPanel is completely ignorant about the GUI that displays it. 
class SettingsPanel extends JPanel {
   private static final long serialVersionUID = 1L;
   private JComboBox<String> choiceListCombo = new JComboBox<>(MainPanel.CHOICE_LIST);

   public SettingsPanel() {
      add(new JLabel("Select Font:"));
      add(choiceListCombo);
   }

   // to allow outside classes to set the combo's selected item 
   public void setSetting(String text) {
      if (text != null && !text.trim().isEmpty()) {
         choiceListCombo.setSelectedItem(text);
      }
   }

   // allow outside classes to extract the selected item from combo
   public String getFontType() {
      return (String) choiceListCombo.getSelectedItem();
   }

}

答案 1 :(得分:0)

您可以使用以下方法获取和设置Combobox的选定项目(对象):

choiceCombo.getSelectedItem();

choiceCombo.setSelectedItem(anObject);