I have to use the function of this class in another class in action_performed. This code is giving me error.
public class Menu {
public void Menu()
{
try {
Image img = ImageIO.read(getClass().getResource("Image1.jpg"));\\to get image
Image img1 = ImageIO.read(getClass().getResource("Image2.jpg"));
Image img2 = ImageIO.read(getClass().getResource("Image3.png"));
Image img3 = ImageIO.read(getClass().getResource("Image4.jpg"));
Image img4= ImageIO.read(getClass().getResource("Image5.jpg"));
Image img5= ImageIO.read(getClass().getResource("Image6.jpg"));
JFrame f1=new JFrame("Menu");
f1.setSize(400,200);
f1.setVisible(true);
JPanel P1=new JPanel();
P1.setVisible(true);
JButton b1=new JButton("Creamy Chocolate Cup");
b1.setIcon(new ImageIcon(img));
b1.add(P1);
b1.setVisible(true);
P1.add(f1);
} catch (IOException ex) {
}
}
}
Cant add more details and this is all I can tell Just tell me how to solve this problem as quick as possible.
Remove the line:
P1.add(f1);
This will give you a java.lang.IllegalArgumentException because you are trying to add a window to a container. It should work if you remove that line.
However, your code is totally incorrect. You are adding a JFrame to a JPanel and adding the JPanel to the JButton, it should be the opposite way around.
For example, this will work for you:
public void Menu()
{
Image img = ImageIO.read(getClass().getResource("Image1.jpg"));
JFrame f1=new JFrame("Menu");
f1.setSize(400,200);
JPanel P1=new JPanel();
JButton b1=new JButton("Creamy Chocolate Cup");
b1.setIcon(new ImageIcon(img));
P1.add(b1);
f1.add(P1);
f1.setVisible(true);
}
Related
i have been extensively researching on stackoverflow and other platforms to find out the solution to my problem.I do understand that this is a duplicate question and I totally understand how to convert JPanel to an image based on Java tutorial and other existing post on stackoverflow . However, i'm trying to do it in OOP as i don't want to chunk all my codes within the same method. The result i keep getting is blank and it doesn't show my component in PNG file that ive exported.
File 2, imageOutput.java
public class imageOutput {
public JPanel panel() {
JPanel panel = new JPanel();
JButton btn = new JButton("Click");
JLabel label = new JLabel("Exporting image example");
// -----Add to panel ---
panel.add(label);
panel.add(btn);
panel.setSize(200,200);
btn.addActionListener(new saveImageListener());
return panel;
}
public void frame() {
JFrame frame = new JFrame();
JPanel panel = panel();
// --- Add to frame ---
frame.add(panel);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
class saveImageListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel panel = new imageOutput().panel();
System.out.println("Step 1.. ");
BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
System.out.println("Step 2.. ");
Graphics2D g = image.createGraphics();
panel.printAll(g);
g.dispose();
try {
ImageIO.write(image, "jpg", new File("Paint2.jpg"));
ImageIO.write(image, "png", new File("Paint2.png"));
System.out.println("save");
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
Main class, main.java
public class main{
public static void main(String[] args) {
new imageOutput().frame();
}
}
When i run the program, it results blank as mentioned above. ive been trying to figure out whats the cause of it for the past week and i have not come out with any solution. Has anyone encounter this problem and able to solve ?
BUT when i do it this way , it's perfectly fine. However, it's not oop for me.
public void frame() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("Click");
JLabel label = new JLabel("Exporting image example");
//-----Add to panel ---
panel.add(label);
panel.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
panel.printAll(g);
g.dispose();
try {
ImageIO.write(image, "jpg", new File("Paint2.jpg"));
ImageIO.write(image, "png", new File("Paint2.png"));
System.out.println("save");
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
//--- Add to frame ---
frame.add(panel);
frame.setSize(200, 200);
frame.setVisible(true);
//btn.addActionListener(new saveImageListener());
}
Thank you in advance. :)
The problem is a compounding one.
When you call panel() on an instance of imageOutput, it's create another instance of the JPanel, in of itself, this isn't a bad thing, but you need to remember that this new instance has nothing to do with what's on the screen.
In the example you've provided, this means that no layout pass has been done on the component, so all the components are at there default position/size (which is 0x0x0x0), so nothing gets rendered
If you're going to continue creating a new instance of the panel each time you call panel(), then you're going to have to force a layout pass, maybe something like...
JPanel panel = new imageOutput().panel();
panel.setSize(panel.getPreferredSize());
panel.doLayout();
Now, personally, I'd avoid setSize and passing it "magic" numbers and instead use the components preferredSize, but that's me
I'm currently writing an application using Java Swing. So far, the application is simple, it creates a window (JFrame) that fills the screen. This JFrame has a main JPanel, and in that JPanel is a JLabel for the title and a JLabel that I'm loading a BufferedImage into. When I run the program, the JLabel containing the title shows up, but the JLabel containing the image I'm loading in doesn't appear. However, when I hit the "minimize" button on the window, and then maximize the window again, the image appears as it should. Why isn't the image showing up when the program is opened? My code is shown below:
public class MainWindow extends JFrame {
private static final int DEFAULT_WIDTH = 1400;
private static final int DEFAULT_HEIGHT = 800;
private JPanel mainPanel;
public MainWindow() {
setup();
}
private void setup() {
this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
this.mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(Color.BLUE);
this.add(mainPanel);
setupObjectInsertPanel();
}
private void setupObjectInsertPanel() {
JLabel label = new JLabel("TileSets");
mainPanel.add(label, BorderLayout.NORTH);
try{
BufferedImage tilesetImage = ImageIO.read(new File(...)); // path ommitted
JLabel tilesetIcon = new JLabel(new ImageIcon(tilesetImage));
mainPanel.add(tilesetIcon, BorderLayout.SOUTH);
System.out.println("Loaded tileset into panel");
} catch (IOException e) {
System.out.println("Could not open tileset");
e.printStackTrace();
}
}
}
The try statement always succeeds, and the success message is printed when the program starts up, but the image isn't showing up until the window is minimized/re-maximized. Why is this behavior happening?
I'm using IntelliJ GUIDesigner.
I have JScrollPanel which contains JPanel.
The idea is that I want to add image to JPanel and to have it load at full size so I can use scrollers to move around and see whole image.
And My problem is that it paints itself alright if I won't change the size of JPanel. But the moment I'm chaning JPanel size it just repaints itself to orginal state (I suppose, IntelliJ hides a lot of code from me).
The code is:
private JPanel panel1;
private JButton button1;
private JPanel drawingPanel;
public MainPanel(){
button1.addActionListener(e -> {
JFileChooser openFile = new JFileChooser();
File chosenFile;
if(openFile.showSaveDialog(panel1) == JFileChooser.APPROVE_OPTION){
chosenFile = openFile.getSelectedFile();
drawImage(chosenFile);
}
});
}
private void drawImage(File file){
try {
BufferedImage image = ImageIO.read(file);
//Works OK if line belowed is removed, but doesn't adjust size so I can't scroll.
drawingPanel.setSize(image.getWidth(), image.getHeight());
Graphics g = drawingPanel.getGraphics();
g.drawImage(image, 0, 0, null);
drawingPanel.paintComponents(g);
}
catch (IOException e) {
e.printStackTrace();
}
}
As I wrote in comment, if the line below the comment is removed then I can load the image and it shows OK but it's too big and I can't see whole image.
If I add the line then it just clears everything and I can't see nothing.
This is important - I need to get the image to show in full size.
How do I do it?
I have JScrollPanel which contains JPanel.
Don't do custom painting.
Just create a JLabel and add the label to the viewport of the scroll pane. Then when you want to change the image you use the setIcon(...) method of the JLabel and the label will automatically repaint itself and scrollbars will appear if necessary.
Maybe you can share your IntelliJ GUI forms? Otherwise it's difficult to reproduce the scrolling problem that you're facing. Without the custom painting and using a label as camickr suggested, you can get scrolling working like this:
public class MainPanel {
private static JFrame frame;
private JPanel panel1;
private JButton button1;
private JPanel drawingPanel;
private JLabel drawingLabel;
public static void main(String[] args) {
MainPanel.test();
}
private static void test() {
frame = new JFrame("");
frame.setBounds(100, 100, 640, 480);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
new MainPanel();
frame.setVisible(true);
}
public MainPanel() {
initializeGui();
button1.addActionListener(e -> {
JFileChooser openFile = new JFileChooser("[...]");
File chosenFile;
if (openFile.showSaveDialog(panel1) == JFileChooser.APPROVE_OPTION) {
chosenFile = openFile.getSelectedFile();
System.out.println("chosenFile: " + chosenFile);
drawImage(chosenFile);
}
});
}
private void initializeGui() {
panel1 = new JPanel(new BorderLayout());
frame.getContentPane().add(panel1);
button1 = new JButton("Open image");
panel1.add(button1, BorderLayout.NORTH);
drawingPanel = new JPanel(new BorderLayout());
panel1.add(drawingPanel, BorderLayout.CENTER);
drawingLabel = new JLabel();
drawingPanel.add(new JScrollPane(drawingLabel), BorderLayout.CENTER);
}
private void drawImage(File file){
try {
BufferedImage image = ImageIO.read(file);
//Works OK if line below is removed, but doesn't adjust size so I can't scroll.
// drawingPanel.setSize(image.getWidth(), image.getHeight());
// Graphics g = drawingPanel.getGraphics();
// g.drawImage(image, 0, 0, null);
// drawingPanel.paintComponents(g);
drawingLabel.setIcon(new ImageIcon(image));
drawingPanel.validate();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Not sure how easy it is to do something similar with the IntelliJ GUI designer; I do prefer IntelliJ (over Eclipse and NetBeans) but I also prefer to create my Java GUIs in code... ;-)
i try to make imageviewer, the code is below
import javax.swing.*;
import java.awt.event.*;
import java.IO.*;
public class javaImageViewer extends JFrame{
public javaImageViewer(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(200,100);
JButton openButton = new JButton("Open Images");
getContentPane().add(openButton);
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser(".");
int status = chooser.showOpenDialog(javaImageViewer.this);
if(status == JFileChooser.APPROVE_OPTION){
try{
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(chooser.getSelectedFile().toURL()));
frame.add(label);
frame.setSize(500,500);
frame.setVisible(true);
}
catch(Exception e2){
System.out.println("Error"+e2);
}
}
}
});
}
public static void main(String [] args){
javaImageViewer tim = new javaImageViewer();
tim.setVisible(true);
}
}
but when i open image from camera, it always showing over the frame size
i dont know how to make the image follow my frame size ?
in order to place your image with the Full Size, you can try to make your own JPanel, override the paintComponent method, and inside this method use g.DrawImage ,
other solution and maybe easier is set the JPanel dimesion with the same dimesion of you Image and Add this JPanel to a JScrollPane , in this way is going to show a scrollbars to navigate
depends of reall size in pixels
1) put Image / BufferedImage as Icon/ImageIcon to the JLabel, then image will be resiziable up to real size in pixels
2) resize Image by usage of Image#getScaledInstance(int width, int height, int hints)
I have created one GUI using Swing of Java. I have to now set one sample.jpeg image as a background to the frame on which I have put my components.How to do that ?
There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.
One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.
For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:
public class JPanelWithBackground extends JPanel {
private Image backgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroundImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, this);
}
}
(Above code has not been tested.)
The following code could be used to add the JPanelWithBackground into a JFrame:
JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));
In this example, the ImageIO.read(File) method was used to read in the external JPEG file.
This is easily done by replacing the frame's content pane with a JPanel which draws your image:
try {
final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
setContentPane(new JPanel(new BorderLayout()) {
#Override public void paintComponent(Graphics g) {
g.drawImage(backgroundImage, 0, 0, null);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
This example also sets the panel's layout to BorderLayout to match the default content pane layout.
(If you have any trouble seeing the image, you might need to call setOpaque(false) on some other components so that you can see through to the background.)
The Background Panel entry shows a couple of different ways depending on your requirements.
You can either make a subclass of the component
http://www.jguru.com/faq/view.jsp?EID=9691
Or fiddle with wrappers
http://www.java-tips.org/java-se-tips/javax.swing/wrap-a-swing-jcomponent-in-a-background-image.html
Perhaps the easiest way would be to add an image, scale it, and set it to the JFrame/JPanel (in my case JPanel) but remember to "add" it to the container only after you've added the other children components.
ImageIcon background=new ImageIcon("D:\\FeedbackSystem\\src\\images\\background.jpg");
Image img=background.getImage();
Image temp=img.getScaledInstance(500,600,Image.SCALE_SMOOTH);
background=new ImageIcon(temp);
JLabel back=new JLabel(background);
back.setLayout(null);
back.setBounds(0,0,500,600);
Here is another quick approach without using additional panel.
JFrame f = new JFrame("stackoverflow") {
private Image backgroundImage = ImageIO.read(new File("background.jpg"));
public void paint( Graphics g ) {
super.paint(g);
g.drawImage(backgroundImage, 0, 0, null);
}
};
if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
One way
-----------------*/
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads \\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
setSize(399,399);
setSize(400,400);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}