java - 关于ActionListener.image编辑的问题

标签 java swing imageicon

我接到一个作业,要求我用 Java 编写一个程序,该程序采用一个图像。创建 3 个名为(左对齐、右对齐和居中对齐)的按钮。2 个文本字段宽度和高度,我可以在其中输入数字并调整按钮大小。 4个按钮(左对齐、右对齐、居中和调整大小)必须将图像位置更改为左、右或居中,并根据分别给定的数字调整图像大小

enter image description here

我编写的代码只是为了向左走,但我不知道该怎么做...我也不知道在调整大小时该怎么做...有人可以帮助我吗?

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class Destructor extends JFrame implements ActionListener {

    private JButton red, blue, white, resize;

    public Destructor(String title) {
        super(title);
        Container contentPane = this.getContentPane();
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        red = new JButton("Align Left");
        //red.addActionListener(this);
        blue = new JButton("Align Center");
        blue.addActionListener(this);
        white = new JButton("Align Right");
        white.addActionListener(this);
        //read the Image
        // try {                
        // BufferedImage pic1 = ImageIO.read(new File("PewPew.jpg"));
        //JLabel picLabel = new JLabel(new ImageIcon( pic1 ));
        //add( picLabel );
        ImageIcon pic1 = new ImageIcon("PewPew.jpg");
        add(new JLabel(pic1));
        // } catch (IOException ex) {
        // handle exception...
        // }

        //Action LIsteners
        //add the buttons to the frame
        JPanel north = new JPanel();
        north.add(red);
        north.add(blue);
        north.add(white);
        contentPane.add(north, BorderLayout.NORTH);
        //THe Under Panel
        JPanel south = new JPanel();
        south.setLocation(250, 30);
        resize = new JButton("Resize");
        JLabel Width = new JLabel("Width :");
        JLabel Height = new JLabel("Height :");
        //The text field
        JTextField times = new JTextField();
        JTextField times2 = new JTextField();
        Width.setLabelFor(times);
        Height.setLabelFor(times2);
        Width.setLocation(120, 0);

        south.add(Width);
        south.add(times, BorderLayout.NORTH);
        south.add(Height);
        south.add(times2, BorderLayout.SOUTH);
        south.add(resize);
        contentPane.add(south, BorderLayout.SOUTH);
        GridLayout lay2 = new GridLayout(3, 2);
        south.setLayout(lay2);

        //create a menu bar and attach it to this JFrame
        JMenuBar menuBar = new JMenuBar();
        this.setJMenuBar(menuBar);

        JMenu fileMenu = new JMenu("Options");

        menuBar.add(fileMenu);

        JMenuItem redMenuItem = new JMenuItem("Reset");

        fileMenu.add(redMenuItem);



    }
//Trying to move the picture to the left
    public void actionPerformed(ActionEvent a) {
        contentPane.add(pic1, BorderLayout.NORTH);
    }

    public static void main(String[] args) {
        Destructor f = new Destructor("Image App");
        f.setSize(600, 600);
        f.setVisible(true);
    }
}

编辑:我制作了一个程序,在trashgod的帮助下更改网站的 Logo 我还尝试通过更改使用我的图像加载的 URL 图像来更改它 imageLabel = new JLabel(new ImageIcon("PewPew.jpg")); 它也可以工作。调整大小的完成方式与左对齐的方式有点相同,尽管我应该“链接”文本字段编号对吗?我还需要设置一个 setPreferedSize 并以某种方式获取文本字段的宽度和高度?

import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;

/** @see http://stackoverflow.com/a/10610126/230513 */
public class AlignImage extends JPanel {

    private JPanel controlPanel = new JPanel();
    private JLabel imageLabel;

    public AlignImage() {
        super(new GridLayout());
        try {
            imageLabel = new JLabel(new ImageIcon(new URL(
                "http://sstatic.net/stackoverflow/img/logo.png")));
        } catch (MalformedURLException ex) {
            ex.printStackTrace(System.err);
        }
        this.add(imageLabel);
        controlPanel.add(new JButton(new AbstractAction("Align Left") {

            @Override
            public void actionPerformed(ActionEvent e) {
                align(JLabel.LEFT);
            }
        }));
          controlPanel.add(new JButton(new AbstractAction("Align Center") {

            @Override
            public void actionPerformed(ActionEvent e) {
                align(JLabel.CENTER);
            }
        }));
        controlPanel.add(new JButton(new AbstractAction("Align Right") {

            @Override
            public void actionPerformed(ActionEvent e) {
                align(JLabel.RIGHT);
            }
        }));


    }

