【问题标题】:How to add an image at specific location in JFrame in Java using eclipse?如何使用 eclipse 在 Java 中的 JFrame 中的特定位置添加图像?
【发布时间】:2017-09-17 12:53:15
【问题描述】:

我使用 GUI 概念制作了一个学生信息页面。我想知道如何使用 JLabel 或任何其他方法在特定位置添加图像?我想要的是围绕整个 Jframe 的背景图像和在右上角的特定位置的另一个图像。我怎样才能做到这一点?

我还找到了使用 Jlabel 添加图像的代码,但它不适用于我的代码,因为我将布局设置为 null。 我找到的代码

    String path = "Image1.jpg";
    File file = new File(path);
    BufferedImage image = ImageIO.read(file);
    JLabel label = new JLabel(new ImageIcon(image));
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(label);
    f.pack();
    f.setLocation(200,200);
    f.setVisible(true);

下面是我的代码:

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JTextArea; 
import javax.swing.JTextField;

public class LoginPage 
{

JFrame jf;
JLabel gender,hobbies,name_label,rollno_label,marks_label,city_label,address_label;
JTextField name_field,rollno_field,marks_field;
JRadioButton male,female;
ButtonGroup bg;
JCheckBox photography,music,sketching,coding;
JComboBox city_combo;
JTextArea adress_textarea;
JButton save, exit;
JMenuBar mbar;
JMenu file,edit,help;
JMenuItem open,save_item,edit_item,close,cut,copy,paste,find,replace,help_content,about,updates;


    public LoginPage()  //constructor
    {

    jf = new JFrame("Student Information");
    name_label = new JLabel("Student's Name");
    name_field = new JTextField();
    rollno_label = new JLabel("Student's Roll Number");
    rollno_field = new JTextField();
    marks_label = new JLabel("Student's Total Marks Achieved");
    marks_field = new JTextField();
    gender = new JLabel("Gender");
    male = new JRadioButton("Male");
    female = new JRadioButton("Female");
    bg = new ButtonGroup();
    hobbies = new JLabel("Hobbies");
    photography = new JCheckBox("Photography");
    music = new JCheckBox("Music");
    coding = new JCheckBox("Coding");
    sketching = new JCheckBox("Sketching");
    city_label = new JLabel("City");
    city_combo = new JComboBox();
    address_label = new JLabel("Residential Address");
    adress_textarea = new JTextArea();
    save = new JButton("Save");
    exit = new JButton("Exit");
    mbar = new JMenuBar();
    file = new JMenu("File");
    edit = new JMenu("Edit");
    help = new JMenu("Help");
    open = new JMenuItem("open");
    save_item = new JMenuItem("Save");
    edit_item = new JMenuItem("Edit");
    close = new JMenuItem("Close");
    cut = new JMenuItem("Cut");
    copy = new JMenuItem("Copy");
    paste = new JMenuItem("Paste");
    find = new JMenuItem("Find");
    replace = new JMenuItem("Replace");
    about = new JMenuItem("About");
    updates = new JMenuItem("Check for Updates");
    help_content = new JMenuItem("Help Content");

    }

void Display() 
{
    jf.setSize(1000, 700);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setLayout(null);
    jf.getContentPane().setBackground( Color.LIGHT_GRAY );

    name_label.setBounds(50, 50, 150, 20);
    name_field.setBounds(300, 50, 200, 20);
    rollno_label.setBounds(50, 100, 150, 20);
    rollno_field.setBounds(300, 100, 200, 20);
    marks_label.setBounds(50, 150, 200, 20);
    marks_field.setBounds(300, 150, 200, 20);
    gender.setBounds(50, 200, 100, 20);
    male.setBounds(300, 200, 80, 20);
    female.setBounds(400, 200, 80, 20);
    hobbies.setBounds(50, 250, 80, 20);
    photography.setBounds(300, 250, 100, 20);
    music.setBounds(420, 250, 80, 20);
    sketching.setBounds(500, 250, 100, 20);
    coding.setBounds(600, 250, 80, 20);
    city_label.setBounds(50, 300, 100, 20);
    city_combo.setBounds(300, 300, 100, 20);
    address_label.setBounds(50, 350, 200, 20);
    adress_textarea.setBounds(300, 350, 300, 100);
    save.setBounds(300, 500, 100, 50);
    exit.setBounds(600, 500, 100, 50);

    bg.add(male);
    bg.add(female);

    city_combo.addItem("Select City");
    city_combo.addItem("Chandigarh");
    city_combo.addItem("Kurali");
    city_combo.addItem("Mohali");
    city_combo.addItem("Panchkula");

    file.add(open);
    file.add(save_item);
    file.add(edit_item);
    file.add(close);
    edit.add(cut);
    edit.add(copy);
    edit.add(paste);
    edit.add(find);
    edit.add(replace);
    help.add(about);
    help.add(help_content);
    help.add(updates);
    mbar.add(file);
    mbar.add(edit);
    mbar.add(help);

    jf.add(name_label);
    jf.add(name_field);
    jf.add(rollno_label);
    jf.add(rollno_field);
    jf.add(marks_label);
    jf.add(marks_field);
    jf.add(gender);
    jf.add(male);
    jf.add(female);
    jf.add(hobbies);
    jf.add(music);
    jf.add(photography);
    jf.add(sketching);
    jf.add(coding);
    jf.add(city_label);
    jf.add(city_combo);
    jf.add(address_label);
    jf.add(adress_textarea);
    jf.add(save);
    jf.add(exit);

    jf.setJMenuBar(mbar);

    jf.setVisible(true);


}

public static void main(String[] args) {
    new LoginPage().Display();
}

}

