如何使用JavaSwing显示用户在JFrame上选择的图像

如何使用JavaSwing显示用户在JFrame上选择的图像,java,image,swing,upload,javax.imageio,Java,Image,Swing,Upload,Javax.imageio,我正在尝试向用户的个人资料页面添加“个人资料图片”。基本上,我有它的地方,他们可以选择一个文件从他们的计算机和上传到应用程序,它将显示他们的个人资料图片。但是它不工作,我认为它目前无法显示它,但生成的结果不正确 这是我的密码 import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.ObjectInp

我正在尝试向用户的个人资料页面添加“个人资料图片”。基本上,我有它的地方,他们可以选择一个文件从他们的计算机和上传到应用程序,它将显示他们的个人资料图片。但是它不工作,我认为它目前无法显示它,但生成的结果不正确

这是我的密码

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFileChooser;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

class createProfilePage extends JFrame implements ActionListener {
    Container container = getContentPane();

    JLabel name = new JLabel("Name: ");
    JTextField nameField = new JTextField();

    JLabel age = new JLabel("Age: ");
    JTextField ageField = new JTextField();

    JLabel interest = new JLabel("Interests: ");
    JTextField interestField = new JTextField();

    JLabel aboutMe = new JLabel("About me: ");
    JTextField aboutMeField = new JTextField();

    JLabel phoneNum = new JLabel("Phone Number: ");
    JTextField phoneNumberField = new JTextField();

    JButton submit = new JButton("Save Profile");
    JButton deleteProfile = new JButton("Delete Profile");

    JButton uploadPic = new JButton("Upload Profile Picture");

    createProfilePage()
    {
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        //setting container
        setLayoutManager();
        setLocationAndSize();
        addComponents();
        addActionEvent();

        setTitle("Welcome");
        setSize(600, 500);
    }
    public void setLayoutManager() {
        container.setLayout(null);
    }
    public void setLocationAndSize()
    {
        //Setting location and Size of each components using setBounds() method.
        name.setBounds(50,100,100,30);
        age.setBounds(50,170,100,30);
        phoneNum.setBounds(50,240,100,30);
        interest.setBounds(50,310,100,30);
        aboutMe.setBounds(50,380,100,30);

        submit.setBounds(350, 240, 150, 30);
        deleteProfile.setBounds(350,310,150,30);
        uploadPic.setBounds(350,380,150,30);

        nameField.setBounds(150,100,150,30);
        ageField.setBounds(150,170,150,30);
        phoneNumberField.setBounds(150,240,150,30);
        interestField.setBounds(150,310,150,30);
        aboutMeField.setBounds(150,380,150,30);
    }
    public void addComponents() {
        container.add(name);
        container.add(age);
        container.add(phoneNum);
        container.add(interest);
        container.add(aboutMe);
        container.add(nameField);
        container.add(ageField);
        container.add(phoneNumberField);
        container.add(interestField);
        container.add(aboutMeField);
        container.add(submit);
        container.add(deleteProfile);
        container.add(uploadPic);
    }
    public void addActionEvent() {
        submit.addActionListener(this);
        deleteProfile.addActionListener(this);
        uploadPic.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == submit) {
            String name = nameField.getText();
            String age = ageField.getText();
            String phoneNum = phoneNumberField.getText();
            String interest = interestField.getText();
            String aboutMe = aboutMeField.getText();
            try {
                Socket socket = new Socket("localhost", 4242);
                ObjectInputStream reader = new ObjectInputStream(socket.getInputStream());
                //creating user object to send to the server
                User user = new User();
            } catch (IOException b) {
                b.printStackTrace();
            }



            JOptionPane.showMessageDialog(this, "Profile Creation Successful");
        } else if (e.getSource() == deleteProfile) {
            String name = null;
            String age = null;
            String phoneNum = null;
            String interest = null;
            String aboutMe = null;

            JOptionPane.showMessageDialog(this, "Profile Deletion Successful");
        } else if (e.getSource() == uploadPic) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
            int result = fileChooser.showOpenDialog(getParent());
            if (result == JFileChooser.APPROVE_OPTION) {
                try {
                    File file = fileChooser.getSelectedFile();
                    //ImageDrawer drawer = new ImageDrawer();
                    Toolkit toolkit = Toolkit.getDefaultToolkit();
                    String stringFile = file.toString();
                    Image image = toolkit.getImage(stringFile);
                    Path path = Paths.get(stringFile);
                    Path imagePath = path.toAbsolutePath();
                    String newStr = imagePath.toString();
                    BufferedImage picture = ImageIO.read(new File(newStr));

                    JLabel picLabel = new JLabel(new ImageIcon(picture));
                    picLabel.setBounds(350, 170, 150, 30);
                    add(picLabel);
                } catch (IOException g) {
                    JOptionPane.showMessageDialog(null,"ERROR");
                }
            }
        }
    }
}