    @Override
    public Dimension getPreferredSize() {
        int w = 3 * imageLabel.getIcon().getIconWidth() / 2;
        int h = 3 * imageLabel.getIcon().getIconHeight() / 2;
        System.out.println(w + " " + h);
        return new Dimension(w, h);
    }

    private void align(int alignment) {
        imageLabel.setHorizontalAlignment(alignment);
    }

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

            @Override
            public void run() {
                JFrame f = new JFrame("Align Left");
                f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                AlignImage ai = new AlignImage();
                f.add(ai, BorderLayout.CENTER);
                f.add(ai.controlPanel, BorderLayout.NORTH);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
                JFrame f1 = new JFrame("Align Center");
                f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                 JFrame f2 = new JFrame("Align Right");
                f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

                f2.add(ai, BorderLayout.CENTER);
                f2.add(ai.controlPanel, BorderLayout.NORTH);
                f2.pack();
                f2.setLocationRelativeTo(null);
                f2.setVisible(true);
                f1.add(ai, BorderLayout.CENTER);
                f1.add(ai.controlPanel, BorderLayout.NORTH);
                f1.pack();
                f1.setLocationRelativeTo(null);
                f1.setVisible(true);
               ;

            }
        });

    }
}

编辑2:我制作了一个更接近我需要做的程序。我尝试像原始程序一样添加菜单 MenuBar menuBar = new JMenuBar();

this.setJMenuBar(menuBar);
   JMenu fileMenu = new JMenu("Options");
      menuBar.add(fileMenu);
     JMenuItem redMenuItem = new JMenuItem("Reset");
    fileMenu.add(redMenuItem);

并且我收到一个无法识别 this.setJMenuBar 的错误。而且我尝试了很多方法,但我无法使 3 个按钮向北移动,而调整大小和文本字段向南移动...我做错了什么?代码:

import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;

/** @see http://stackoverflow.com/a/10610126/230513 */
public class AlignImage extends JPanel {

    private JPanel controlPanel = new JPanel();
    private JLabel imageLabel;

    public AlignImage() {
        super(new GridLayout());

            imageLabel = new JLabel(new ImageIcon("PewPew.jpg"));

        this.add(imageLabel);
        controlPanel.add(new JButton(new AbstractAction("Align Left") {

            @Override
            public void actionPerformed(ActionEvent e) {
                align(JLabel.LEFT);
            }
        }));
          controlPanel.add(new JButton(new AbstractAction("Align Center") {

            @Override
            public void actionPerformed(ActionEvent e) {
                align(JLabel.CENTER);
            }
        }));
        controlPanel.add(new JButton(new AbstractAction("Align Right") {

            @Override
            public void actionPerformed(ActionEvent e) {
                align(JLabel.RIGHT);
            }
        }));

        JPanel south= new JPanel();

    JButton resize=new JButton("Resize");
   JLabel Width = new JLabel("Width :");
   JLabel Height = new JLabel("Height :");
   //The text field
   JTextField times= new JTextField();
   JTextField times2= new JTextField();
   Width.setLabelFor(times);
   Height.setLabelFor(times2);


  south.add(Width);
  south.add(times, BorderLayout.NORTH);
  south.add(Height);
  south.add(times2, BorderLayout.SOUTH);
  south.add(resize);
   controlPanel.add(south, BorderLayout.SOUTH);
    GridLayout lay2 = new GridLayout(3,2); south.setLayout(lay2);
        JMenuBar menuBar = new JMenuBar();

    }

    @Override
    public Dimension getPreferredSize() {
        int w = 3 * imageLabel.getIcon().getIconWidth() / 2;
        int h = 3 * imageLabel.getIcon().getIconHeight() / 2;
        System.out.println(w + " " + h);
        return new Dimension(w, h);
    }

