Adding an image in ActionListener [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a JButton that displays an image in the JPanel when pressed - allowing the user to choose the location in the panel. I am using the following methods to paint:
public void paint(Graphics g, URL path) {
Image img = getImage(path);
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(img, getX(),getY(),50,50, null);
}
public Image getImage(URL path) {
Image temp = null;
try
{
temp = Toolkit.getDefaultToolkit().getImage(path);
} catch (Exception e) {
e.printStackTrace();
}
return temp;
}
When I call paint(), I get a null pointer exception in my last line of my ActionListener:
dogButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Graphics g = null;
Animal animal = new Animal();
animal.paint(g, main.class.getResource("/Animals/dog.jpg"));
}
I'm a little confused overall about how to use ActionListeners. This is my first project so I apologize for my lack of knowledge.

You have set
Graphics g = null;
Initialize g with something other than null.
I would recommend overriding public void paintComponent(Graphics g) of the JPanel where you plan to paint and use this graphics.

Related

how to override paintComponent method and use with JPanel [duplicate]

This question already has an answer here:
How to draw the radius of a circle without it being shorter or larger than the circumference
(1 answer)
Closed 5 years ago.
I have override paintComponents method, but when I am using it and run my program then it does not show any circle and lines. Recently frakcool said it is not paintComponents method, it is paintComponent method. I found out but I didn't get any paintComponent method.
This picture shows that i have not got any paintComponent method:
Codes are here.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SecondActivity frame = new SecondActivity();
frame.setBackground(Color.WHITE);
frame.paintComponents(null);
// frame.paint(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void paintComponents(Graphics g) {
// TODO Auto-generated method stub
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
drawCircle(g2d,centerX,centerY,r);
drawLineAzim(g2d);
drawLineEle(g2d);
}
You are overriding the wrong method. Get rid of the "s" at the end of the method name. You need to override paintComponent(...).
But, you also need to override the paintComponent(...) method of a JPanel, You can't just add the method to your class and expect it to work. This is Java 101.
Start with the working examples found in the Swing tutorial on Custom Painting

