This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to add some images to those labels,but Eclipse throw me java.lang.NullPointerException and I don't know why?! Please help :}
public class LabelPanel extends JPanel {
public JLabel[] bills;
public LabelPanel() {
setLayout(new FlowLayout());
init();
labelOrder();
}
private void init() {
bills = new JLabel[4];
for (int i = 0; i < bills.length; i++){
bills[0].setIcon(newImageIcon("C:\\users\\Acer\\Documents\\images\\1.jpg"));
bills[1].setIcon(new ImageIcon("C:\\Users\\Acer\\Documents\\images\\2.jpg"));
bills[2].setIcon(new ImageIcon("C:\\Users\\Acer\\Documents\\images\\5.jpg"));
bills[3].setIcon(new ImageIcon("C:\\Users\\Acer\\Documents\\images\\10.jpg"));
bills[4].setIcon(new ImageIcon("C:\\Users\\Acer\\Documents\\images\\20.jpg"));
}
}
private void labelOrder() {
add(bills[0]);
add(bills[1]);
add(bills[2]);
add(bills[3]);
add(bills[4]);
}
}
Try following code
Sample Code
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.FlowLayout;
public class SwingExampleDemo {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
ImageIcon imageIcon = new ImageIcon("C:\\users\\Acer\\Documents\\images\\1.jpg"); //here image path
JLabel jLabel = new JLabel(imageIcon);
f.add(jLabel);
f.setLayout(new FlowLayout());//using layout managers
f.setVisible(true);//making the frame visible
f.pack();
}
}
Hope It will help you...
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Loading ImageIcon from JAR or file system
(1 answer)
Closed 6 years ago.
So while making the following program I am getting the errors as mentioned below:
I don't know why the IDE is not able to find my images
and the images are in the same folder as the .java files.
I am using eclipse neon
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at gui_22.gui.<init>(gui.java:24)
at gui_22.MAIN.main(MAIN.java:6)
The code is as follows:
Main Class
import javax.swing.JFrame;
public class MAIN(){
public static void main(String[] args);
gui go = new gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}
}
Gui Class
import java.awt.FlowLayout;
import.java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class gui extends JFrame{
private JButton reg;// to create buttons
private JButton custom;// Same as above
public gui(){
super("The Title"); //Allows access to the superclass.
setLayout(new FlowLayout());
reg = new JButton("reg Button");
add(reg);
Icon b = new ImageIcon(getClass().getResource("b.png"));
Icon x = new ImageIcon(getClass().getResource("a.png"));
custom = new JButton("Custom",b);
custom.setRolloverIcon(x);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);//adding a handler for the button
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null,String.format("%s", event.getActionCommand()));
}
}
}
I am doing a slot machine for a project. I am having trouble getting my JButton to generate new random numbers from my ArrayList. I can randomize the numbers when the program starts and have an actionlistener set up, but it doesn't do what I need. It was merely for testing purposes.
My Actionlistener is in a different Java file. Everything works, I just can't figure out how to generate new randoms in the placeholder of plc1, plc2, and plc3 when the button is clicked.
I have just recently began to really code as about 3 weeks ago.
No haters please, this is my first project ever.
package GGCGuiLotto;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Image;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.util.Random;
public class GGCGuiLotto {
public static void main(String[] args) {
//Arraylist of images
ImageIcon pic0 = new ImageIcon("pics/pic1.png");
ImageIcon pic1 = new ImageIcon("pics/pic2.png");
ImageIcon pic2 = new ImageIcon("pics/pic3.png");
ImageIcon pic3 = new ImageIcon("pics/pic4.png");
ImageIcon pic4 = new ImageIcon("pics/pic5.png");
ImageIcon pic5 = new ImageIcon("pics/pic6.png");
ImageIcon pic6 = new ImageIcon("pics/pic7.png");
final ArrayList<ImageIcon> slotlist = new ArrayList<ImageIcon>();
slotlist.add(pic0);
slotlist.add(pic1);
slotlist.add(pic2);
slotlist.add(pic3);
slotlist.add(pic4);
slotlist.add(pic5);
slotlist.add(pic6);
Random ran = new Random();
int plc1 = ran.nextInt(4);
int plc2 = ran.nextInt(4);
int plc3 = ran.nextInt(4);
//generates the frame and the labels are added.
JFrame frame = new JFrame();
frame.setSize (400,275);
frame.setTitle("GGC Lotto Slots Rcorbin");
frame.setResizable(false);
frame.setVisible(true);
JPanel pnlReels = new JPanel();
frame.add(pnlReels);
JPanel aReel1 = new JPanel();
aReel1.setBackground(new Color(25,25,112));
aReel1.setBounds(15,10,100,100);
JPanel bReel2 = new JPanel();
bReel2.setBackground(new Color(25,25,112));
bReel2.setBounds(145,10,100,100);
JPanel cReel3 = new JPanel();
cReel3.setBackground(new Color(25,25,112));
cReel3.setBounds(275,10,100,100);
pnlReels.add(aReel1);
pnlReels.add(bReel2);
pnlReels.add(cReel3);
JLabel aReel1lbl = new JLabel();
JLabel bReel2lbl = new JLabel();
JLabel cReel3lbl = new JLabel();
aReel1.add(aReel1lbl);
bReel2.add(bReel2lbl);
cReel3.add(cReel3lbl);
aReel1lbl.setIcon(slotlist.get(plc1));
bReel2lbl.setIcon(slotlist.get(plc2));
cReel3lbl.setIcon(slotlist.get(plc3));
//jbutton
JButton slotbtn1 = new JButton();
slotbtn1.setText("GGC LOTTO Click ME");
pnlReels.add(slotbtn1);
slotbtn1.setBounds(145,50,100,75);
//FirstGuiListener act = new FirstGuiListener();
//slotbtn1.addActionListener((ActionListener) act);
GenPLCListener genPLC = new GenPLCListener();
slotbtn1.addActionListener((genPLC));
{}
if (plc1 == plc2 && plc1 == plc3 && plc2 == plc3)
{
JOptionPane.showConfirmDialog(null,"Winner! Play Again? ","GGC Lotto Slots RCorbin ",JOptionPane.YES_NO_OPTION);
//System.out.println("Winner");
}
else
{
//JOptionPane.showMessageDialog(null,"No Winner Winner Chicken Dinner ! ");
System.out.println("Crazy"); }
}
}
package GGCGuiLotto;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JOptionPane;
class GenPLCListener extends GGCGuiLotto implements ActionListener{
public void actionPerformed(ActionEvent event){
System.out.println("Works");
JOptionPane.showConfirmDialog(null,"Choose Wisely. ","Click If you Trust!",JOptionPane.YES_NO_OPTION);
}
}
Trying to extends GGCGuiLotto isn't going to do what you think it's supposed to, which is give you access to the same instance variables. So get rid of that. Instead you can pass-by-reference, the current instance of GGCGuiLotto to your listener. And have some getters and setters to access the variables you need from the GGCGuiLotto class. What I mean is maybe something like this (not completely sure what you're trying to accomplish, so this is just an example).
public class GenPLCListener implements ActionListener {
private GGCGuiLotto lotto;
public GenPLCListener(GGCGuiLotto lotto) {
this.lotto = lotto;
}
#Override
public void actionPerfomred(ActionEvent e) {
List<ImageIcon> slotList = lotto.getSlotList();
Collections.shuffle(slotList); // shuffle the list
// do something else if need be.
}
}
When you create the listener, pass this to it. this being the instance of GGCGuiLotto
Few Side Notes
Swing programs aren't like console programs. You don't want to do everything inside your main method. For starters, the code in your main method, you could put in the constructor instead. Then create an instance of GGCGuiLotto in the main method.
Swing apps should be run on the Event Dispatch Thread. See Initial Threads
EDIT
Maybe a more proper solution to your problem would be to have an interface with the pullSlot method that you can override in the GGCGuiLotto class and just pass the interface to the listener and call the pullSlot method inf your actionPerformed. Something like this
public interface PullInterface {
public void pullSlot();
}
public class GGCGuiLotto implements PullInterface {
ArrayList<ImageIcon> slotList = new ArrayList<>(); // global scope.
JLabel aReel1lbl = new JLabel();
JLabel bReel2lbl = new JLabel();
JLabel cReel3lbl = new JLabel();
Random rand = new Random();
public GGCGuiLotto() {
GenPLCListener listener = new GenPLCListener(this);
}
#Override
public void pullSlot() {
// do what you need to do here to implement a pulling of the lever
int r1 = rand.nextInt(slotList.size());
int r2 = rand.nextInt(slotList.size());
int r3 = rand.nextInt(slotList.size());
reel1lbl.setIcon(slotList.get(r1));
}
}
public class GenPLCListener implement ActionListener {
private PullInterface pull;
public GenPLCListener(PullInterface pull) {
this.pull = pull;
}
#Override
public void actionPerformed(ActionEvent e) {
pull.pullSlot();
}
}
I come to you because I have a strange issue, for which I don't find any solution...
I build an application using a webcam, in order to take some photographs.
I use WebcamCapture to do that, and I don't encounter any issues with it.
The only "weird" thing that happens is the following :
I use a JDialog in which I make photograph. In its JFrame parent, I display those photographs in JLabel.
Then, i need to disable those JLabel, and I do that by calling a method which disable all components. The weird thing is, when I disable JLabel, the JLabel display the last image capture by the webcam. Not the last photographs, but really the last captured image.
It's seems that BufferedImage (used by WebcamPanel) are linked to the issue.
Here is the SSCE :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
#SuppressWarnings("serial")
public class CameraFrame extends JFrame implements ActionListener{
public Webcam webcam;
Boolean enabled = true;
CameraFrame frame;
private JButton btnSaveVerso;
private JLabel lblVerso;
private JButton btnEnable;
private JButton btnQuit;
private JPanel mainPanel;
private WebcamPanel streamPanel;
public static void main(String[] args){
CameraFrame frame = new CameraFrame();
frame.setVisible(true);
}
public CameraFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setMinimumSize(new Dimension(800, 600));
setPreferredSize(new Dimension(800,600));
buildPanel();
setContentPane(mainPanel);
}
});
}
public void buildPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
Border blackline = BorderFactory.createLineBorder(Color.black, 1, true);
webcam = Webcam.getDefault();
webcam.open();
streamPanel = new WebcamPanel(webcam);
streamPanel.setPreferredSize(new Dimension(webcam.getViewSize()));
streamPanel.setMaximumSize(new Dimension(webcam.getViewSize()));
btnSaveVerso = new JButton("Take pic");
btnSaveVerso.setActionCommand("take");
btnSaveVerso.addActionListener(this);
lblVerso = new JLabel("Here will be the pic taken by the camera");
lblVerso.setBorder(blackline);
btnEnable = new JButton("Disable");
btnEnable.setActionCommand("disable");
btnEnable.addActionListener(this);
btnQuit = new JButton("Quit");
btnQuit.setActionCommand("quit");
btnQuit.addActionListener(this);
mainPanel.add(streamPanel);
mainPanel.add(btnSaveVerso);
mainPanel.add(lblVerso);
mainPanel.add(btnEnable);
mainPanel.add(btnQuit);
}
#Override
public void actionPerformed(final ActionEvent e) {
Thread newThread = new Thread(){
public void run(){
if(e.getActionCommand().equals("take")){
ImageIcon icon = new ImageIcon(webcam.getImage().getScaledInstance(100, 150, Image.SCALE_SMOOTH ));
lblVerso.setIcon(new ImageIcon(icon.getImage()));
lblVerso.revalidate();
lblVerso.repaint();
}
else if(e.getActionCommand().equals("disable")){
if(enabled){
lblVerso.setEnabled(false);
enabled = false;
btnEnable.setText("Enable");
}
else{
lblVerso.setEnabled(true);
enabled = true;
btnEnable.setText("Disable");
}
}
}
};
newThread.run();
if(e.getActionCommand().equals("quit")){
webcam.close();
this.setVisible(false);
}
}
}
I hope you will compile it without issues. Don't forget to link the librairies.
Thanks in advance
I finally resolved the problem : you simply need to close the webcam after each pictures, as follows :
BufferedImage picture = webcam.getImage();
webcam.close();
webcam.open();
... Do what you need with picture
(You don't even need to convert BufferedImage picture in an other type.)
I am working on a desktop application for windows version using java. In my application there is a requirement to display IMAGES from Path with a next and previous button.
For that I wrote a class to return all the paths of the images : I use ArrayList
import java.io.File;
import java.util.ArrayList;
public class RE {
private ArrayList<String> c =new ArrayList<String>();
public RE (String rep)
{
File src=new File(rep);
if(src!=null && src.exists() && src.isDirectory())
{
String[] tab=src.list();
if(tab!=null)
{
for(String s:tab)
{
File srcc=new File(rep+File.separatorChar+s);
if(srcc.isFile())
{
if(srcc.getName().matches(".*"+"png$")|| srcc.getName().matches(".*"+"jpg$") || srcc.getName().matches(".*"+"gif$"))
c.add(srcc.getPath());
}
}
}
}
}
public ArrayList<String> getAll()
{
return c;
}
}
and a class to display images, but I have some problems in ActionPerformed
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ListIterator;
import javax.swing.*;
public class swing extends JFrame implements ActionListener{
private RE c=new RE("H:\\photos\\g");
JTextField chemin=new JTextField(30);
JLabel lab;ImageIcon imageIcon;
JButton next =new JButton("NEXT");
JButton prev=new JButton("prev");
JPanel pan1=new JPanel();
JPanel pan2=new JPanel();
JPanel pan3=new JPanel();
swing()
{
imageIcon = new ImageIcon(c.getAll().get(2));
lab = new JLabel(imageIcon);
this.setLayout(new BorderLayout());
this.setVisible(true);
pan1.setLayout(new FlowLayout());
pan1.add(new JLabel("ENTREZ LE CHEMIN DE REPERTOIRE :"));
pan1.add(chemin);
pan2.setLayout(new FlowLayout());
pan2.add(lab);
pan3.setLayout(new FlowLayout());
next.addActionListener(this);
prev.addActionListener(this);
pan3.add(prev); pan3.add(next);
this.add(pan1,BorderLayout.NORTH);
this.add(pan2,BorderLayout.CENTER);
this.add(pan3,BorderLayout.SOUTH);
this.pack();
}
public static void main(String[] args){
new swing();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==next)
{
String cur=imageIcon.toString();
ListIterator<String> l=c.getAll().listIterator(c.getAll().indexOf(cur));
lab.setIcon(new ImageIcon(l.previous().toString()));
}
else
{
}
}
}
but I can't complete that :
public void actionPerformed(ActionEvent e) {
if(e.getSource()==next)
{
String cur=imageIcon.toString();
ListIterator<String> l=c.getAll().listIterator(c.getAll().indexOf(cur));
lab.setIcon(new ImageIcon(l.previous().toString()));
}
else
{
}
}
Use an appropriate layout manager. In this case, use CardLayout. This will make image swapping easier. Unless the number of images is absurdly large, then I highly recommend this approach.
Use your List<String> to construct a corresponding List<ImageIcon> and replace the label's icon as required. In this example, a JComboBox holds the current selection, and the buttons change the selection accordingly. Note that the indexes wrap around, forming a circular queue.
I have JScrollPane with JTextArea inside it and I am trying to set the JTextArea's orientation from right to left so the text inside it will start from the right and the scrollbar will be on the left
I've tried the following but they didn't affect the direction of the orientation:
txt.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
txt.setAlignmentX(JTextArea.RIGHT_ALIGNMENT);
EDIT:
the two answers camickr & trashgod provided work fine but not in my program where I use my JTextArea as an object Message and pass it to OptionPane.
EDIT2:
I figured out that setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); doesn't work if I apply it on the JOptionPane contents .. is there an alternative solution to this issue?
Similar to my code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TextArea extends JPanel
{
private JTextArea txt = new JTextArea();
public TextArea()
{
setLayout(new GridLayout());
txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JScrollPane scroll = new JScrollPane(txt);
scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setPreferredSize(new Dimension(200,200));
this.add(scroll);
}
private void display()
{
Object[] options = {this};
JOptionPane pane = new JOptionPane();
int option = pane.showOptionDialog(null, null, "Title", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
public static void main(String[] args)
{
new TextArea().display();
}
}
and the scrollbar will be on the left
scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
so the text inside it will start from the right
textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
The text starts on the right side, but still gets append to the end as you type instead of being inserted at the beginning of the line.
Update:
I don't know why it doesn't work in an option pane. Here is a simple solution:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class Test
{
public static void main(String args[]) throws Exception
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextArea textArea = new JTextArea(4, 20);
JScrollPane scrollPane = new JScrollPane( textArea );
JPanel panel = new JPanel();
panel.add( scrollPane );
scrollPane.addAncestorListener( new AncestorListener()
{
public void ancestorAdded(AncestorEvent e)
{
JScrollPane scrollPane = (JScrollPane)e.getComponent();
scrollPane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
public void ancestorMoved(AncestorEvent e) {}
public void ancestorRemoved(AncestorEvent e) {}
});
JOptionPane.showMessageDialog(null, panel);
}
});
}
}
This seems to work.
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/** #see http://stackoverflow.com/questions/6475320 */
public class RTLTextArea extends JPanel {
private static final String s = "مرحبا العالم";
private JTextArea jta = new JTextArea(7, 5);
private Locale arabic = new Locale("ar", "KW");
private ComponentOrientation arabicOrientation =
ComponentOrientation.getOrientation(arabic);
public RTLTextArea() {
this.setLayout(new GridLayout());
this.add(new JScrollPane(jta));
this.applyComponentOrientation(arabicOrientation);
for (int i = 0; i < 8; i++) {
jta.append(s + "\n");
}
}
private void display() {
JFrame f = new JFrame("RTLTextAre");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new RTLTextArea().display();
}
});
}
}
this line
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT)
change the correct order of the words.
i have this result
KBytes 80.78
The following lines solved my problem:
jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
jTextArea1.setText(<text>);
They serve to:
setComponentOrientation() changes the orientation of the TextArea; and,
setText() refreshes TextArea immediately so it displays properly
Simply setting ComponentOrientation to RIGHT_TO_LEFT is not sufficient by itself. repaint() doesn't force the text to realign itself. A quick solution for me was to update the contents of the TextArea. That forced the text to realign itself.