如何使用左右箭头的Java Spinner?

时间:2015-03-06 16:42:07

标签: java spinner

我在Java Swing中使用过Java Spinner,但它有向上和向下箭头,有没有办法设置它的方向以便箭头左右?

感谢Jean-FrançoisSavard的回答,我离我更近了一步,但仍然不太正确,我有以下几点:

  public void installUI(JComponent c)
  {
    super.installUI(c);
    c.removeAll();
    FlowLayout FL=new FlowLayout();
    FL.setHgap(0);
    c.setLayout(FL);
    JComponent editor=createEditor();
    editor.setPreferredSize(new Dimension(30,16));
    c.add(editor);
    c.add(createPreviousButton());
    c.add(createNextButton());
  }

间距不正确,如何解决?我在上面的行中硬编码,如何自动为文本提供适当的空间?

1 个答案:

答案 0 :(得分:3)

在谷歌上进行的简短搜索引导我进行JSpinner的自定义实施。

public class LeftRightSpinnerDemo {

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

      @Override
      public void run() {
        new LeftRightSpinnerDemo().makeUI();
      }
    });
  }

  public void makeUI() {
    JSpinner spinner = new JSpinner();
    spinner.setUI(new LeftRightSpinnerUI());

    JFrame frame = new JFrame();
    frame.add(spinner);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

class LeftRightSpinnerUI extends BasicSpinnerUI {

  public static ComponentUI createUI(JComponent c) {
    return new LeftRightSpinnerUI();
  }

  @Override
  protected Component createNextButton() {
    Component c = createArrowButton(SwingConstants.EAST);
    c.setName("Spinner.nextButton");
    installNextButtonListeners(c);
    return c;
  }

  @Override
  protected Component createPreviousButton() {
    Component c = createArrowButton(SwingConstants.WEST);
    c.setName("Spinner.previousButton");
    installPreviousButtonListeners(c);
    return c;
  }

  // copied from BasicSpinnerUI
  private Component createArrowButton(int direction) {
    JButton b = new BasicArrowButton(direction);
    Border buttonBorder = UIManager.getBorder("Spinner.arrowButtonBorder");
    if (buttonBorder instanceof UIResource) {
      b.setBorder(new CompoundBorder(buttonBorder, null));
    } else {
      b.setBorder(buttonBorder);
    }
    b.setInheritsPopupMenu(true);
    return b;
  }

  @Override
  public void installUI(JComponent c) {
    super.installUI(c);
    c.removeAll();
    c.setLayout(new BorderLayout());
    c.add(createNextButton(), BorderLayout.EAST);
    c.add(createPreviousButton(), BorderLayout.WEST);
    c.add(createEditor(), BorderLayout.CENTER);
  }
}

确保在我删除它们时添加正确的import以减轻代码。

有关原始帖子,请参阅this