How to make JLabel with image fill BorderLayout.CENTER - java

Ive got a JFrame and set the LayoutManager to BorderLayout and then proceeded to add my JLabel with an image. However when i resize the frame the JLabel doesnt resize. I have not added any components to North, S, E and so on. I was hoping to simply have the image inside the label fill up the entire frame leaving my menu in tact of course.

Forgive me if this seems arrogant, but I have nothing else to go on.
I did a quick sample
See the red line around the image, that's the JLabel's border. As you can see, the label is been re-sized to fill the entire area.
This is the code I used to produce the sample
public class LayoutFrame extends JFrame {
public LayoutFrame() throws HeadlessException {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Image image = null;
URL url = getClass().getResource("/layout/issue78.jpg");
try {
image = ImageIO.read(url);
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(new ImageIcon(image));
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
label.setBorder(new LineBorder(Color.RED, 4));
setLayout(new BorderLayout());
add(label);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
LayoutFrame frame = new LayoutFrame();
frame.setSize(200, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
Obviously, you'll need to supply your own image ;).
Don't forget, the label WON'T scale the content for you, if that's your goal, you'll need to implement your own component to achieve this.
If you're still having problems, I would suggest (in the absence of further evidence) that your label may not be in the container you think it is or the containers layout manager is not what you think it is.
UPDATE
I don't know why you're having issues with components going missing or issues with you menu. Are mixing heavy and light weight components??
Sample with menu bar
After reading your question a little closer, I've devised a simple resizing image pane sample. For speed, I've relied on my libraries, but it should be reasonably easy to implementation your own code in place of my calls
public class ImagePane extends JPanel {
protected static final Object RESIZE_LOCK = new Object();
private BufferedImage image;
private BufferedImage scaledImage;
private Timer resizeTimer;
public ImagePane() {
URL url = getClass().getResource("/layout/issue78.jpg");
try {
image = ImageIO.read(url);
} catch (IOException ex) {
ex.printStackTrace();
}
resizeTimer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Simple thread factory to start a slightly lower
// priority thread.
CoreThreadFactory.getUIInstance().execute(new ResizeTask());
}
});
resizeTimer.setCoalesce(true);
resizeTimer.setRepeats(false);
}
#Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
resizeTimer.restart();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if (scaledImage != null) {
// This simply returns a rectangle that takes into consideration
//the containers insets
Rectangle safeBounds = UIUtilities.getSafeBounds(this);
System.out.println("scaledImage = " + scaledImage.getWidth() + "x" + scaledImage.getWidth());
int x = ((safeBounds.width - scaledImage.getWidth()) / 2) + safeBounds.x;
int y = ((safeBounds.height - scaledImage.getHeight()) / 2) + safeBounds.y;
g2d.drawImage(scaledImage, x, y, this);
}
}
protected class ResizeTask implements Runnable {
#Override
public void run() {
synchronized (RESIZE_LOCK) {
if (image != null) {
int width = getWidth();
int height = getHeight();
System.out.println("width = " + width);
System.out.println("height = " + height);
// A simple divide and conquer resize implementation
// this will scale the image so that it will fit within
// the supplied bounds
scaledImage = ImageUtilities.getScaledInstanceToFit(image, new Dimension(width, height), ImageUtilities.RenderQuality.High);
System.out.println("scaledImage = " + scaledImage.getWidth() + "x" + scaledImage.getWidth());
repaint(); // this is one of the few thread safe calls
}
}
}
}
}

Best option is to sub class ImageIcon and override its paintIcon method to simply paint the image using the Graphics.paint( x, y, width, height ...).

Related

Add moving objects to JFrame

