Java Applet JSlider宽度

时间:2012-06-03 01:09:49

标签: java applet slider jslider

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

还有更好的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

是的,一个不错的解决方案是使用诸如HashTable<Integer, JLabel>之类的词典,并使用与JSlider上的适当位置对应的整数填充JLabel,其中包含颜色矩形的ImageIcons。例如,我的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();
         }
      });
   }
}