好吧,现在它“起作用了”。此代码可以打开并显示用户选择的图像。布局仍处于中断状态(1),如
上传配置文件Pict…
所示。这台计算机上的猜测宽度和截断文本是使用布局管理器、填充和边框在GUI中定位元素的众多原因之一

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

final class createProfilePage extends JFrame implements ActionListener {

    Container container = getContentPane();

    JLabel name = new JLabel("Name: ");
    JTextField nameField = new JTextField();
    JLabel age = new JLabel("Age: ");
    JTextField ageField = new JTextField();
    JLabel interest = new JLabel("Interests: ");
    JTextField interestField = new JTextField();
    JLabel aboutMe = new JLabel("About me: ");
    JTextField aboutMeField = new JTextField();
    JLabel phoneNum = new JLabel("Phone Number: ");
    JTextField phoneNumberField = new JTextField();
    JLabel picLabel = new JLabel();

    JButton submit = new JButton("Save Profile");
    JButton deleteProfile = new JButton("Delete Profile");
    JButton uploadPic = new JButton("Upload Profile Picture");

    createProfilePage() {
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        //setting container
        setLayoutManager();
        setLocationAndSize();
        addComponents();
        addActionEvent();

        setTitle("Welcome");
        setSize(600, 500);
    }

    public void setLayoutManager() {
        container.setLayout(null);
    }

    public void setLocationAndSize() {
        //Setting location and Size of each components using setBounds() method.
        name.setBounds(50, 100, 100, 30);
        age.setBounds(50, 170, 100, 30);
        phoneNum.setBounds(50, 240, 100, 30);
        interest.setBounds(50, 310, 100, 30);
        aboutMe.setBounds(50, 380, 100, 30);

        submit.setBounds(350, 240, 150, 30);
        deleteProfile.setBounds(350, 310, 150, 30);
        uploadPic.setBounds(350, 380, 150, 30);

        nameField.setBounds(150, 100, 150, 30);
        ageField.setBounds(150, 170, 150, 30);
        phoneNumberField.setBounds(150, 240, 150, 30);
        interestField.setBounds(150, 310, 150, 30);
        aboutMeField.setBounds(150, 380, 150, 30);
        picLabel.setBounds(350, 50, 150, 150);
    }

    public void addComponents() {
        container.add(name);
        container.add(age);
        container.add(phoneNum);
        container.add(interest);
        container.add(aboutMe);
        container.add(nameField);
        container.add(ageField);
        container.add(phoneNumberField);
        container.add(interestField);
        container.add(aboutMeField);
        container.add(picLabel);
        container.add(submit);
        container.add(deleteProfile);
        container.add(uploadPic);
    }