【问题讨论】:

    标签: java eclipse swing jlabel


    【解决方案1】:

    我想要的是围绕整个 Jframe 的背景图片

    建议:

    • 创建一个扩展JPanel的类,
    • 覆盖其paintComponent 方法
    • 一定要在你的覆盖中调用super的paintComponent方法
    • 在此方法中使用g.drawImage(...) 绘制背景图像
    • 要么将此 JPanel 设为 JFrame 的 contentPane,要么将其添加到 contentPane BorderLayout.CENTER,然后将您的 GUI 组件添加到此 JPanel
    • 确保某些组件不是透明的,例如,在您的 JRadioButtons 上调用 setOpaque(false),也许还有其他组件,以便显示背景图像。

    以及右上角的特定位置的另一张图片。我怎样才能做到这一点?

    • 使用上面相同的 JPanel,并使用 drawImage(...) 的重载绘制较小的图像,将图像精确地放置在您想要的位置

    注意事项:

    • 当我为 GUI 创建背景图像时,我更喜欢在 JPanel 而不是 JLabel 中进行绘制,因为 JLabel 没有开箱即用地充当 contentPane 或像样的容器。
    • 强烈建议您不要使用 null 布局和 setBounds,因为这会导致 gui 在一个平台上看起来不错,但在另一个平台上却没有,其中的 JLabel 的文本不完整可见,这很难升级和维护。学习和使用布局管理器。
    • 看起来您正在使用多个 JFrame。如果有,请阅读:The Use of Multiple JFrames: Good or Bad Practice?

    例如,下面是一种在 JPanel 中将图像显示为背景图像以及 GUI 右上部的较小图像的方法:

    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.URL;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class LoginPage3 extends JPanel {
        public static final String BG_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
                + "commons/e/e9/Maesil_%28prunus_mume%29_washed_and_stemmed.jpg";
        public static final String RU_IMG_PATH = "https://upload.wikimedia.org/wikipedia/"
                + "commons/thumb/5/5b/Escudo_de_San_Pedro_de_Atacama.svg/200px-Escudo_de_San_Pedro_de_Atacama.svg.png";
    
        private BufferedImage backgroundImg;
        private BufferedImage rightUpperImg;
    
        public LoginPage3(BufferedImage bgImg, BufferedImage ruImg) {
            this.backgroundImg = bgImg;
            this.rightUpperImg = ruImg;
        }
    
        @Override
        public Dimension getPreferredSize() {
            if (backgroundImg == null || isPreferredSizeSet()) {
                return super.getPreferredSize();
            } else {
                int w = backgroundImg.getWidth();
                int h = backgroundImg.getHeight();
                return new Dimension(w, h);
            }
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (backgroundImg != null) {
                g.drawImage(backgroundImg, 0, 0, this);
            }
            if (rightUpperImg != null) {
                int x = getWidth() - rightUpperImg.getWidth();
                g.drawImage(rightUpperImg, x, 0, this);
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    
        private static void createAndShowGui() {
            BufferedImage bg = null;
            BufferedImage ru = null;
            try {
                bg = ImageIO.read(new URL(BG_IMG_PATH));
                ru = ImageIO.read(new URL(RU_IMG_PATH));
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
    
            LoginPage3 mainPanel = new LoginPage3(bg, ru);
            JFrame frame = new JFrame("LoginPage3");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }
    

    【讨论】:

    • @UsagiMiyamoto:是的,正如我上面提到的(作为本网站的回答者,你也应该推荐),他应该使用@987654328 @布局。由于我们是 Swing 新手的领头羊,我们应该推荐最佳实践,而不是乱七八糟的东西。
    • 我同意在“正常情况下”不应该使用“空布局”,但我个人发现,当我必须以非常低的分辨率为 POS 终端创建 GUI 时,这是唯一的可能性。 . 所以我倾向于接受开发者有他/她的理由使用null 作为布局。
    • @UsagiMiyamoto:但你明白,在这种情况下的原因是开发人员是新手,不知道更好。
    【解决方案2】:

    对于背景图片:

    • 将其加载为icon,并使用它创建JLabel。 (查看您的第一个 sn-p)
    • JLabel 设置为JFrame 的内容窗格。

    您需要注意的是,Icon 不会拉伸,因此您必须拥有与您的JFrame 尺寸完全相同(或更大)的图像。

    对于给定位置的图像,JLabel 创建和Icon 加载过程是相同的,但是将其添加到JFrame 后,您必须设置位置和大小,就像其他组件一样, EG 致电setBounds()...

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多