代码之家  ›  专栏  ›  技术社区  ›  AlexHomeBrew

如何将图像放在左上角的滚动窗格中

  •  0
  • AlexHomeBrew  · 技术社区  · 1 年前

    我在滚动窗格中显示图像,当窗格小于图像时效果很好。当窗格大于图像时,图像垂直居中,水平左对齐。我希望图像左上对齐,这样所有多余的空间都在右下对齐。

    enter image description here

    我尝试过使用insets、setAlignmentY()和JScrollPaneLayout中的方法,它们不会影响图像的显示位置。

    我找到的所有提示和文档都显示了如何在需要滚动条时处理窗格,而不是在不需要滚动条的时候。

    我怀疑这种行为是由使用JLabel来显示图像引起的,因为默认情况下,JLabel似乎在左侧对齐并垂直居中。但我的任何尝试都没有成功地将这一形象推向顶峰。

    以下是我用于创建上述图像的实际代码(从我的项目中大幅缩减,为了简洁起见,删除了注释)。它应该编译并运行良好。

    我在Windows 10机器上使用Intellij Idea社区版中的Java 15。

    public class ShowPattern extends JFrame
    {
        public static final int IMAGE_WIDTH = 340;
        public static final int IMAGE_HEIGHT = 272;
        protected BufferedImage fullSizeImage;
        private final JLabel imgLabel = new JLabel();
    
        public ShowPattern(int width, int height)
        {
            JPanel mainPanel = new JPanel(new BorderLayout());
            mainPanel.add(createImagePane(this.imgLabel), BorderLayout.CENTER);
            add(mainPanel);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            this.setPreferredSize(new Dimension(width + 35, height + 60));
            this.setLocation(25, 25);
            pack();
        }
        public final void showMapImage(BufferedImage img, File file)
        {
            setTitle("Pattern from file " + file.getName());
            fullSizeImage = img;
            ImageIcon imgIcon = new ImageIcon(img);
            imgLabel.setIcon(imgIcon);
        }
        private JScrollPane createImagePane(JLabel image)
        {
            JScrollPane scrollPane = new JScrollPane(image);
            image.setAlignmentY(Component.TOP_ALIGNMENT);  //DOESN'T AFFECT PLACEMENT
            scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            scrollPane.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
            return scrollPane;
        }
        public static void main( String[] args )
        {
            ShowPattern showPattern = new ShowPattern(IMAGE_WIDTH, IMAGE_HEIGHT);
            try
            {
                JFileChooser fileChooser = new JFileChooser();
                int status = fileChooser.showOpenDialog(null);
                fileChooser.setMultiSelectionEnabled(false);
                if (status == JFileChooser.APPROVE_OPTION)
                {
                    File file = fileChooser.getSelectedFile();
                    BufferedImage bimg;
                    try
                    {
                        bimg = ImageIO.read(file);
                        showPattern.showMapImage(bimg, file);
                        showPattern.setVisible(true);
                    }
                    catch (IOException ioe)
                    {
                        throw new RuntimeException(ioe);
                    }
                }
            }
            catch (Exception e)
            {
                System.out.println("Exception Loading Pattern " + e.getMessage());
            }
        }
    }
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   MadProgrammer    1 年前

    利用 JLabel#setHorizontalAlignment JLabel#setVerticalAlignment

    enter image description here

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.io.IOException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    
    public class Main {
        public static void main(String[] args) {
            new Main();
        }
    
        public Main() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        JFrame frame = new JFrame("Test");
                        frame.add(new TestPane());
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);
                    } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
    
        protected class TestPane extends JPanel {
    
            public TestPane() throws IOException {
                setLayout(new BorderLayout());
                JLabel label = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/resources/apple.png"))));
                label.setHorizontalAlignment(JLabel.LEADING);
                label.setVerticalAlignment(JLabel.TOP);
    
                add(new JScrollPane(label));
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
        }
    }