I'm trying to make a smiley face GUI keeps giving me a Null Pointer Exception (NPE) on my JButtons [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I need to set up a standard smiley face GUI where you can wink, blink, smile, and frown with JButtons. I need to do this with three separate classes: a class that draws the smiley face, a class with all my buttons and actionListeners that control the smiley face, and a class with the applet.
I keep getting NPE's on my buttons in the button class. I can't figure out why. Please go easy on me, I'm new to Java.
Here's my controls class:
public class SmileyControls extends JPanel implements ActionListener {
Smiley smiley;
JPanel controlPanel, eyePanel;
JButton open, wink, shut; // make these an animation???? see loop chapter in text
public SmileyControls(Smiley smileControl) {
smiley = smileControl;
controlLayout();
}
public void controlLayout() {
eyePanel = new JPanel(new FlowLayout());
open = new JButton("Open");
wink = new JButton("Wink");
shut = new JButton("Shut");
open.addActionListener(this);
wink.addActionListener(this);
shut.addActionListener(this);
eyePanel.add(open);
eyePanel.add(wink);
eyePanel.add(shut);
add(eyePanel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
smiley.setEyeCondition(0); // this calls the method setEyeCondition() from the smiley class that I created. I'm getting my NPE's here
}
if(e.getSource()==wink){
smiley.setEyeCondition(1); // and here
}
if(e.getSource()==shut){
smiley.setEyeCondition(2); // and here
}
}
}
Here's my smiley class:
public class Smiley extends JPanel {
int locX, locY, height, width;
Color moleColor;
int eyeCondition;
Graphics2D g2d;
public Smiley(int x, int y, int w, int h) {
locX = x;
locY = y + 100; // needed to add 100 pixels to make room for hair
height = h;
width = w;
moleColor = new Color(84,60,37);
eyeCondition = 0;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g2d= (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
setHair();
setFace();
setEyes(); // these methods paint the face
setMole();
setMouth();
}
// CONTROL METHODS
public void setEyeCondition(int eye) {
// the int values here are taken from the smileyControls class
// I think they'd repaint my applet if it weren't for the NPE's
if(eye == 0) {
// draw eyes open
g2d.fillOval(locX+width/5, locY+height/5,width/5, height/5); // left eye
g2d.fillOval(locX+3*width/5, locY+height/5, width/5, height/5); // right eye
repaint();
} else if(eye == 1) {
// draw wink
g2d.fillRect(locX+width/5, locY+height/5,width/2, height/20); // left eye winking
g2d.fillOval(locX+3*width/5, locY+height/5, width/5, height/5); // right eye open
repaint();
} else if(eye == 2) {
// draw blink
g2d.fillRect(locX+width/5, locY+height/5,width/2, height/20); // left eye blinking
g2d.fillRect(locX+3*width/5, locY+height/5,width/2, height/20); // right eye blinking
repaint();
}
}
public void setEyes() { // this method paints the original eyes
g2d.setColor(Color.black);
g2d.fillOval(locX+width/5, locY+height/5,width/5, height/5); // left eye
g2d.fillOval(locX+3*width/5, locY+height/5, width/5, height/5); // right eye
}
}
And here's my applet:
public class SmileyApplet extends JApplet {
Smiley smiley1;
SmileyControls control1;
JPanel container, smileyAndControls1, smileyAndControls2, smileyAndControls3;
BorderLayout border;
public void init() {
border = new BorderLayout();
setLayout(border);
setUpContainer();
}
public void setUpContainer() {
container = new JPanel(new FlowLayout());
smileyAndControls1 = new JPanel(new FlowLayout());
setUpControl();
setUpSmiley();
smiley1.setPreferredSize(new Dimension(450, 600));
smileyAndControls1.add(control1);
smileyAndControls1.add(smiley1);
container.add(smileyAndControls1); // add more controls to master container here
add(container, BorderLayout.CENTER);
}
public void setUpSmiley() {
smiley1 = new Smiley(0, 0, 400, 400);
add(smiley1);
}
public void setUpControl() {
control1 = new SmileyControls(smiley1);
}
}
At first you call setUpControl(), in there you create your SmileyControls and pass smiley1 to it (which is null at that time).
After that you call setUpSmiley() which creates the instance of Smiley.
So you probably only have to call setUpSmiley() before you call setUpControl() and your problem should be solved.
Try changing the order of these lines, as you use your smiley1 variable before it gets its value:
setUpControl(); // This uses smiley1
setUpSmiley(); // This instantiates smiley1
EDIT
You should move the drawing to the paint*() methods, or methods called directly from them.
That is, your setEyeCondition() method should set a property on the smiley, and the drawing should go into your setEyes()method.

backgroundImage is null instead of Image [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm relatively new to Java programming and here is some code where it should draw a background Image:
public class Board extends JPanel{
private static final long serialVersionUID = 4759318639631503071L;
public String room = "menu";
public Image backgroundImage;
public Image getBackgroundImage() throws IOException{
if (room == "menu") {
backgroundImage = ImageIO.read(new File("assets/background_title.png"));
}
return backgroundImage;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, this);
}
}
I used System.out.println and realized that backgroundImage was null, what have I done wrong here?
You have used == to compare strings
Use if (room.equals("menu"))
instead of
if (room == "menu")
In Java you should compare String objects using equals() method, since == operator checks whether two references point to exactly the same object.
So:
if(room.equals("menu")) { ... }

Adding a Print Button to JPanel [duplicate]

This question already has answers here:
How can I print a single JPanel's contents?
(3 answers)
Closed 9 years ago.
I have a JPanel, with some components like buttons, labels, table, etc.
What I want to do is to add a functionality (a jButton), that clicking on that button directs me to print the whole panel, along with labels and components.
Please help.
Just make a JButton that calls this code:
public void printComponent() {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
pj.setPrintable (new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum) {
if (pageNum > 0) return Printable.NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
componenet_name.paint(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false) return;
try {
pj.print();
} catch (PrinterException ex) {
// handle exception
}
}
(taken from: How can I print a single JPanel's contents?)

Display image on applet

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

Categories

Resources