0

我正在尝试在 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()));
}

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

谢谢!

4

1 回答 1

4

是的,一个不错的解决方案是使用一个字典,例如 aHashTable<Integer, JLabel>并用 JLabels 填充它,这些 JLabels 包含您的颜色矩形的 ImageIcons,使用与 JSlider 上的适当位置相对应的整数。例如,我的 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();
         }
      });
   }
}
于 2012-06-03T01:34:32.557 回答