-2

这是一个神秘的问题。我有一个JSlider,JLabelJTextField. 我希望它们都相邻对齐。我的问题是JTextField's (valueField) 上移了。当我打印出组件之间的 y 坐标值时,它们都是相同的。这是我的代码JLabelJTextField

public SliderLabelPanel(String labelStr, String unitLabelStr)
//PRE:  labelStr is initialized  
//POST: a default SliderLabelPanel is created
{
    //this.setLayout(new FlowLayout());
    slider = new JSlider();
    slider.setMajorTickSpacing(10);
    slider.setMaximum(100);
    slider.setMinimum(0);
    slider.setPaintTicks(true);

    label = new JLabel(labelStr);
    valueField = new JTextField();
    unitLabel = new JLabel(unitLabelStr);

    this.add(slider);
    this.add(label);
    this.add(valueField);
    this.add(unitLabel);
    //printFields();
}

public void update()
//POST: this SliderLabelPanel is updated (size of the components)
{
    this.slider.setBounds(0, slider.getY(), (int)(Global.sliderWidth * getWidth()), (int)(Global.labelHeight * getHeight()));
    this.label.setBounds(slider.getX() + slider.getWidth(), slider.getY(), 
                        Global.LABEL_WIDTH, (int)(Global.labelHeight * getHeight()));

    this.valueField.setBounds(label.getX() + label.getWidth(), slider.getY(),
                             (int)(Global.fieldWidth * getWidth()), Global.FIELD_HEIGHT);

    //valueField.getx

    this.unitLabel.setBounds(valueField.getX() + valueField.getWidth(), slider.getY(),
                             Global.LABEL_WIDTH, (int)(Global.labelHeight * getHeight()));
    printFields();
}

public void paintComponent(Graphics g)
//PRE:  g is initialized
//POST: the components of this SliderLabelPanel are painted to g
{
    super.paintComponent(g);
}

JSlider与 对齐JLabel,但是JTextField将向上移动。也请给我建议,我的想法不多了。感谢所有的帮助!

4

1 回答 1

1

你能给我一些建议吗?

布局测试

import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;

/** @see http://stackoverflow.com/q/10867400/230513 */
public class LayoutTest extends JPanel {

    public LayoutTest() {
        super(new GridLayout(1, 0));
        JSlider slider = new JSlider();
        this.add(slider);
        JLabel label = new JLabel("Label", JLabel.CENTER);
        this.add(label);
        JTextField jtf = new JTextField("Text");
        this.add(jtf);
    }

    private void display() {
        JFrame f = new JFrame("LayoutTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

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

            @Override
            public void run() {
                new LayoutTest().display();
            }
        });
    }
}
于 2012-06-03T20:59:08.940 回答