这是一个神秘的问题。我有JSlider
,JLabel
和JTextField
。我希望他们都是相邻的。我的问题是JTextField
的(valueField)向上移动了。当我打印出组件之间的y坐标值时,它们都是相同的。以下是JLabel
和JTextField
:
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
会向上移动。请给我一些建议,我的想法已经不多了。谢谢你的帮助!
答案 0 :(得分:1)
你能给我一些建议吗?
避免使用absolute positioning。
从sscce开始并修改它以显示您遇到的任何问题。
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();
}
});
}
}