I have trouble with my IT class project in NetBeans and jFrame. When I set the background image, there is a weird rectangle, after changing it via menu bar and menu item. There is no jPanel or other components that could cover it.
This is how I set the background:
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
Graphics x= this.getGraphics();
Image img = null;
try
{img = ImageIO.read(new File("noga1.jpg"));
x.drawImage(img, 0, 0, rootPane);}
catch (Exception e) {}
}
And that's what we can see after performing an action:
Related
I am facing an issue that I am not able to draw an png image into my swing GUI into JPanel (which I am adding into JScrollPane after).
Here is my code I am trying to use for this.
if(processCreated == true){
System.out.println("updating tree of organisms");
processCreated = false;
updateTree();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Svet.class.getName()).log(Level.SEVERE, null, ex);
}
tree = new File(path+"/out.png"); //File
try {
treeImage = ImageIO.read(tree); //BufferedImage
tp = new TreePane(treeImage.getScaledInstance( 500, 500 ,treeImage.SCALE_SMOOTH)); // my class, implementation below
treeOutput.add(tp); //adding "JPanel" with picture into GUI
treeOutput.repaint();
} catch (IOException ex) {
Logger.getLogger(Svet.class.getName()).log(Level.SEVERE, null, ex);
}
}
After this the JScrollPane remains empty. Is there anything wrong with my code? You can find what is what in comments.
Here is my TreePane class
public class TreePane extends JPanel{
Image img;
public TreePane( Image img ){
this.img = img;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int imgX = 0;
int imgY = 0;
g.drawImage(img, imgX, imgY, this);
}
}
Very likely your TreePane is layed out to size 0,0 and therefore you'll never see anything. Try adding a breakpoint and inspecting in paintComponent - it might not even ever get called.
To fix, you should explicitly set the size of your TreePane before adding it to the JScrollPane.
tp = new TreePane(treeImage.getScaledInstance( 500, 500 ,treeImage.SCALE_SMOOTH)); // my class, implementation below
tp.setSize(myWidth, myHeight);
treeOutput.add(tp); //adding "JPanel" with picture into GUI
treeOutput.repaint();
I have a GUI, which consists of a JFrame and Menu bar. Inside the JFrame is my custom Panel (extending JPanel), which is initially hidden. The user chooses an image (JFileChooser), this image is passed to the panel and drawn (using paintIcon). The panel is resized to fit the image and then set visible. I want to resize my JFrame to fit the panel, but I cannot seem to get it to work. I have tried using the pack() method, but this just makes a tiny GUI, that is the size of the JMenu! I have also tried resizing both the frame and the JPanel using the getIconWidth() and getIconHeight() properties of the ImageIcon, but while this correctly sizes the panel it does not size the JFrame. Any ideas as to how I would do this correctly?
The block of code where I am setting the size of the JFrame is here:
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser imgChooser = new JFileChooser();
JMenuItem evtSource = (JMenuItem) e.getSource();
String srcText = evtSource.getText();
if (srcText.equals("Add Image..."))
{
imgChooser = new JFileChooser();
imgChooser.showOpenDialog(frmMain);
chosenImage = imgChooser.getSelectedFile();
try
{
loadedImage = ImageIO.read(chosenImage);
}
catch (IOException ex)
{
String errorMsg = ex.getMessage();
JOptionPane.showMessageDialog(frmMain, "Error while loading file: " + errorMsg, "Error!", JOptionPane.ERROR_MESSAGE);
}
panelImage = new ImageIcon(loadedImage);
frmMain.setSize(panelImage.getIconWidth(), panelImage.getIconHeight() + mbMenu.getHeight());
displayImage.loadImage(panelImage);
displayImage.setVisible(true);
}
}
The code from the relevant sections of the "displayImage" custom panel is below:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (imgIsLoaded)
{
panelImage.paintIcon(this,g2,0,0);
resizePanel(panelImage.getIconWidth(), panelImage.getIconHeight());
}
}
public void loadImage(ImageIcon i)
{
panelImage = i;
imgIsLoaded = true;
}
public void resizePanel(int w, int h)
{
this.setSize(w, h);
}
Override getPreferredSize() in the panel to return a default value (e.g. 400x400) if it has no image, and the size of the image otherwise.
After setting an image, call frame.pack().
BTW - if all the panel does is paint the image, I'd opt for a JLabel instead.
Some days ago, I wasted a lot of time searching some way to show a image in a JFrame. And here is my final solution:
jPanel1 = new javax.swing.JPanel(){
#Override
public void paintComponent(Graphics g) {
BufferedImage image = null;
try {
BufferedImage in = ImageIO.read(Startup.class.getResource("imagem.jpg"));
image = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);
g.drawImage(in, 0, 0, null);
} catch (Exception ex) {}
super.paintComponents(g);
}
};
I just want to know, if it is the one way to do that, or exists another solutions like a image component on Swing o AWT that can be easily used?
You can show an image using JLabel, which is much simpler than your solution. For example:
label.setIcon(new ImageIcon("Path/to/your/image.jpg"));
I am using Jtree for listing various images of a directory, I want to display image on applet when the user click on the image name displayed in the Tree, the code i'm using is as below, ta is an object of the applet because i'm using it in another class.
private void displayImage(URL furl, String fname) {
ta.Picture = ta.getImage(furl, fname);
prepareImage(ta.Picture, this);
Graphics g = ta.imageCanvas.getGraphics();
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
} // displayImage
public void valueChanged(TreeSelectionEvent e)
{
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode) tree.getLastSelectedPathComponent();
System.out.println("slecte asldf " + node.isLeaf());
if (node.isLeaf())
{
currentFile = node.file;
System.out.println("File name " + currentFile.getName());
try
{
URL furl = new URL("file:/F:/photos");
displayImage(furl, currentFile.getName());
}
catch (MalformedURLException mle)
{
System.out.println("Exception::::::" + mle);
}
}
else
currentFile = null;
}
But its not working.
As you are showing files from the local filesystem, working with URLs is not required. Use
displayImage(currentFile);
and rewrite that method as following:
private void displayImage(File file) {
BufferedImage image = ImageIO.read(file);
ta.image = image;
ta.repaint();
}
where the paint method of the (I an assuming) component ta must be like
BufferedImage image;
public void paint(Graphics g) {
g.clearRect(10, 10, 800, 800);
g.drawImage(ta.Picture, 10, 10, this);
}
Because of security reasons, the applet will only be able to access the file system if signed or running without security manager (most often on the same computer).
But its not working.
This is in no way helpful, do you get exceptions? What happens? Please post an SSCCE for better help sooner
I want to display image on applet when the user click on the image
name displayed in the Tree, the code i'm using is as below, ta is an
object of the applet because i'm using it in another class.
IMO you are going about it wrong using the JPanel object and Component#getGraphics.
Dont use Component#getGraphics() as its not good practice and not persistent thus on next call to repaint() the screen will be cleared.
Dont use Applet with Swing components rather use JApplet.
Add a custom JPanel with getters and setters for BufferedImage variable to the container and than override paintComponnet and draw the BufferedImage there.
Now to change the BufferedImage simply call the setter i.e setBackgroundImage(BufferedImage img) and than call repaint() on JPanel to show the changes. Like so:
public class MyPanel extends JPanel {
private BufferedImage bg;
public MyPanel(BufferedImage bi) {
bg=bi;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
g2d.drawImage(bg,0,0,this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(bg.getWidth(),bg.getHeight());
}
public BufferedImage setBackgroundImage(BufferedImage bi) {
bg=bi;
}
}
Now we use it like so:
MyPanel mp=new MyPanel(...);//create the panel with an image
...
add(mp);//add to container
...
mp.setBackgroundImage(..);//change the image being displayed
mp.repaint();//so the new image may be painted
I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?
I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}
I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*
Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}
I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}