Graysull
Graysull

Reputation: 109

JLabel - Cutting Off The Top of Image

in my new Java project I have a JFrame in which there is a JLabel set to North with BorderLayout, and below it is an image. The image fits fine on the JFrame, but the JLabel cuts off the top of it. How can I resize this JLabel? I tried setPreferredSize and that didn't work. Help would be appreciated.

Code:

    package counter.main;

    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.net.URL;

    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;

    public class FoodCounter {

    public static JLabel greet4 = new JLabel("",SwingConstants.CENTER);
    public static JLabel message4 = new JLabel();
    public static JLabel lclicks4  = new JLabel();
    public static JButton buttonClick4 = new JButton("+ Food");
    public static int clicks4 = 0;
    public static URL food =           Main.class.getResource("/counter/main/FoodEating.wav");
    public static JButton back = new JButton("Back");
    public static JLabel bread;

    static JFrame frame = new JFrame("Food Counter"); {
        createView();

        frame.setSize(500, 100);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.revalidate();
        frame.repaint();
    }

    private void createView() {
        final JPanel panelc = new JPanel();
        frame.getContentPane().add(panelc);

        panelc.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 11));

        greet4.setFont(new Font( "Dialog", Font.PLAIN, 18));
        greet4.setPreferredSize(new Dimension(40, 20));

        panelc.add(message4);

        frame.add(back, BorderLayout.WEST);
        frame.add(greet4, BorderLayout.NORTH);
        back.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
                SelectionFrame.frame1.setVisible(true);
            }

        });

        panelc.add(buttonClick4);
        panelc.add(lclicks4);
        updateCounter();

        bread = new JLabel("");
        bread.setPreferredSize(new Dimension(64, 64));
        Image img = new ImageIcon(this.getClass().getResource("/counter/main/SlicedBread64.png")).getImage();
        bread.setIcon(new ImageIcon(img));
        frame.getContentPane().add(bread, BorderLayout.EAST);

        buttonClick4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clicks4++;
                updateCounter();
                try {
                AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(food);
                Clip clip = AudioSystem.getClip();
                clip.open(audioInputStream);
                clip.start();
                } catch (IOException | UnsupportedAudioFileException |  LineUnavailableException x) {
                    x.printStackTrace();
                }
                }
            });

        };

    private void updateCounter() {
        lclicks4.setText(clicks4 + "/100 Food  ");

        if (clicks4 < 1) {
            message4.setText("Click to Begin! -->");
        }

        if (clicks4 >= 1 && clicks4 < 10) {
            message4.setText("Keep Going!");
        }

        if (clicks4 >= 10 && clicks4 < 50) {
            message4.setText("Keep 'em Comin'!");
        }

        if (clicks4 >= 50 && clicks4 < 70) {
            message4.setText("Don't Stop!");
        }

        if (clicks4 >= 70 && clicks4 < 80) {
            message4.setText("Almost!");
        }


        if (clicks4 >= 90 && clicks4 < 100) {
            message4.setText("Finish Strong!");
        }

        if (clicks4 >= 100) {
            try {
                Thread.sleep(3000);                 
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            System.exit(0);
        }
    }       
}

Upvotes: 0

Views: 1828

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

  • Don't set sizes, preferred sizes or similar issues on components and top-level windows if it can be avoided.
  • Instead let the GUI size itself by using layout managers smartly and by calling pack() on the top-level window after adding all components and before calling setVisible(true).
  • Consider putting dummy text into your greet4 JLabel, so that it takes up space when the GUI is packed. Some spaces, " " will likely suffice.

Unrelated recommendations:

  • Most of your variables should be instance variables, not static variables. Java is structured along object-oriented programming principles for many reasons, but a chief one is to reduce connections and its associated complexity. By using static variables and methods, you remove this benefit and risk creating programs with a high degree of cyclomatic complexity, making debugging difficult.
  • Likewise for variables declared as public. Prefer to use private fields to help reduce coupling and increase cohesion.
  • Run long-running code, such as the code that plays your music, in a background thread to avoid tying up the Swing event thread.
  • Never call Thread.sleep(...) within the Swing Event Dispatch Thread, or EDT, as this will put your entire Swing GUI to sleep.

For example,

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class FoodCounter2 extends JPanel {
   public static final String IMAGE_PATH = "https://duke.kenai.com/iconSized/duke.gif";
   private static final Font TITLE_FONT = new Font("Dialog", Font.PLAIN, 18);
   private JLabel titleLabel = new JLabel("Welcome, User", SwingConstants.CENTER);
   private JButton backButton = new JButton("Back");
   private JButton addFoodButton = new JButton("+ Food");
   private JLabel foodCountLabel = new JLabel("0/100 Food");

   public FoodCounter2() throws IOException {
      URL imgUrl = new URL(IMAGE_PATH);
      BufferedImage img = ImageIO.read(imgUrl);
      ImageIcon icon = new ImageIcon(img);

      JPanel foodPanel = new JPanel(new GridBagLayout());
      // JPanel foodPanel = new JPanel();
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.insets = new Insets(10, 10, 10, 10);
      foodPanel.add(new JLabel("Click to Begin! --->"), gbc);
      gbc.gridx++;
      foodPanel.add(addFoodButton, gbc);
      gbc.gridx++;
      foodPanel.add(foodCountLabel, gbc);

      JPanel centerPanel = new JPanel(new BorderLayout());
      titleLabel.setFont(TITLE_FONT);
      centerPanel.add(titleLabel, BorderLayout.PAGE_START);
      centerPanel.add(foodPanel, BorderLayout.CENTER);

      setLayout(new BorderLayout());
      add(backButton, BorderLayout.LINE_START);
      add(centerPanel, BorderLayout.CENTER);
      add(new JLabel(icon), BorderLayout.LINE_END);

   }

   private static void createAndShowGui() {
      FoodCounter2 mainPanel  = null;
      try {
         mainPanel = new FoodCounter2();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      JFrame frame = new JFrame("FoodCounter2");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Which displays as:

enter image description here

Upvotes: 2

Graysull
Graysull

Reputation: 109

This is what is happening:

enter image description here

As you can see, the top part of the bread is cut off. This is because the JPanel is covering it I assume.

Upvotes: -1

Related Questions