JSpinner文字颜色

时间:2012-11-10 18:43:06

标签: java swing netbeans colors jspinner

我目前正在NetBeans中创建一个GUI,我有一个包含颜色列表的JSpinner,但我不知道如何使文本成为每个颜色的相应颜色。

即。 - 红色(应该是红色等)

以下是JSpinner的代码:

Color_Selector_Spinner = new javax.swing.JSpinner(); Color_Selector_Spinner.setModel(new javax.swing.SpinnerListModel(new String[] { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"}));

2 个答案:

答案 0 :(得分:4)

您需要以下内容来制作颜色编码JSpinner

  1. ChangeListener JSpinner,以便在组件值更改时更新颜色

  2. String值转换为颜色。

  3. 在微调器中只使用了一个JTextField,因此必须在每次更改事件时使用当前颜色进行更新。

    spinner.addChangeListener(new ChangeListener() {
    
       @Override
       public void stateChanged(ChangeEvent e) {
    
        try {
           String colorString = (String)spinner.getValue();
    
           Field field = Class.forName("java.awt.Color").getField(colorString.toLowerCase()); // toLowerCase because the color fields are RED or red, not Red
           Color color = (Color)field.get(null);
    
           JTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
           tf.setForeground(color);
    
           } catch (Exception ex) { // handle ex }
       }
    });
    

答案 1 :(得分:2)

我个人更喜欢设置自己的编辑器,而不是转换现有的编辑器,并希望将来不会破坏它。所以Reimeus代码的略微修改版本

import javax.swing.*;
import java.awt.Color;
import java.lang.reflect.Field;

public class ColorSpinnerDemo {

  public static void main( String[] args ) {
    JFrame testFrame = new JFrame( "TestFrame" );

    JSpinner spinner = new JSpinner( new SpinnerListModel( new String[]{"Red", "Orange", "Yellow", "Green"} ) );
    spinner.setEditor( new SpinnerEditor( spinner ).getComponent() );

    testFrame.add( spinner );

    testFrame.pack();
    testFrame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
    testFrame.setVisible( true );
  }

  private static class SpinnerEditor{
    private JLabel label = new JLabel(  );

    public SpinnerEditor( JSpinner spinner ){
      spinner.addChangeListener( new ChangeListener() {
        @Override
        public void stateChanged( ChangeEvent e ) {
          String currentValue = ( String ) ( ( JSpinner ) e.getSource() ).getValue();
          label.setText( currentValue );

          try {
            Field field = Class.forName("java.awt.Color").getField(currentValue.toLowerCase()); // toLowerCase because the color fields are RED or red, not Red
            Color color = (Color)field.get(null);

            label.setForeground( color );
          } catch ( NoSuchFieldException e1 ) {           
          } catch ( ClassNotFoundException e1 ) {
          } catch ( IllegalAccessException e1 ) {
          }
        }
      } );
    }

    public JComponent getComponent(){
      return label;
    }
  }
}