    private void align(int alignment) {
        imageLabel.setHorizontalAlignment(alignment);
    }

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

            @Override
            public void run() {
                JFrame f = new JFrame("Align Left");
                f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                AlignImage ai = new AlignImage();
                f.add(ai, BorderLayout.CENTER);
                f.add(ai.controlPanel, BorderLayout.NORTH);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
                JFrame f1 = new JFrame("Align Center");
                f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                 JFrame f2 = new JFrame("Align Right");
                f2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

                f2.add(ai, BorderLayout.CENTER);
                f2.add(ai.controlPanel, BorderLayout.NORTH);
                f2.pack();
                f2.setLocationRelativeTo(null);
                f2.setVisible(true);
                f1.add(ai, BorderLayout.CENTER);
                f1.add(ai.controlPanel, BorderLayout.NORTH);
                f1.pack();
                f1.setLocationRelativeTo(null);
                f1.setVisible(true);
               JFrame f3 = new JFrame("Res");
                f3.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

                f3.add(ai, BorderLayout.CENTER);
                f3.add(ai.controlPanel, BorderLayout.SOUTH);
                f3.pack();
                f3.setLocationRelativeTo(null);
                f3.setVisible(true);

            }
        });

    }
}

最佳答案

有两种常见方法:

  • 给定一个合适的layout manager ,使用常量 JLabel.LEFT 之一, JLabel.CENTERJLabel.RIGHT在您调用setHorizontalAlignment()时;遵循 validate()repaint() ,如果需要的话。

  • 覆盖paintComponent()并使用drawImage()渲染 Image在所需的坐标处。缩放是自动的。左对齐很容易:

    int w = Integer.valueOf(width.getText()); // formerly times
    int h = Integer.valueOf(height.getText()); // formerly times2
    g.drawImage(image, 0, 0, w, h, null);
    

    中心、右侧和异常处理留作练习。

附录:sscce下面说明了单一比对的第一种方法;尝试使用现有按钮作为指导添加其他两个按钮。

import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;

/** @see http://stackoverflow.com/a/10610126/230513 */
public class AlignImage extends JPanel {

    private JPanel controlPanel = new JPanel();
    private JLabel imageLabel;

    public AlignImage() {
        super(new GridLayout());
        try {
            imageLabel = new JLabel(new ImageIcon(new URL(
                "http://sstatic.net/stackoverflow/img/logo.png")));
        } catch (MalformedURLException ex) {
            ex.printStackTrace(System.err);
        }
        this.add(imageLabel);
        controlPanel.add(new JButton(new AbstractAction("Align Left") {

            @Override
            public void actionPerformed(ActionEvent e) {
                align(JLabel.LEFT);
            }
        }));
    }

    @Override
    public Dimension getPreferredSize() {
        int w = 3 * imageLabel.getIcon().getIconWidth() / 2;
        int h = 3 * imageLabel.getIcon().getIconHeight() / 2;
        System.out.println(w + " " + h);
        return new Dimension(w, h);
    }

    private void align(int alignment) {
        imageLabel.setHorizontalAlignment(alignment);
    }

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

            @Override
            public void run() {
                JFrame f = new JFrame("Align Left");
                f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                AlignImage ai = new AlignImage();
                f.add(ai, BorderLayout.CENTER);
                f.add(ai.controlPanel, BorderLayout.SOUTH);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });

    }
}

关于java - 关于ActionListener.image编辑的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10604638/

相关文章:

java - 如何知道JToolbar的状态?

java - JTabbedPane 中的图标未显示

java - 如何在没有 JButton 的情况下使 ImageIcon(或任何类型的图像)可见?

Java:充满接口(interface)元素的数据结构 - 如何强制实现接口(interface)的类实现compareTo()?

java - 关键监听器java - 数量限制

java - 如何解决 Swing JPanel 中显示倒数计时器(JLabel)的延迟问题

java - 为 JFrame 制作自定义图标

java - 为 MySQL 或 Java 编写脚本

java - Service层异常处理

java - 在gradle中运行任务后如何运行集成任务?