I am going through thenewboston's tutorials and I have an unexpected error. I have tried to do everything that Eclipse suggest, but can't figure it out where the problem is.
this is my Main Class
import javax.swing.JFrame;
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);
}
}
and this is 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;
private JButton custom;
public Gui(){
super("The title");
setLayout(new FlowLayout());
reg = new JButton("Regular Button");
add(reg);
Icon b = new ImageIcon(getClass().getResource("b.png"));
Icon a = new ImageIcon(getClass().getResource("a.png"));
custom = new JButton("Custom", b);
custom.setRolloverIcon(a);
add(custom);
HandlerClass handler = new HandlerClass();
reg.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
}
Thanks brothers for helping me out!
You've posted a couple of different stacktraces with the error on different line numbers but the code seems to have moved around. The error itself is talking about a NullPointerException in a constructor for ImageIcon. Not really anything to do with the JButton so the tags are misleading.
Basically you're looking up an image location of b.png and a.png. If these two files don't exist then you'll get a runtime exception like you have. The quick fix is to add these two images to the project so they are found.
A more robust solution would be to handle the exception and either output a more meaningful error or just carry on without the icon on the gui.
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 trying to create an application with several tabbed panes, and to keep the code manageable, I wanted to have the content for these panes in separate classes, in separate .java files.
I have 3 files currently
(i) TestLayout.java
package testlayout;
public class TestLayout
{
public static void main(String[] args)
{
MainFrame mainFrameObject = new MainFrame();
mainFrameObject.displayMainFrame();
}
}
(ii) MainFrame.java
package testlayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
public class MainFrame
{
JFrame masterFrame = new JFrame("JAVA 1.1");
JTabbedPane tabbedPane = new JTabbedPane();
public void displayMainFrame()
{
masterFrame.setSize(1000, 600);
masterFrame.setVisible(true);
masterFrame.setResizable(false);
masterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
masterFrame.add(tabbedPane);
DisplayReadMe drmObj = new DisplayReadMe();
drmObj.showReadMe();
//showReadMe();
}
/*
public void showReadMe()
{
JPanel panelReadMe = new JPanel(new GridLayout(10,1,8,8));
panelReadMe.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
tabbedPane.addTab("Read Me", null, panelReadMe, "First Tab");
String testreadMeTestMessage = "This is a test message";
JLabel testreadMeLabel = new JLabel(testreadMeTestMessage, SwingConstants.LEFT);
testreadMeLabel.setBorder(BorderFactory.createLineBorder(Color.orange,3));
panelReadMe.add(testreadMeLabel);
}
*/
}
and
(iii) DisplayReadMe.java
package testlayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class DisplayReadMe extends MainFrame
{
public DisplayReadMe()
{
}
public void showReadMe()
{
System.out.println("method showReadMe begins");
JPanel panelReadMe = new JPanel(new GridLayout(10,1,8,8));
panelReadMe.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
tabbedPane.addTab("Read Me", null, panelReadMe, "First Tab");
String testreadMeTestMessage = "This is a test message";
JLabel testreadMeLabel = new JLabel(testreadMeTestMessage, SwingConstants.LEFT);
testreadMeLabel.setBorder(BorderFactory.createLineBorder(Color.orange,3));
panelReadMe.add(testreadMeLabel);
System.out.println("method showReadMe ends");
}
}
My query is, when I uncomment the //showReadMe(); and showReadMe method in MainFrame, it works. The tab is added to the JFrame and the test message shows in the box.
But should the
DisplayReadMe drmObj = new DisplayReadMe();
drmObj.showReadMe();
code, not do the same thing? Am I not calling the showReadMe method from the DisplayReadMe class, akin to showReadMe().
I have tried revalidate, repaint and threading and nothing seems to call the method and show the tab and message ?
Any guidance would be gratefully appreciated
Many Thanks
PG
The method is actually working, but the tabbedPane instance in drmObj is different with respect to the JTabbedPane class member in MainFrame. Try to add tabbedPane as a parameter in showReadMe() and refer to that instance whenever adding elements. It should work.
public void showReadMe(JTabbedPane tabbedPane);
...
drmObj.showReadMe(this.tabbedPane);
Hope it helps!
you may not have duplicated method with same parameters, check if you have another showReadMe method who expects nothing as parameter.
if you make an overwrite of the showReadMe, remember that it will make showReadMe of the main class, then will make showReadMe inherited since it cannot go more up.
i donno if i explained it well at all.
I'm kind of a beginner and I was using a tutorial to make a simple program that displays text fields on a JFrame. I didn't use a JLayeredPane in the whole project, but I still get this error that says, "The type javax.swing.JLayeredPane cannot be resolved. It is indirectly referenced from required .class files." Why do I get this error?
Here's the code (there's two classes):
second class:
package eventHandlerTutorial;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
public class secondClass extends JFrame
{
private JTextField item1;
private JTextField item2;
private JTextField item3;
private JPasswordField passwordField;
public secondClass()
{
super("The title");
setLayout(new FlowLayout());
item1=new JTextField(10);
add(item1);
item2=new JTextField("enter text here");
add(item2);
item3=new JTextField("uneditable",20);
item3.setEditable(false);
add(item3);
passwordField=new JPasswordField("mypass");
add(passwordField);
theHandler handler=new theHandler();
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
passwordField.addActionListener(handler);
}
private class theHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String string="";
if(event.getSource()==item1)
string=String.format("field 1: %s",event.getActionCommand());
else if(event.getSource()==item2)
string=String.format("field 2: %s",event.getActionCommand());
else if (event.getSource()==item3)
string=String.format("field 3: %s",event.getActionCommand());
else if(event.getSource()==passwordField)
string=String.format("password field is: %s",event.getActionCommand());
JOptionPane.showMessageDialog(null,string);
}
}
}
main class:
package eventHandlerTutorial;
import javax.swing.JFrame;
public class mainClass
{
public static void main(String[] args)
{
secondClass sc=new secondClass();
sc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sc.setSize(350,100);
sc.setVisible(true);
}
}
The error is explained:
"... cannot be resolved. It is indirectly referenced from required .class files.".
Another thing is, in your question you are saying "JOptionPane"
and
in explanation you are saying "JLayeredPane".
Sometimes (because of IDE errors) you are suppose to import manually.
Add
import javax.swing.JLayeredPane;
manually.
and check it out.
if, still you face issue,
try to clean the project.
I've been trying to make it so my button will close out of the frame on click but it never does anything. I've looked through several stackoverflow threads but none of them seems to work on my this.. here is what I have so far
JButton start = new JButton("Start");
start.setBounds(251, 216, 119, 23);
start.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt) {
try {
int hpToEat = Integer.parseInt(GUI.textField.getText());
Frost.hp = hpToEat;
} catch(NumberFormatException nfe) {
GUI.textField.setText("");
}
setVisible(false);
}
});
contentPane.add(start);
I have tried making a closeFrame method which uses super.dispose(); and I've also tried system.exit(0);
Does anyone have any idea as to why My button won't do What i want it to do?
Someone requested the rest of my code so here it is:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JTextField;
import javax.swing.JButton;
public class GUI extends JFrame{
private JPanel contentPane;
public static JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI() {
//LABELS ===================================================================================================
The problem is that GUI.textfield is not what you think it is. You're shadowing the field here:
JTextField textField = new JTextField();
That creates a local variable by the name textField, it does not set the static field you're using in the action listener. A quick fix would be writing just:
textField = new JTextField();
However, I recommend getting out of the habit of using static fields. That approach does not scale. Furthermore, don't use absolute positioning. It leads to no end of trouble (just browse a few questions in the swing tag for examples). Learn to use layout managers right from the start.
Why is it that my code is not showing the image that I inserted? there's no compilation error or Syntax error but why is it like that?
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
public class FirstUI extends JFrame{
private JLabel firstlabel;
private JLabel secondLabel;
private JLabel pie;
public FirstUI(){
super("Tittle");
setLayout(new FlowLayout());
firstlabel = new JLabel("Hello World");
firstlabel.setToolTipText("Hello World");
String path = "pie.png";
Icon pie = new ImageIcon(path);
secondLabel = new JLabel("Text with icon",pie,SwingConstants.LEFT);
add(secondLabel);
add(firstlabel);
}
}
main class
import javax.swing.JFrame;
public class FirstUiTest {
public static void main(String[] args){
FirstUI MyUI = new FirstUI();
MyUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyUI.setSize(320,280);
MyUI.setVisible(true);
}
}
if the "pie.png" is in the same Path of FirstUI.class try to use:
Icon pie = new ImageIcon(ImageIO.read( FirstUI.class.getResourceAsStream( "pie.png" ) ) );
I tried this exact code, and it worked. It looks like pie.png cannot be found. If you're using eclipse, put it in the project root (The same folder that has /bin and /src). Otherwise, put it in the same directory where you run the java command from.