I have a program, with JFrame and JInternalFrames inside. So, when I try to set background with this code:
BufferedImage myImage;
myImage = ImageIO.read(new File("C:/5/JavaLibrary2/background.jpg"));
ImagePanel Image = new ImagePanel(myImage);
frame.setContentPane(Image);
My JInternalFrames just gone. So, see a short video with debug
frame.setContentPane(Image); just delete my JInternal windows.
I have no issue.
I've used both a JLabel and custom painting routines.
I've created and setup the internal frames BEFORE adding them to the desktop,
I've added the internal frame to the desktop and THEN changed their content panes as well as throwing the update to the end of the EDT to ensure that the main frame is visible.
The problem must be in some part of your code you're not showing us.
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
public TestInternalFrame() {
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) {
}
JDesktopPane desktop = new JDesktopPane();
final JInternalFrame frame1 = new JInternalFrame("Image on Label");
// frame1.setContentPane(new LabelImagePane());
// frame1.pack();
// frame1.setLocation(0, 0);
frame1.setVisible(true);
desktop.add(frame1);
final JInternalFrame frame2 = new JInternalFrame("Painted Image");
// frame2.setContentPane(new ImagePane());
// frame2.pack();
// frame2.setLocation(frame1.getWidth(), 0);
frame2.setVisible(true);
desktop.add(frame2);
JFrame frame = new JFrame("I Haz Images");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(desktop);
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame1.setContentPane(new LabelImagePane());
frame1.pack();
frame1.setLocation(0, 0);
frame2.setContentPane(new ImagePane());
frame2.pack();
frame2.setLocation(frame1.getWidth(), 0);
}
});
}
});
}
public class LabelImagePane extends JPanel {
public LabelImagePane() {
setLayout(new BorderLayout());
JLabel label = new JLabel();
add(label);
try {
label.setIcon(new ImageIcon(ImageIO.read(new File("..."))));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImagePane extends JPanel {
private BufferedImage image;
public ImagePane() {
try {
image = ImageIO.read(new File("..."));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g.drawImage(image, x, y, this);
}
}
}
}
Related
I am trying to make a PacMan alternative with a tiger chasing bagels (don't ask why). I'm on the first stage still, trying to make the tiger move around the JFrame. However, now that I implemented the KeyEvent, the image is no longer showing up. I have been stuck on this for an hour, and I don't understand where I went wrong.
Edit: I have got the image to show up, but the image does not update or change location when pressing on the arrow keys, probably something to do with the connection between the KeyEvent and the PacMan class.
Main:
public Main() {
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
UI frame = null;
try {
frame = new UI();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
});
}
UI:
public PacMan PacMan;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT){
PacMan.moveRight();
}
if (key == KeyEvent.VK_LEFT){
PacMan.moveLeft();
}
if (key == KeyEvent.VK_UP){
PacMan.moveUp();
}
if (key == KeyEvent.VK_DOWN){
PacMan.moveDown();
}
}
public UI() throws IOException {
this.PacMan = new PacMan();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setTitle("PacMan");
frame.setResizable(false);
frame.setSize(1200, 700);
frame.setMinimumSize(new Dimension(1200, 700));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setBackground(Color.BLACK);
panel.add(PacMan.getImage());
frame.add(panel);
frame.setVisible(true);
}
PacMan:
public int xCoords = 570;
public int yCoords = 320;
JLabel pacManImage = new JLabel();
Icon tigerLeft;
Icon tigerRight;
public PacMan() throws IOException {
ImageIcon tigerLeft = new ImageIcon(new ImageIcon("textures/tigerLeft.png").getImage().getScaledInstance(60, 40, Image.SCALE_DEFAULT));
ImageIcon tigerRight = new ImageIcon(new ImageIcon("textures/tigerRight.png").getImage().getScaledInstance(60, 40, Image.SCALE_DEFAULT));
pacManImage.setIcon(tigerRight);
pacManImage.setVisible(true);
}
public void initialDraw() {
pacManImage.setBounds(xCoords, yCoords, 60, 40);
pacManImage.setIcon(tigerRight);
pacManImage.repaint();
}
public void moveRight() {
System.out.println("here: " + tigerRight);
//xCoords = xCoords + 2;
pacManImage.setIcon(tigerRight);
pacManImage.setLocation(pacManImage.getLocationOnScreen().x + 2, pacManImage.getLocationOnScreen().y);
pacManImage.repaint();
}
public void moveLeft() {
//xCoords = xCoords + 2;
pacManImage.setIcon(tigerLeft);
pacManImage.setLocation(pacManImage.getLocationOnScreen().x - 2, pacManImage.getLocationOnScreen().y);
pacManImage.repaint();
}
public void moveUp() {
//yCoords = yCoords + 2;
pacManImage.setLocation(pacManImage.getLocationOnScreen().x, pacManImage.getLocationOnScreen().y - 2);
pacManImage.repaint();
}
public void moveDown() {
//yCoords = yCoords + 2;
pacManImage.setLocation(pacManImage.getLocationOnScreen().x, pacManImage.getLocationOnScreen().y + 2);
pacManImage.repaint();
}
public JLabel getImage(){
return pacManImage;
}
Your UI class is not complete so I can't tell exactly what you are doing. I can only guess.
Ignoring the actual KeyListener code, my guess is you have code like:
public class UI extends JPanel
{
public UI() throws IOException
{
this.PacMan = new PacMan();
addKeyListener(this);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.add(PacMan.getImage());
frame.add(panel);
frame.setVisible(true);
}
}
So once again you have two JPanel components:
the UI class "is a" JPanel and you add the KeyListener to it.
then you create a second JPanel and add the "PacMan" to that panel and add that panel to the frame.
So the problem is the first panel has the KeyListener but it is never added to the frame.
Your class should look like:
public class UI extends JPanel
{
public UI() throws IOException
{
this.PacMan = new PacMan();
addKeyListener(this);
setBackground(Color.BLACK);
add(PacMan.getImage());
}
}
That's it. The creation of the frame does not belong in this class.
I found out that my keyReleased function was never being called, and I fixed that issue by issuing the simplest fix, moving the KeyListener within the UI method.
UI class code:
public class UI extends JPanel {
public PacMan PacMan;
public UI() throws IOException {
this.PacMan = new PacMan();
addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN){
PacMan.moveDown();
}
if (e.getKeyCode() == KeyEvent.VK_UP){
PacMan.moveUp();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT){
PacMan.moveLeft();
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
PacMan.moveRight();
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
});
setFocusable(true);
setBackground(Color.BLACK);
add(PacMan.getImage());
}
i want to make a screenshot of the panel that i have created and the code is given below.
Can any body please tell me why i am not getting.thanks
public static final void makeScreenshot(JFrame argFrame)
{
Rectangle rec = argFrame.getBounds();
BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
argFrame.paint(bufferedImage.getGraphics());
try
{
// Create temp file.
File temp = File.createTempFile("C:\\Documents and Settings\\SriHari\\My Documents\\NetBeansProjects\\test\\src\\testscreenshot", ".jpg");
// Use the ImageIO API to write the bufferedImage to a temporary file
ImageIO.write(bufferedImage, "jpg", temp);
//temp.deleteOnExit();
}
catch (IOException ioe) {}
} //
public static void main(String args[])
{
TimeTableGraphicsRunner ts= new TimeTableGraphicsRunner();
for(long i=1;i<1000000000;i++);
ts.makeScreenshot(jf);
System.out.println("hi");
}
The following works for me:
public static void main (String [] args)
{
final JFrame frame = new JFrame ();
JButton button = new JButton (new AbstractAction ("Make Screenshot!")
{
#Override
public void actionPerformed (ActionEvent e)
{
Dimension size = frame.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame.paint (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
});
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane ().setLayout (new BorderLayout ());
frame.getContentPane ().add (button, BorderLayout.CENTER);
frame.pack ();
frame.setVisible (true);
}
It does not render window title and border because this is handled by OS, not Swing.
You could try using something like Robot#createScreenCapture
If you don't want to capture the whole screen, you can use Component#getLocationOnScreen to find the position of the component on the screen instead...
public class CaptureScreen {
public static void main(String[] args) {
new CaptureScreen();
}
public CaptureScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(new JLabel("Smile :D"), gbc);
JButton capture = new JButton("Click");
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
Robot robot = new Robot();
Rectangle bounds = frame.getBounds();
bounds.x -= 1;
bounds.y -= 1;
bounds.width += 2;
bounds.height += 2;
BufferedImage snapShot = robot.createScreenCapture(bounds);
ImageIO.write(snapShot, "png", new File("Snapshot.png"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
frame.add(capture, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Example using Component#getLocationOnScreen
public class CaptureScreen {
public static void main(String[] args) {
new CaptureScreen();
}
public CaptureScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(new JLabel("Smile :D"), gbc);
JButton capture = new JButton("Click");
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
Robot robot = new Robot();
Container panel = frame.getContentPane();
Point pos = panel.getLocationOnScreen();
Rectangle bounds = panel.getBounds();
bounds.x = pos.x;
bounds.y = pos.y;
bounds.x -= 1;
bounds.y -= 1;
bounds.width += 2;
bounds.height += 2;
BufferedImage snapShot = robot.createScreenCapture(bounds);
ImageIO.write(snapShot, "png", new File("Snapshot.png"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
frame.add(capture, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Another Example show Component#getLocationOnScreen
The main reason 3 of the image are the same, is because the example dumps the root pane, layerd pane and content pane...
public class CaptureScreen {
public static void main(String[] args) {
new CaptureScreen();
}
public void save(Component comp, File file) {
if (comp.isVisible()) {
try {
System.out.println(comp);
Robot robot = new Robot();
Rectangle bounds = new Rectangle(comp.getLocationOnScreen(), comp.getSize());
bounds.x -= 1;
bounds.y -= 1;
bounds.width += 2;
bounds.height += 2;
BufferedImage snapShot = robot.createScreenCapture(bounds);
ImageIO.write(snapShot, "png", file);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private int layer;
public void capture(Container container) {
layer = 1;
captureLayers(container);
}
public void captureLayers(Container container) {
save(container, new File("SnapShot-" + layer + "-0.png"));
int thisLayer = layer;
int count = 1;
for (Component comp : container.getComponents()) {
if (comp instanceof Container) {
layer++;
captureLayers((Container) comp);
} else {
save(comp, new File("SnapShot-" + thisLayer + "-" + count + ".png"));
count++;
}
}
}
public CaptureScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(new JLabel("Smile :D"), gbc);
JButton capture = new JButton("Click");
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
capture(frame);
}
});
frame.add(capture, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I'm trying to create a hold button on Java for my bandit machine, when pressed it will hold that image and the other 2 images will keep spinning. Anyone know the code to allow that to happen?
if (e.getSource()== btnaddcash){
txtbalance.setForeground(Color.red);
cash = cash + 100;
txtbalance.setText(cash + "");
if (e.getSource() == btnpic1){
The basic concept is, you want to spin an image (or take some action) while the button is "armed".
A way by which you can achieve this is to add a ChangeListener to the button and monitor the ButtonModel#isArmed state.
public class ChangeButton {
public static void main(String[] args) {
new ChangeButton();
}
public ChangeButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SlotPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SlotPaneextends JPanel {
private SpinPane spinPane;
private JButton button;
public SlotPane() {
spinPane = new SpinPane();
button = new JButton("Press");
// I've attached directly to the model, I don't
// think this is required, simply attaching a change
// listener to the button achieve the same result.
button.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
spinPane.setSpinning(button.getModel().isArmed());
}
});
setLayout(new BorderLayout());
add(spinPane);
add(button, BorderLayout.SOUTH);
}
}
public class SpinPane extends JPanel {
private BufferedImage mole;
private Timer timer;
private float angel = 0;
public SpinPane() {
try {
mole = ImageIO.read(new File("mole.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
timer = new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
angel += 15;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
}
#Override
public Dimension getPreferredSize() {
return mole == null ? super.getPreferredSize() : new Dimension(mole.getWidth(), mole.getHeight());
}
public void setSpinning(boolean spinning) {
if (spinning) {
if (!timer.isRunning()) {
timer.restart();
}
} else {
timer.stop();
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mole != null) {
int x = (getWidth() - mole.getWidth()) / 2;
int y = (getHeight() - mole.getHeight()) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angel), getWidth() / 2, getHeight() / 2));
g2d.drawImage(mole, x, y, this);
g2d.dispose();
}
}
}
}
thank you so much but I need Listener methods and solved it now.. But now I cant see the buttons until I hover on them! I think its just a small mistake but I couldnt figure it out!! Now my code is like below...
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class PaintMain extends JFrame
{
JPanel colorPanel = new JPanel();
JPanel drawPanel = new JPanel();
JPanel selectPanel = new JPanel();
JButton[][] randomColors = new JButton[5][5];
Color selectedColor = Color.BLACK;
Random colorGenerator = new Random();
int curx = drawPanel.getX();
int cury = drawPanel.getY();
public PaintMain()
{
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colorPanel.setLayout(new GridLayout(5,5));
drawPanel.setLayout(new BorderLayout());
drawPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
randomColors[i][j]=new JButton();
randomColors[i][j].setBackground(getRandomColor());
randomColors[i][j].addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if( e.getSource() instanceof JButton)
{
selectedColor=((JButton)e.getSource()).getBackground();
System.out.println(selectedColor);
}
}
});
colorPanel.add(randomColors[i][j]);
}
}
this.addMouseMotionListener(new MouseLsnr());
add(colorPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.CENTER);
setVisible(true);
pack();
}
public Color getRandomColor()
{
return new Color(colorGenerator.nextInt(256), colorGenerator.nextInt(256), colorGenerator.nextInt(256));
}
public static void main(String[] args)
{
new PaintMain();
}
public void paint(Graphics g)
{
//super.paint(g);
g.setColor(selectedColor);
g.drawRect(curx, cury, 2, 1);
}
class MouseLsnr implements MouseMotionListener
{
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0.getX()+":"+arg0.getY());
curx=arg0.getX();
cury=arg0.getY();
repaint();
}
public void mouseMoved(MouseEvent arg0)
{
}
}
}
You'll want to take a closer look at Custom Painting
The you might want to take a read through How to Write a Mouse Listener
public class RandomColorPane {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new RandomColorPane();
}
public RandomColorPane() {
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) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
JPanel colorPanel = new JPanel();
JPanel drawPanel = new DrawPane();
JPanel selectPanel = new JPanel();
JPanel[][] randomColors = new JPanel[5][5];
Color selectedColor = Color.BLACK;
Random colorGenerator = new Random();
int curx = drawPanel.getX();
int cury = drawPanel.getY();
public MainPane() {
setLayout(new BorderLayout());
colorPanel.setLayout(new GridLayout(5, 5));
drawPanel.setLayout(new BorderLayout());
drawPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
randomColors[i][j] = new JPanel();
randomColors[i][j].setPreferredSize(new Dimension(25, 25));
randomColors[i][j].setBackground(getRandomColor());
// randomColors[i][j].addActionListener(new ActionListener() {
// #Override
// public void actionPerformed(ActionEvent e) {
// if (e.getSource() instanceof JButton) {
// selectedColor = ((JButton) e.getSource()).getBackground();
// drawPanel.setForeground(selectedColor);
// drawPanel.repaint();
// }
// }
//
// });
randomColors[i][j].addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
drawPanel.setForeground(((JPanel)e.getSource()).getBackground());
drawPanel.repaint();
}
});
colorPanel.add(randomColors[i][j]);
}
}
add(colorPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.CENTER);
}
public Color getRandomColor() {
return new Color(colorGenerator.nextInt(256), colorGenerator.nextInt(256), colorGenerator.nextInt(256));
}
}
public class DrawPane extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - 10) / 2;
int y = (getHeight() - 10) / 2;
g.setColor(getForeground());
g.fillRect(x, y, 20, 20);
}
}
}
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 ...).