I'm creating a java game. In the game there are a hero and a bubble. The hero is supposed to move when I press the arrow keys and the bubble is supposed to have continuous diagonal movement. When I add the hero or the bubble directly into to the JFrame separately I get the desired behavior, but when I add them both I just get a very small square! I tried to add them to the same JPanel and after add that JPanel to the JFrame but it is not working. Probably I have to define some type of layout to the JPanels.
What am I doing wrong?
Code:
public class Pang {
public static void main(String[] args) {
JFrame f=new JFrame();
JPanel gamePanel=new JPanel();
gamePanel.setPreferredSize(new Dimension(800, 600));
DrawHero d=new DrawHero();
DrawBubble bubble=new DrawBubble();
gamePanel.add(d);
gamePanel.add(bubble);
f.add(gamePanel);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800, 600);
}
}
public class DrawHero extends JPanel implements ActionListener, KeyListener {
Timer myTimer = new Timer(5, this);
int x = 0, y = 0, dx = 0, dy = 0, step = 10;
private transient Image imageHero = null;
public DrawHero() {
myTimer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
imageHero = getHeroImage();
g2.drawImage(imageHero, x, y, 40, 40, null);
}
public Image getHeroImage() {
Image image = null;
image = getImage("hero.png");
return image;
}
public Image getImage(String path) {
Image tempImage = null;
try {
URL heroiURL = DrawHero.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(heroiURL);
} catch (Exception e) {
System.out.println("Error loading hero image! - "
+ e.getMessage());
}
return tempImage;
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void moveUp() {
y = y - step;
}
public void moveDown() {
y = y + step;
}
public void moveLeft() {
x = x - step;
}
public void moveRight() {
x = x + step;
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
moveUp();
}
if (keyCode == KeyEvent.VK_DOWN) {
moveDown();
}
if (keyCode == KeyEvent.VK_LEFT) {
moveLeft();
}
if (keyCode == KeyEvent.VK_RIGHT) {
moveRight();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
public class DrawBubble extends JPanel implements ActionListener, KeyListener {
Timer myTimer = new Timer(5, this);
int x = 100, y = 200, dx = 0, dy = 0, step = 10;
private transient Image imageHero = null;
public DrawBubble() {
myTimer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.fill(new Ellipse2D.Double(x, y, 40, 40));
}
public void actionPerformed(ActionEvent e) {
x=x+dx;
y=y+dy;
repaint();
}
public void moveBubble() {
dy=2;
dx=2;
}
public void keyPressed(KeyEvent e) {
moveBubble();
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
I recommend that neither the DrawHero nor DrawBubble (which should be called Hero nor Bubble respectively) should extend any JComponent. Instead each should simply know how to draw itself to a Graphics object passed to it, when requested to do so.
Then a single GameField or PlayingArea class should keep references to all the Bubble objects and the Hero and draw call the draw(Graphics) method of those objects.
Using this approach it is not necessary to worry about layouts within the GameField component (they become irrelevant).
That is the basic strategy I pursue for rendering the stationary objects in this answer to [Collision detection with complex shapes.
When I add the hero or the bubble directly into to the JFrame separately I get the desired behavior, but when I add them both i just get a very small square!
The default layout manager for a JFrame is a BorderLayout. When you use add(component) without a constraint the component goes to the CENTER. Only one component can be added to the CENTER, so only the last one added is displayed.
I tried to add them to the same JPanel and after add that JPanel to the JFrame but it is not working.
The default layout manager for a JPanel is the FlowLayout which respects the preferred size of component. The problem is you don't override the getPreferredSize() method so the size is (0, 0) and there is nothing to paint.
Probably I have to define some type of layout to the JPanels.
Actually since you want random motion you need to use a null layout on the panel and then use the setSize() and setLocation() method of your components to position the components.
Then when you do this the custom painting should always be done at (0, 0) instead of (x, y) since the location will control where the component is painted on the panel.

Java - instantiating a class in a loop

I'm having an issue instantiating a class in Java, essentially it generates a new world every tick, which is a bit frustrating when the program runs.
Whereas all I need to do is instantiate it then access a variable inside the class.
Here's the code:
Background.java
public class Background extends UserView {
private BufferedImage bg;
private static Game game;
public Background(World w, int width, int height) {
super(w, width, height);
try {
bg = ImageIO.read(new File("data/background.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void paintBackground(Graphics2D g) {
super.paintBackground(g);
game = new Game();
g.drawImage(bg, 0, 0, this);
int level = game.getLevel();
g.drawString("Level: " + level, 25, 25);
}
}
Game.java
public Game() {
// make the world
level = 1;
world = new Level1();
world.populate(this);
// make a view
view = new Background(world, 500, 500);
// uncomment this to draw a 1-metre grid over the view
// view.setGridResolution(1);
// display the view in a frame
JFrame frame = new JFrame("Save the Princess");
// quit the application when the game window is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
// display the world in the window
frame.add(view);
// don't let the game window be resized
frame.setResizable(false);
// size the game window to fit the world view
frame.pack();
// make the window visible
frame.setVisible(true);
// get keyboard focus
frame.requestFocus();
// give keyboard focus to the frame whenever the mouse enters the view
view.addMouseListener(new GiveFocus(frame));
controller = new Controller(world.getPlayer());
frame.addKeyListener(controller);
// start!
world.start();
}
/** Run the game. */
public static void main(String[] args) {
new Game();
}
Any help would be appreciated! Thank you!
Well you probably need to think about the class concept nad its dependencies, but this is the easiest and fastest approach in your case to keep only one instance of Game :
public class Background extends UserView {
private BufferedImage bg;
private static Game game = new Game();
public Background(World w, int width, int height) {
super(w, width, height);
try {
bg = ImageIO.read(new File("data/background.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void paintBackground(Graphics2D g) {
super.paintBackground(g);
g.drawImage(bg, 0, 0, this);
int level = game.getLevel();
g.drawString("Level: " + level, 25, 25);
}
}
If you add more code and say what you want and what you get, we can say you more about it.

Rescale BufferedImage java

Hi i am looking for a way to rescale my image and still show the entire image, so it isn't cut in half or something like that. I am also not allowed to use libraries of any sort. Im drawing the image with paintcomponent.
Is there any way how to do this properly?
I've tried this one already :
BufferedImage image = null;
try {
image = ImageIO.read(new File($question.getMediaFile().getPath())); /* Get the image */
Image scaled = image.getScaledInstance(350, 350, Image.SCALE_SMOOTH);
g.drawImage(scaled, w-350, 200, null);
} catch (IOException e) {
e.printStackTrace();
}
This resizes my image but doesn't show the entire image, i would like to rescale it to an image with 300*300 or 350*350 size or something like that.
Thanks!
Using the getScaledInstance() method works fine for me. Here's the code i was testing with:
public class Resize {
public static void main(String[] args) throws Exception {
final Image logo = ImageIO.read(new URL("http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png"));
final Dimension dim = new Dimension(logo.getWidth(null), logo.getHeight(null));
final JFrame frame = new JFrame();
frame.add(new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(logo.getScaledInstance(dim.width, dim.height, 0), 0, 0, this);
}
});
final JSlider xSlider = new JSlider(JSlider.HORIZONTAL, 1, dim.width*3, dim.width);
final JSlider ySlider = new JSlider(JSlider.VERTICAL, 1, dim.height*3, dim.height);
ChangeListener cl = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
dim.width = xSlider.getValue();
dim.height = ySlider.getValue();
frame.repaint();
}
};
xSlider.addChangeListener(cl);
ySlider.addChangeListener(cl);
frame.add(xSlider, "South");
frame.add(ySlider, "East");
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

drawImage within separate jpanel draws just a piece

I'm not that familiar with Java and I'm a little clueless about my current problem.
I'm trying to draw an Image within a separate class of my Main JFrame, but it
always draw just a little piece of the picture (maybe 10x10px).
(A test with a Label worked)
Maybe I didn't used the g.drawImage method correct, or the JPanel don't have enough space??
MainWindow:
public class Deconvolutioner extends JFrame {
Draw z;
Picturearea picturearea;
class Draw extends JPanel {
public void paint(Graphics g) {
}
}
public Deconvolutioner() {
setTitle("Deconvolutioner");
setLocation(30,1);
setSize(1300,735);
super.setFont(new Font("Arial",Font.BOLD,11));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
this.setLayout(flow);
picturearea = new Picturearea();
this.add(picturearea);
add(z = new Draw());
setVisible(true);
}
class Open implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser fileOpen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("png & jpg files", "png",
"jpg");
fileOpen.addChoosableFileFilter(filter);
int returnVal = fileOpen.showDialog(null, "Open file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
String path = fileOpen.getSelectedFile().getPath();
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
picturearea.setPicture(img);
} catch (IOException ex) {
System.err.println("Some IOException accured (set the right path?): ");
System.err.println(ex.getMessage());
}
} else {
}
repaint();
}
}
And the separate class:
public class Picturearea extends JPanel {
public BufferedImage image;
Draw z;
public Picturearea() {
add(z = new Draw());
setVisible(true);
}
class Draw extends JPanel {
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
public void setPicture(BufferedImage picture) {
try {
image = picture;
} catch (Exception e) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(e.getMessage());
}
repaint();
}
}
I'm grateful for every help.
thanks for your time.
You are using FlowLayout for JFrame's contentPane's layout. FlowLayout obeys component's preferredSize. Try setting preferredSize of your pictureArea by pictureArea.setPreferredSize(Dimension) or overriding getPreferredSize(Dimension) function in PictureArea class.
you are using paint(Graphics g) for custom painting:
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
Do not override paint() for custom painting override paintComponent(Graphics g) instead. And You may need to scale your image to fit in the size of the JPanel. you can use g.drawImage(x, y, width, height, observer) function if you need to scale your image.
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}

JScrollPane doesn't update JScrollBar on JSplitPane

I want to create simple app able to edit images. Main view of app contains JSplitPane with two JScrollPane. Each JScrollPane contains JPanel. The right JPanel has several buttons etc. and the left JPanel is my drawing area.
Here is my problem...
When I first created JPanelDrawingArea I could set preferred size. If the size is bigger than size of JScrollPane the JScrollBars show up (in default it is equal). But when I load image to JPanelDrawingArea scroll bars don't update. Despite the fact I set new preferred size of JPanelDrawingArea (bigger than size of JScrollPane) scroll bars don't update unless I manually change the JSplitPanes divider position.
Here is my JSplitPane custom class:
public class DrawingPaneView extends JSplitPane{
private DrawingWorkMode drawingWorkMode;
private ImageWorkerView imageWorker;
JScrollPane workScrollPane;
JScrollPane pictureScrollPane;
private DrawingPaneController controller;
private Dimension minimumSize = new Dimension(100, 200);
private JPanel imagePanel;
public DrawingPaneView() {
setPreferredSize(new Dimension(ConfigClass.APP_WIDTH,ConfigClass.DRAWING_PANE_HEIGHT));
controller = new DrawingPaneController(this);
//Panel
drawingWorkMode = new DrawingWorkMode();
workScrollPane = new JScrollPane(drawingWorkMode);
//Image
imageWorker = new ImageWorkerView();
pictureScrollPane = new JScrollPane(imageWorker);
workScrollPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//addJPanels
this.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
this.setRightComponent(workScrollPane);
this.setLeftComponent(pictureScrollPane);
//addLeftPanelWithJButtonOnly
imagePanel = new ImagePanelView();
pictureScrollPane.setRowHeaderView(imagePanel);
this.setDividerLocation(ConfigClass.DRAWING_PANE_WIDTH);
this.setOneTouchExpandable(true);
}
//Change mode
public void changeMode(String mode){
drawingWorkMode.changeMode(mode);
}
}
And there is my custom JPanel which perform drawing:
public class ImageWorkerView extends JPanel {
private BufferedImage img;
private ImageWorkerController controller;
private int defaultBounds = 50;
private double scale=1.0;
int imgW;
int imgH;
public ImageWorkerView() {
//setLayout(new BorderLayout(0, 0));
controller = new ImageWorkerController(this);
}
public void setScale(double scale) {
this.scale = scale;
}
public void setImage(File image) {
try {
img = ImageIO.read(image);
if (img.getType() != BufferedImage.TYPE_INT_RGB) {
BufferedImage img2 =
new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics big = img2.getGraphics();
big.drawImage(img, 0, 0, null);
img = img2;
}
} catch (IOException e) {
System.out.println("Image could not be read");
}
}
private void adjustPreferredSize(Boolean defaultSize){
if(defaultSize){
//Calculate the proper size of drawing area
imgW = ConfigClass.DRAWING_PANE_WIDTH - ImagePanelView.PREFERRED_WIDTH-10;
imgH = ConfigClass.DRAWING_PANE_HEIGHT-50;
setPreferredSize(new Dimension(imgW,imgH));
controller.setWindowHeight(imgH);
}
else{
imgW = (int)(img.getWidth() * scale + (defaultBounds*2));
imgH = (int)(img.getHeight() * scale + (defaultBounds*2));
setPreferredSize(new Dimension(imgW,imgH));
controller.setWindowHeight(imgH);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(img!=null){
if(scale!=1.0){
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp aop =
new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
g2.drawImage(img, aop, defaultBounds, defaultBounds);
}
else
g2.drawImage(img, defaultBounds, defaultBounds, null);
adjustPreferredSize(false);
}
else{
adjustPreferredSize(true);
}
}
}
And how i load image:
public class ImageWorkerController {
ImageWorkerView view;
ImageModel model;
public ImageWorkerController(ImageWorkerView workerView) {
this.view = workerView;
this.model = ApplicationContext.getObject(ImageModel.class);
//Load image
ApplicationContext.getObject(Context.class).addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(Context.IMAGE_LOADED.equals(evt.getPropertyName())){
view.setImage((File) evt.getNewValue());
view.repaint();
}
}
});
public void setWindowHeight(int h){
model.setDrawingWindowHeight(h);
}
}
As you can see there is adjustPreferredSize() method, when it is first called, and it sets preferredSize bigger than JScrollPane, JScrollBars appear. But when it is called again it does nothing.
What is interesting, when I manually change divider's location JScrollBars show up, on screen below you have an example:
http://s17.postimage.org/e1nkja3zx/liliebead.jpg
So there is some kind of event, which makes JScrollPane to update? I've tried several ways: updateUI(), repaint(), revalidate(). None of them worked.
Any ideas what I am doing wrong?
In short, you need to revalidate() your ImageWorkerView (right where you call repaint()). This will ask the component and its parent for "re-layout" and that in turn will trigger necessary adjustments for the scroll bars.
Thanks for your answer! Your suggestion made me think. What actually I did wrong is call revalidate() immediatelly after repaint() so in fact revalidate() executes before paintComponent method in ImageWorkerView (I found this out during debugging). The proper way to do this is:
ApplicationContext.getObject(Context.class).addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(Context.IMAGE_LOADED.equals(evt.getPropertyName())){
view.setImage((File) evt.getNewValue());
//view.repaint();
view.paintImmediately(new Rectangle(1, 1));
view.revalidate();
}
}
});
So now paintComponent sets preferred size and then revalidate() adjust scroll bars.

Categories

Resources