    public void addActionEvent() {
        submit.addActionListener(this);
        deleteProfile.addActionListener(this);
        uploadPic.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == uploadPic) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
            int result = fileChooser.showOpenDialog(getParent());
            if (result == JFileChooser.APPROVE_OPTION) {
                try {
                    File file = fileChooser.getSelectedFile();
                    BufferedImage picture = ImageIO.read(file);

                    picLabel.setIcon(new ImageIcon(picture));
                    add(picLabel);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    JOptionPane.showMessageDialog(null, "ERROR");
                }
            }
        }
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            new createProfilePage().setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}
  • 就我个人而言,我会采取不同的方式来看待这个问题。顶部有一个工具栏,用于显示所有按钮。左边的两列标签和字段如图所示,但标签文本向右对齐,字段大小根据需要而不同。甚至可以把“关于我:”变成一个文本区域,而不是一个字段。然后,在标签/字段组合的右侧,显示宽度的其余部分 和用于图片标签的高度。它将以一种新的形式展示 滚动窗格(除非图片大小相同)
  • 好吧,现在它“起作用了”。此代码可以打开并显示用户选择的图像。布局仍处于中断状态(1),如
    上传配置文件Pict…
    所示。这台计算机上的猜测宽度和截断文本是使用布局管理器、填充和边框在GUI中定位元素的众多原因之一

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    final class createProfilePage extends JFrame implements ActionListener {
    
        Container container = getContentPane();
    
        JLabel name = new JLabel("Name: ");
        JTextField nameField = new JTextField();
        JLabel age = new JLabel("Age: ");
        JTextField ageField = new JTextField();
        JLabel interest = new JLabel("Interests: ");
        JTextField interestField = new JTextField();
        JLabel aboutMe = new JLabel("About me: ");
        JTextField aboutMeField = new JTextField();
        JLabel phoneNum = new JLabel("Phone Number: ");
        JTextField phoneNumberField = new JTextField();
        JLabel picLabel = new JLabel();
    
        JButton submit = new JButton("Save Profile");
        JButton deleteProfile = new JButton("Delete Profile");
        JButton uploadPic = new JButton("Upload Profile Picture");
    
        createProfilePage() {
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            //setting container
            setLayoutManager();
            setLocationAndSize();
            addComponents();
            addActionEvent();
    
            setTitle("Welcome");
            setSize(600, 500);
        }
    
        public void setLayoutManager() {
            container.setLayout(null);
        }
    
        public void setLocationAndSize() {
            //Setting location and Size of each components using setBounds() method.
            name.setBounds(50, 100, 100, 30);
            age.setBounds(50, 170, 100, 30);
            phoneNum.setBounds(50, 240, 100, 30);
            interest.setBounds(50, 310, 100, 30);
            aboutMe.setBounds(50, 380, 100, 30);
    
            submit.setBounds(350, 240, 150, 30);
            deleteProfile.setBounds(350, 310, 150, 30);
            uploadPic.setBounds(350, 380, 150, 30);
    
            nameField.setBounds(150, 100, 150, 30);
            ageField.setBounds(150, 170, 150, 30);
            phoneNumberField.setBounds(150, 240, 150, 30);
            interestField.setBounds(150, 310, 150, 30);
            aboutMeField.setBounds(150, 380, 150, 30);
            picLabel.setBounds(350, 50, 150, 150);
        }
    
        public void addComponents() {
            container.add(name);
            container.add(age);
            container.add(phoneNum);
            container.add(interest);
            container.add(aboutMe);
            container.add(nameField);
            container.add(ageField);
            container.add(phoneNumberField);
            container.add(interestField);
            container.add(aboutMeField);
            container.add(picLabel);
            container.add(submit);
            container.add(deleteProfile);
            container.add(uploadPic);
        }
    
        public void addActionEvent() {
            submit.addActionListener(this);
            deleteProfile.addActionListener(this);
            uploadPic.addActionListener(this);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == uploadPic) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
                int result = fileChooser.showOpenDialog(getParent());
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        File file = fileChooser.getSelectedFile();
                        BufferedImage picture = ImageIO.read(file);
    
                        picLabel.setIcon(new ImageIcon(picture));
                        add(picLabel);
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                        JOptionPane.showMessageDialog(null, "ERROR");
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            Runnable r = () -> {
                new createProfilePage().setVisible(true);
            };
            SwingUtilities.invokeLater(r);
        }
    }
    
  • 就我个人而言,我会采取不同的方式来看待这个问题。顶部有一个工具栏,用于显示所有按钮。左边的两列标签和字段如图所示,但标签文本向右对齐,字段大小根据需要而不同。甚至可以把“关于我:”变成一个文本区域,而不是一个字段。然后,在标签/字段组合的右侧,显示宽度的其余部分 和用于图片标签的高度。它将以一种新的形式展示 滚动窗格(除非图片大小相同)

  • container.setLayout(空)Java GUI必须在不同的操作系统、屏幕大小、屏幕分辨率等上工作,在不同的地区使用不同的PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或与布局填充和边框一起使用。如果这一问题得到解决,问题很可能会消失。如果没有,人们可能会更仔细地查看code.BTW:
    File File=fileChooser.getSelectedFile()//ImageDrawer drawer=新的ImageDrawer();Toolkit=Toolkit.getDefaultToolkit();String stringFile=file.toString();Image=toolkit.getImage(stringFile);Path Path=Path.get(stringFile);Path imagePath=Path.toabsolutionPath();字符串newStr=imagePath.toString();buffereImage picture=ImageIO.read(新文件(newStr))
    可以是
    File File=fileChooser.getSelectedFile();buffereImage picture=ImageIO.read(文件)。在构建类时,添加
    picLabel
    并将其与其他组件一起放置(使用布局和边框)。将其作为类属性保留引用。“使用”加载图像时,将图像设置为标签的图像图标,它将出现。@AndrewThompson谢谢您,这是我第一次使用Swing,我接受了您的建议。我遵循了一个指南,其中说要执行container.setLayout(null),但现在您已经提出了它。在macOS上,它看起来确实是一团糟,但我不认为这是因为布局。谢谢
    container.setLayout(null)Java GUI必须在不同的操作系统、屏幕大小、屏幕分辨率等上工作,在不同的地区使用不同的PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或与布局填充和边框一起使用。如果这一问题得到解决,问题很可能会消失。如果没有,人们可能会更仔细地查看code.BTW:
    File File=fileChooser.getSelectedFile()//ImageDrawer drawer=新的ImageDrawer();Toolkit=Toolkit.getDefaultToolkit();String stringFile=file.toString();Image=toolkit.getImage(stringFile);Path Path=Path.get(stringFile);Path imagePath=Path.toabsolutionPath();字符串newStr=imagePath.toString();buffereImage picture=ImageIO.read(新文件(newStr))
    可以是
    File File=fileChooser.getSelectedFile();buffereImage picture=ImageIO.read(文件)。在构建类时,添加
    picLabel
    并将其与其他组件一起放置(使用布局和边框)。将其作为类属性保留引用。“使用”加载图像时,将图像设置为标签的图像图标,它将出现。@AndrewThompson谢谢您,这是我第一次使用Swing,我接受了您的建议。我遵循了一个指南,其中说要执行container.setLayout(null),但现在您已经提出了它。在macOS上,它看起来确实是一团糟,但我不认为这是因为布局。谢谢谢谢你,我已经实施了它,它正在发挥作用。很appreciated@HovercraftFullOfEels我之所以没有对他的答案投赞成票,是因为我直到现在还没有足够的声誉。你问另一个问题是对的,我已经删除了那条评论。谢谢谢谢你,我已经实施了它,它正在发挥作用。很appreciated@HovercraftFullOfEels我之所以没有对他的答案投赞成票,是因为我直到现在还没有足够的声誉。你问另一个问题是对的,我已经删除了那条评论。非常感谢。