1

I got an assignment that i have to make a programm in Java that takes an Image.Creates 3 Buttons named(Align left,right and center).2 textfields Width and Height that i can input numbers there and a button resize.The 4 buttons(align left,right,center and resize) have to change the image place to left right or center and resize the image as the numbers were given respectively

enter image description here

I have written the code just for going left but i cant figure what to do...I also have no idea what to do on resizing...Can someone help me?

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);
    }
}

EDIT: I made a program that changes the Logo of the site with the help of trashgod Also i tried to change it a bit by changing the URL image loading with my image by doing imageLabel = new JLabel(new ImageIcon("PewPew.jpg")); and it works too.The Resize is gonna be done kinda the same way that its aligned left though i should "link" the text field numbers right?I need to also make a setPreferedSize and somehow get the width and height of textfields?

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);
               ;

            }
        });

    }
}

Edit 2: I made a programm that comes closer to what i need to do.I try to add the menu too like the original programm MenuBar menuBar = new JMenuBar();

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

and i get an error that does not recognize this.setJMenuBar.Also i tried many ways and i cant make the 3 buttons go north and the resize and textfields go south...What i am doing wrong?Code:

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);

            }
        });

    }
}
Barett
  • 5,826
  • 6
  • 51
  • 55
Amethyst0z
  • 33
  • 4
  • So you do not know how to align an image to the left/center/right of a `JPanel` ? And to ask that you dump a gigantic piece of code and basically ask us to do your assignment ? It that a correct summary of your question ? I suggest you try to write an [SSCCE](http://sscce.org) where you try to align something to the left and if you do not succeed you post that code and ask for assistance – Robin May 15 '12 at 16:11
  • Actually i tried to do that public void actionPerformed(ActionEvent a) { contentPane.add(pic1, BorderLayout.NORTH); } But it does not work and i do not know/can find another way to do this.Edited the code so you can see it better – Amethyst0z May 15 '12 at 16:15
  • It is an assignment. I am not simply going to give you code. You will need to study the different layout managers available in Swing. A good starting point is the [Visual guide to layout managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) – Robin May 15 '12 at 16:18
  • The fact is that i tried to do that...Actually i went to our java lab to ask for help they did not know what to do and i thought i could get some help...As you can see i edited the code and wrote a comment in where i actually try to move the image to the left.I try to compile but it does not recognize the image as an object i think?..I am asking some corection/tips...I do not want the fast or easy solution – Amethyst0z May 15 '12 at 16:20
  • I did some searching, as I knew someone has answered this in the wonderful sense, and here is the link to that wonderful answer, that can be applied to your scenario too, [how to add Image](http://stackoverflow.com/a/9760077/1057230) by @HovercraftFullOfEels (Every answer might add something to your knowledge there) – nIcE cOw May 15 '12 at 17:35

1 Answers1

2

Two approaches are common:

  • Given a suitable layout manager, use one of the constants JLabel.LEFT, JLabel.CENTER or JLabel.RIGHT in your call to setHorizontalAlignment(); follow this with validate() and repaint(), if required.

  • Override paintComponent() and use drawImage() to render the Image at the desired coordinates. Scaling is automatic. Left alignment is easy:

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

    Center, right and exception handling are left as an exercise.

Addendum: The sscce below illustrates the first approach for a single alignment; try adding the other two buttons using the existing button as a guide.

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);
            }
        });

    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I tried to do the 1st thing and the 2nd though i am not sure about it but the thing is in my ActionPerformed method it does not recognize the label at all..It says variable label1 can not be found.... – Amethyst0z May 16 '12 at 02:52
  • 1
    Please edit your question to include an [sscce](http://sscce.org/) that shows your current approach. [`FauxImage`](http://stackoverflow.com/a/8090328/230513) may be a convenient placeholder. – trashgod May 16 '12 at 03:32
  • Why should the TextField matter about moving my image?I try to do public void actionPerformed(ActionEvent a) { pic1/label1.drawImage(image, 120, 50, 300, 300, null); } Random numbers but it does not recognize my pic1/label1 so it can really move it and i dont know why – Amethyst0z May 16 '12 at 23:57
  • Just deleting comments is _not_ an [sscce](http://sscce.org/). I've added a complete example above named `AlignImage` with an exercise for you to complete. If you don't understand something, edit your question to show your working version of `AlignImage`. – trashgod May 17 '12 at 01:13
  • Excellent; to change the size, you're going to have to load the image separately and [scale](http://stackoverflow.com/q/6916693/230513) it. This should be a new question. When you post your sscce, don't forget to use an [image everyone can see](http://sstatic.net/stackoverflow/img/logo.png). – trashgod May 17 '12 at 17:39
  • thanks for the answer.Though i tried to get the values typed in textfield with '//widthx=Integer.parseInt(times.getText()); // heightx=Integer.parseInt(times2.getText()); ' and i get exception error...I have to add 2 action listeners for each textfield to get the values?I have added all the buttons before but i cant force the textfields and resize button to go down and the others up..What can i do? – Amethyst0z May 17 '12 at 19:30
  • Instead of adding more frames, try adding a new panel to the `controlPanel` with a different layout. – trashgod May 17 '12 at 20:52
  • It has to look like this http://i.stack.imgur.com/SoGaK.png..I dont see any extra panel so i guess i am not allowed to make a new one to add to the Control one..Isn't there another way to force the align buttons go up and the others to stay down? In the textfields can y send me any example on how i am gonna try to take the values from there through actionlistener?? so i can resize the image with the values entered in textfields?Thanks – Amethyst0z May 17 '12 at 21:18
  • Move the `controlPanel` to `NORTH` and add a new panel with your text fields to `SOUTH`. – trashgod May 17 '12 at 21:40
  • I have fixed all my problems and the program is now running correctly...Thanks for everything. – Amethyst0z May 18 '12 at 23:58