我试图在JSlider下绘制宽度相等的彩色矩形,以使刻度线分开颜色。我真的很亲密,但是不能做到完美。我已经打印了很多值,但我的问题是滑块的宽度不是滑块的实际长度。滑块的x位置也不是条的起点。这是我的代码,根据滑块位置设置“彩色矩形”边界。

for(int i = 0; i < Global.emSpectrum.length; i++)  //emSpectrum.length is the number of colored rectangles
{
    emSpectrum.get(i).setColorRect(Global.emSpectrum[i], 13 + i * (int)((this.slider.getWidth())/Global.emSpectrum.length),     //13 lines up the first color under the bar
    this.slider.getY() + this.slider.getHeight()/2, (int)((this.slider.getWidth())/Global.emSpectrum.length),
    (int)(Global.rectHeight * getHeight()));
}


有没有更好的方法来解决这个问题?

谢谢!

最佳答案

是的,一个不错的解决方案是使用字典,例如HashTable<Integer, JLabel>,并使用与JSlider上适当位置相对应的Integer来填充包含颜色矩形的ImageIcons的JLabel。例如,我的SSCCE:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Dictionary;
import java.util.Hashtable;

import javax.swing.*;

public class SliderEg extends JPanel {
   public static final Color[] COLORS = { Color.red, Color.orange,
         Color.yellow, Color.green, Color.blue, Color.cyan};
   private static final int BI_W = 30;
   private static final int BI_H = 10;
   private JSlider slider = new JSlider(0, 100, 0);

   public SliderEg() {
      int majorSpacing = slider.getMaximum() / (COLORS.length - 1);
      Dictionary<Integer, JLabel> dictionary = new Hashtable<Integer, JLabel>();
      slider.setMajorTickSpacing(majorSpacing);
      slider.setPaintLabels(true);
      slider.setPaintTicks(true);
      slider.setSnapToTicks(true);
      for (int i = 0; i < COLORS.length; i++) {
         ImageIcon icon = createColorIcon(COLORS[i]);
         JLabel label = new JLabel(icon);
         int key = i * majorSpacing;
         dictionary.put(key, label);
      }
      slider.setLabelTable(dictionary);

      setLayout(new BorderLayout());
      add(slider, BorderLayout.CENTER);
   }

   private ImageIcon createColorIcon(Color color) {
      BufferedImage img = new BufferedImage(BI_W, BI_H,
            BufferedImage.TYPE_INT_RGB);
      Graphics g = img.getGraphics();
      g.setColor(color);
      g.fillRect(0, 0, BI_W, BI_H);
      g.dispose();

      return new ImageIcon(img);
   }

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

      JFrame frame = new JFrame("SliderEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_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();
         }
      });
   }
}

10-08 15:19