2

我有一个具有空布局的 JPanel,我正在尝试添加一个 JSlider:

        slider = new JSlider();


        slider.setSize(300,30);
        slider.setPreferredSize(new Dimension(300,30));
        int x = (Constants.getScreenWidth()/2)-(slider.getWidth()/2);
        int y = (Constants.getScreenHeight()/2)-(slider.getHeight()/2);
        y = y - 100;
        slider.setLocation(x,y);
        slider.setBounds(x-(slider.getWidth()/2),y-(slider.getHeight()/2),300,30);


        add(slider);

但是滑块没有显示出来。我已经打印了滑块,它是:

javax.swing.JSlider[,420,320,300x30,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=288,maximumSize=,minimumSize=,preferredSize=java.awt.Dimension[width=300,height=30],isInverted=false,majorTickSpacing=0,minorTickSpacing=0,orientation=HORIZONTAL,paintLabels=false,paintTicks=false,paintTrack=true,snapToTicks=false,snapToValue=true]

为什么我看不到滑块?

4

1 回答 1

4
  • 在这种情况下删除slider.setLayout(null);您为setLayout(null);其父级设置的JPanel.setLayout(null);

  • 免责声明永远不会AbsoluteLayout用于放置JComponentContainer

我能够在没有代码行的情况下显示 JSlider

int x = (Constants.getScreenWidth()/2)-(slider.getWidth()/2);
int y = (Constants.getScreenHeight()/2)-(slider.getHeight()/2);
y = y - 100;
slider.setLocation(x,y);
slider.setBounds(x-(slider.getWidth()/2),y-(slider.getHeight()/2),300,30);
  • JComponent通过Container使用_Insets

这段代码在屏幕上显示了 JSlider

import javax.swing.*;
import java.awt.*;

public class NullLayoutManagerWithJSlider extends JFrame {

    private JFrame frame = new JFrame();
    private static final long serialVersionUID = 1L;

    public NullLayoutManagerWithJSlider() {
        JSlider slider = new JSlider();
        slider.setPreferredSize(new Dimension(300, 30));        
        frame.setLayout(null);
        frame.add(slider);

        Insets mmInsets = frame.getInsets();
        Dimension sizeMmInn = null;
        slider.setPreferredSize(new Dimension(300, 30));
        sizeMmInn = slider.getPreferredSize();
        slider.setBounds(20 + mmInsets.left, 16 + mmInsets.top, sizeMmInn.width, sizeMmInn.height);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100, 100);
        frame.setSize(new Dimension(600, 400));
        frame.setVisible(true);
    }

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

            @Override
            public void run() {
                NullLayoutManagerWithJSlider cf = new NullLayoutManagerWithJSlider();
            }
        });
    }
}
于 2012-03-15T19:36:28.427 回答