Errors running Java program - java

Im tying to run my java program using netbeans and im getting this error, any suggestion?
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at MainForm.addComponentsToPane(MainForm.java:28)
at MainForm.createAndShowGUI(MainForm.java:112)
at MainForm.access$000(MainForm.java:15)
at MainForm$4.run(MainForm.java:125)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
this is the code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MainForm {
public static void addComponentsToPane(final JFrame frame, Container pane) {
Color colorGreen = new Color(0, 100, 0);
Color colorBrown = new Color(150, 100, 0);
//Color colorBlue = new Color (0, 0, 150);
//Font font = new Font("Verdana", Font.BOLD, 12);
pane.setLayout(null);
pane.setBackground(new Color (255, 255, 170));
//add image and necessary labels on top left corner
//SHA Image and label
ImageIcon image = new ImageIcon(MainForm.class.getResource("SHA_logo.gif"));
JLabel label = new JLabel("Office of Traffic & Safety", image, JLabel.LEFT);
label.setVerticalTextPosition(JLabel.BOTTOM);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setFont(new Font("Times New Roman", Font.PLAIN, 11));
pane.add(label);
label.setBounds(50, 10, 130, 100);
label.setBorder(null);
//university of maryland image and label\\\
image = new ImageIcon(MainForm.class.getResource("maryland_flag_round.gif"));
label = new JLabel("Univ. of Maryland", image, JLabel.LEFT);
label.setVerticalTextPosition(JLabel.BOTTOM);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setFont(new Font("Times New Roman", Font.PLAIN, 11));
pane.add(label);
label.setBounds(190, 10, 130, 90);
label.setBorder(null);
//critical lane label
label = new JLabel("Critical Lane Volume");
label.setFont(new Font("Arial Narrow", Font.BOLD, 30));
label.setForeground(colorGreen);
pane.add(label);
label.setBounds(50, 90, 250, 50);
label.setBorder(null);
label = new JLabel("<html>Please choose the analysis type:</html>");
label.setFont(new Font("Arial", Font.BOLD, 18));
label.setForeground(colorBrown);
pane.add(label);
label.setBounds(25, 130, 300, 70);
label.setBorder(null);
//back and exit buttons
JButton button1 = new JButton("Interchange");
JButton button2 = new JButton ("Intersection");
JButton button3 = new JButton ("Exit");
pane.add(button1);
pane.add(button2);
pane.add(button3);
button1.setBounds(75, 200, 200, 50);
button2.setBounds(75, 270, 200, 50);
button3.setBounds(75, 340, 200, 50);
//add attap label at bottom left
image = new ImageIcon(MainForm.class.getResource("attap_logo.gif"));
label = new JLabel(image);
pane.add(label);
label.setBounds(30, 380, 270, 90);
label.setBorder(null);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
frame.dispose();
InterchangeLoad.main(null);
}
});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
frame.dispose();
MultipleIntersectionLoad.main(null);
}
});
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
frame.dispose();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Critical Lane Volume");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame, frame.getContentPane());
frame.setSize(350, 500);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

It looks like one (or more) of the arguments you are passing into your ImageIcon constructor are null.
EDIT
The exception is occurring at one of these two lines:
ImageIcon image = new ImageIcon(MainForm.class.getResource("SHA_logo.gif"));
or
image = new ImageIcon(MainForm.class.getResource("maryland_flag_round.gif"));
In either case, the problem is the same: the resource is not being found, and so null is being returned by getResource(). Why aren't you just using new ImageIcon(String filename)? I'm not even 100% sure what getResource() is doing.
A few other quick comments (suggestions) on your code:
pane.setLayout(null); is not a good idea, I'm not even sure you can just get rid of the LayoutManager like that.
Reusing the same reference (image and label) multiple times for different objects is bad coding style. You're not saving any memory by doing that, and the code makes less sense.
Use more descriptive names! button1 should probably be called 'interchangeButton' or something along those lines. For such a small segment of code, no one will get lost, but if you ever work on a larger project, a good naming scheme is vital.

Related

How do I properly display radio buttons on the screen along with other elements? (images attached) - Java GUI using NetBeans

I am trying to create a pizza ordering system where the user is presented with two choices for pizza sauces (tomato and barbeque). I have already created the GUI and have already coded the design for the radio buttons, but I am not sure how to display the radio buttons on screen along with other elements. I have tried placing it within the paint code and the main aswell, but it changes the colour of the GUI.
I have attached two images. First one is the GUI which is meant to have the radio buttons placed underneath the text (pizza, base&sauce, topping).
Second one is the GUI I get when I add in radio button code.
//Code
package pizzaorder2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/**
*
* #author sm
*/
public class PizzaOrder2 extends JFrame {
static JFrame frame;
static String[] pizza = {"Supremo Supreme", "Supreme", "Chicken",
"Aussie",
"Vegie", "Hawaiian"};
static String[] base = {"Thin and Crispy", "Pan", "Cheese filled
crust"};
static String[] topping = {"None", "Pepperoni", "Salami", "Ham",
"Bacon", "Chicken", "Onion"};
static String tomatoString = "Tomato";
static String barbequeString = "Barbeque";
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 55));
g.drawString("Pizza Order", 175, 70);
Image imagepizza = new ImageIcon("/Users/supriyamayuri/NetBeansProjects/DrawGraphics/src/piz.jpg").getImage();
g.drawImage(imagepizza, 20, 90, 140, 120, this);
Image imagesauce = new ImageIcon("/Users/supriyamayuri/NetBeansProjects/DrawGraphics/src/sauce.jpg").getImage();
g.drawImage(imagesauce, 220, 90, 150, 120, this);
Image imagetopping = new ImageIcon("/Users/supriyamayuri/NetBeansProjects/DrawGraphics/src/top.jpg").getImage();
g.drawImage(imagetopping, 430, 90, 140, 120, this);
g.setColor(Color.WHITE);
g.setFont(new Font("Helvetica", Font.BOLD, 25));
g.drawString("Pizza", 40, 240);
g.setColor(Color.WHITE);
g.setFont(new Font("Helvetica", Font.BOLD, 25));
g.drawString("Base & Sauce", 210, 240);
g.setColor(Color.WHITE);
g.setFont(new Font("Helvetica", Font.BOLD, 25));
g.drawString("Topping", 450, 240);
}
public PizzaOrder2() {
//Create the radio buttons.
JRadioButton tomatoButton = new JRadioButton(tomatoString);
tomatoButton.setMnemonic(KeyEvent.VK_B);
tomatoButton.setActionCommand(tomatoString);
JRadioButton barbequeButton = new JRadioButton(barbequeString);
barbequeButton.setMnemonic(KeyEvent.VK_C);
barbequeButton.setActionCommand(barbequeString);
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(tomatoButton);
group.add(barbequeButton);
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel();
radioPanel.add(tomatoButton);
radioPanel.add(barbequeButton);
add(radioPanel);
}
public static void main(String[] args) {
JFrame frame = new PizzaOrder2();
frame.setSize(600, 600);
frame.getContentPane().setBackground(new Color(40, 80, 120));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Exit a JPanel or a GlassPane when we click outside it

Days ago i asked for help to put a JPanel on top of the other CardLayout panels, with the help of one of the users i achieved it using GlassPane, so thanks to him, but now i wanna close it whenever i click outside it(in other windows of the applications or components) because its stuck there until i click settings button, how can i achieve that? I have tried with focus lost and gained but that doesn't work with the panel so what am i supposed to do, here is my piece of code..
JPanel settingsPanel = new JPanel();
settingsPanel.setLayout(null);
settingsPanel.setPreferredSize(
new Dimension(180, 260));
JLabel lblSettingsTitle = new JLabel("Settings");
lblSettingsTitle.setFont(new Font("SansSerif", Font.BOLD |
Font.ITALIC, 18));
lblSettingsTitle.setBounds(5, 8, 200, 35);
settingsPanel.add(lblSettingsTitle);
JSeparator settingsSep = new JSeparator();
settingsSep.setForeground(Color.DARK_GRAY);
settingsSep.setBounds(0, 48, 160, 2);
settingsPanel.add(settingsSep);
JPanel panelLanguage = new JPanel();
panelLanguage.setBounds(0, 61, 200, 30);
settingsPanel.add(panelLanguage);
panelLanguage.setLayout(null);
JPanel pnlLanguage = new JPanel();
pnlLanguage.setBounds(0, 0, 200, 30);
panelLanguage.add(pnlLanguage);
pnlLanguage.setLayout(null);
JLabel lblLanguageIcon = new JLabel("");
lblLanguageIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/Language_20px.png")));
lblLanguageIcon.setBounds(5, 5, 20, 20);
pnlLanguage.add(lblLanguageIcon);
JLabel lblLanguage = new JLabel("Choose Language");
lblLanguage.setFont(new Font("SansSerif", Font.ITALIC, 15));
lblLanguage.setBounds(30, 0, 170, 30);
pnlLanguage.add(lblLanguage);
JPanel pnlAlbanian = new JPanel();
pnlAlbanian.setBounds(0, 30, 200, 30);
panelLanguage.add(pnlAlbanian);
pnlAlbanian.setLayout(null);
JLabel lblAlbIcon = new JLabel("");
lblAlbIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/albanian.png")));
lblAlbIcon.setBounds(20, 0, 30, 30);
pnlAlbanian.add(lblAlbIcon);
JLabel lblAlbanian = new JLabel("Albanian");
lblAlbanian.setBounds(50, 0, 150, 30);
pnlAlbanian.add(lblAlbanian);
JPanel pnlEnglish = new JPanel();
pnlEnglish.setBounds(0, 60, 200, 30);
panelLanguage.add(pnlEnglish);
pnlEnglish.setLayout(null);
JLabel lblEngIcon = new JLabel("");
lblEngIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/britain.png")));
lblEngIcon.setBounds(20, 0, 30, 30);
pnlEnglish.add(lblEngIcon);
JLabel lblEnglish = new JLabel("English");
lblEnglish.setBounds(50, 0, 150, 30);
pnlEnglish.add(lblEnglish);
JPanel pnlAboutUs = new JPanel();
pnlAboutUs.setBounds(0, 120, 200, 30);
settingsPanel.add(pnlAboutUs);
pnlAboutUs.setLayout(null);
JLabel lblAboutIcon = new JLabel("");
lblAboutIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/About_20px.png")));
lblAboutIcon.setBounds(5, 5, 20, 20);
pnlAboutUs.add(lblAboutIcon);
JLabel lblAboutUs = new JLabel("About Us");
lblAboutUs.setFont(new Font("SansSerif", Font.ITALIC, 15));
lblAboutUs.setBounds(35, 0, 165, 30);
pnlAboutUs.add(lblAboutUs);
JPanel pnlHelp = new JPanel();
pnlHelp.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Help obj=new Help();
getGlassPane().setVisible(false);
obj.setVisible(true);
obj.setLocationRelativeTo(null);
}
});
pnlHelp.setLayout(null);
pnlHelp.setBounds(0, 91, 200, 30);
settingsPanel.add(pnlHelp);
JLabel lblHelpIcon = new JLabel("");
lblHelpIcon.setIcon(new
ImageIcon(frmMain.class.getResource("/image/Help_20px.png")));
lblHelpIcon.setBounds(5, 5, 20, 20);
pnlHelp.add(lblHelpIcon);
JLabel lblHelp = new JLabel("Help");
lblHelp.setFont(new Font("SansSerif", Font.ITALIC, 15));
lblHelp.setBounds(35, 0, 165, 30);
pnlHelp.add(lblHelp);
((JComponent) getGlassPane()).setLayout(new
FlowLayout(FlowLayout.LEFT, 260, 390));
((JComponent) getGlassPane()).add(settingsPanel, BorderLayout.EAST);
JLabel lblSettings = new JLabel("");
lblSettings.setHorizontalAlignment(SwingConstants.CENTER);
lblSettings.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
getGlassPane().setVisible(!getGlassPane().isVisible());
}
});
lblSettings.setToolTipText("Settings");
lblSettings.setIcon(new
ImageIcon(frmMain.class.getResource("/image/Settings_24px.png")));
lblSettings.setBounds(210, 600, 50, 50);
menuPanel.add(lblSettings);
I've slightly modified my previous example, so the settings panel goes closed on the click outside it.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class RightSidePanel implements Runnable {
#Override
public void run() {
JFrame frm = new JFrame("Right side panel");
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// next two lines are not required
JPanel contentPanel = new JPanel(new BorderLayout());
frm.setContentPane(contentPanel);
JPanel mainPanel = new JPanel(new CardLayout());
mainPanel.add(new JLabel("It's the first card panel"), "first");
mainPanel.add(new JLabel("It's the second card panel"), "second");
// add some components to provide some width and height for the panel.
mainPanel.add(Box.createHorizontalStrut(600));
mainPanel.add(Box.createVerticalStrut(300));
mainPanel.setBackground(Color.CYAN);
JPanel settingsPanel = new JPanel(new GridLayout(1, 1));
settingsPanel.add(new JLabel("Here is the settings panel!"));
settingsPanel.setPreferredSize(new Dimension(settingsPanel.getPreferredSize().width, 300));
JButton settingsButton = new JButton("Show settings"); // move this line up
((JComponent) frm.getGlassPane()).setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0));
((JComponent) frm.getGlassPane()).add(settingsPanel);
// added code here
frm.getGlassPane().addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
// check whether the click on the glass pane.
Component c = SwingUtilities.getDeepestComponentAt(frm.getGlassPane(), e.getX(), e.getY());
if (e.getComponent().equals(c)) {
updateButton(frm, settingsButton);
}
}
});
// end of the added code
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
settingsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// move the method content to a separate method
updateButton(frm, settingsButton);
}
});
JButton switchButton = new JButton("Show second");
switchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) mainPanel.getLayout();
if (mainPanel.getComponent(0).isVisible()) {
cl.show(mainPanel, "second");
switchButton.setText("Show first");
} else {
cl.show(mainPanel, "first");
switchButton.setText("Show second");
}
}
});
buttonPanel.add(switchButton);
buttonPanel.add(settingsButton);
frm.add(mainPanel, BorderLayout.CENTER);
frm.add(buttonPanel, BorderLayout.SOUTH);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private void updateButton(JFrame frm, JButton settingsButton) {
frm.getGlassPane().setVisible(!frm.getGlassPane().isVisible());
if (frm.getGlassPane().isVisible()) {
settingsButton.setText("Hide settings");
} else {
settingsButton.setText("Show settings");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new RightSidePanel());
}
}

text in textfield is displayed but wont change font when choosing in combobox

This code is about user inserting text in text field and transfer the text to label then user can choose font style in JComboBox where the text being displayed will changed font if the user choose font.
package hw;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class HW {
public static void main(String[] args) {
/*from this code is adding the frame, label, textfield, panels, panel background color and the location of the labels and textfields*/
String [] cb = {"Comic Sans MS", "Times New Roman", "Arial Black"};
JFrame frames = new JFrame();
frames.setVisible(true);
frames.setSize(700, 500);
frames.setResizable(false);
frames.setLocation(170, 100);
JPanel panels = new JPanel();
frames.add(panels);
panels.setBackground(new Color(40, 136, 168));
panels.setLayout(null);
JTextField tf1 = new JTextField();
panels.add(tf1);
tf1.setBounds(90, 150, 100, 25);
JLabel label1 = new JLabel("ENTER TEXT");
panels.add(label1);
label1.setBounds(100, 30, 150, 100);
JLabel label2 = new JLabel("FONT STYLE");
panels.add(label2);
label2.setBounds(400, 30, 150, 100);
JComboBox combo = new JComboBox(cb);
panels.add(combo);
combo.setBounds(400, 150, 150, 25);
JLabel label3 = new JLabel("");
panels.add(label3);
label3.setBounds(310, 250, 150, 100);
label3.setText("");
/* this part below is the itemlistener and itemevent, i dont know the if this part below is correct because the font in the inserted text wont change but the text being insert in textfield is showing up in the jlabel*/
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event){
String word;
if (event.getStateChange()==ItemEvent.SELECTED){
label3.setText(word=tf1.getText());
label3.setFont(new Font("Comic Sans MS", Font.PLAIN, 14));
}
else if (event.getStateChange()==ItemEvent.SELECTED) {
label3.setText(word=tf1.getText());
label3.setFont(new Font("Times New Roman", Font.PLAIN, 14));
}
else if (event.getStateChange()==ItemEvent.SELECTED) {
label3.setText(word=tf1.getText());
label3.setFont(new Font("Arial Black", Font.PLAIN, 14));
}
/* the else and else if statement is not working, i dont know how to correct this problem*/
}
}
});
}
}
I have trouble correcting this problem, I dont know where is the main source of the problem why fonts wont change if they being choose in JComboBox.
This fixes the multiple logic problems in the itemStateChanged method (and works for each of the fonts). I would typically use an ActionListener for combo boxes, but YMMV.
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
String fontName = combo.getSelectedItem().toString();
if (event.getStateChange() == ItemEvent.SELECTED) {
label3.setText(tf1.getText());
label3.setFont(new Font(fontName, Font.PLAIN, 14));
}
}
});

How do I remove a component from a JPanel? and then redisplay the frame?

Some context for this code,
what I am trying to do is create a validation warning if the input containts "" as a value,
so if an error is displayed it displays the message.
If it is valid it does not display a message,
so how do I remove the message when the textField is valid?
The message is a JPanel that contains a JLabel with the text in it,
I add this this JPanel to the frame when it is not valid,
and I am trying to remove it when it is valid.
So what am I doing wrong here?
I am at a basic level with Swing.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 401, 232);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 330, 94);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Firstname :");
lblNewLabel.setBounds(10, 11, 104, 14);
panel.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(76, 8, 244, 20);
panel.add(textField);
textField.setColumns(10);
JLabel lblLastname = new JLabel("Lastname :");
lblLastname.setBounds(10, 42, 78, 14);
panel.add(lblLastname);
textField_1 = new JTextField();
textField_1.setBounds(76, 39, 244, 20);
panel.add(textField_1);
textField_1.setColumns(10);
JButton btnValidate = new JButton("Validate");
btnValidate.addMouseListener(new MouseAdapter() {
#SuppressWarnings("deprecation")
#Override
public void mousePressed(MouseEvent arg0) {
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
if(textField.getText().equals("")) {
panel_1.setBackground(new Color(30, 144, 255));
panel_1.setBounds(100, 116, 330, 26);
JLabel lblMessage = new JLabel("0 :");
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_1.add(lblMessage);
frame.getContentPane().add(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
else if(textField_1.getText().equals("")) {
panel_2.setBackground(new Color(50, 200, 255));
panel_2.setBounds(10, 134, 330, 26);
JLabel lblMessage = new JLabel("1 :");
lblMessage.setBounds(50, 50, 50, 50);
lblMessage.setAlignmentX(50);
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_2.add(lblMessage);
frame.getContentPane().add(panel_2);
frame.remove(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
}
});
btnValidate.setBounds(231, 71, 89, 23);
panel.add(btnValidate);
}
}
The easiest way is to simply adjust the visibility (JComponent#setVisible( false ) ).
If you really want to remove the component completely, you have to remove and revalidate, as documented in the Container#remove method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.
which results in code like
panel.remove( componentToRemove );
panel.revalidate();
panel.repaint();
As a side note: please replace the null layout and those setBounds call by a proper LayoutManager. You might want to take a look excellent 'Nested layout example' available on SO to see what is possible with layout managers. The Swing tag info on SO contains some extra useful links when starting to work with layout managers
yourpanel.setVisible(false); should hide your panel, where "yourPanel" is your JPanel instance

create a java program using eclipse, cant run it using netbeans [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Errors running Java program
I am currently writing a java program using eclipse. I heard that it is easier to make java gui using netbeans so I want to try to finish this java program using netbeans. However, when i open my project using netbeans and run it, it give me an error. Im tying to use betbeans run the same program that run fine under eclipse.
this is the error:
run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at MainForm.addComponentsToPane(MainForm.java:28)
at MainForm.createAndShowGUI(MainForm.java:112)
at MainForm.access$000(MainForm.java:15)
at MainForm$4.run(MainForm.java:125)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 8 seconds)
this is the codes im tying to run:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MainForm {
public static void addComponentsToPane(final JFrame frame, Container pane) {
Color colorGreen = new Color(0, 100, 0);
Color colorBrown = new Color(150, 100, 0);
//Color colorBlue = new Color (0, 0, 150);
//Font font = new Font("Verdana", Font.BOLD, 12);
pane.setLayout(null);
pane.setBackground(new Color (255, 255, 170));
//add image and necessary labels on top left corner
//SHA Image and label
ImageIcon image = new ImageIcon(MainForm.class.getResource("SHA_logo.gif"));
JLabel label = new JLabel("Office of Traffic & Safety", image, JLabel.LEFT);
label.setVerticalTextPosition(JLabel.BOTTOM);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setFont(new Font("Times New Roman", Font.PLAIN, 11));
pane.add(label);
label.setBounds(50, 10, 130, 100);
label.setBorder(null);
//university of maryland image and label\\\
image = new ImageIcon(MainForm.class.getResource("maryland_flag_round.gif"));
label = new JLabel("Univ. of Maryland", image, JLabel.LEFT);
label.setVerticalTextPosition(JLabel.BOTTOM);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setFont(new Font("Times New Roman", Font.PLAIN, 11));
pane.add(label);
label.setBounds(190, 10, 130, 90);
label.setBorder(null);
//critical lane label
label = new JLabel("Critical Lane Volume");
label.setFont(new Font("Arial Narrow", Font.BOLD, 30));
label.setForeground(colorGreen);
pane.add(label);
label.setBounds(50, 90, 250, 50);
label.setBorder(null);
label = new JLabel("<html>Please choose the analysis type:</html>");
label.setFont(new Font("Arial", Font.BOLD, 18));
label.setForeground(colorBrown);
pane.add(label);
label.setBounds(25, 130, 300, 70);
label.setBorder(null);
//back and exit buttons
JButton button1 = new JButton("DIAT");
JButton button2 = new JButton ("Intersection");
JButton button3 = new JButton ("Exit");
pane.add(button1);
pane.add(button2);
pane.add(button3);
button1.setBounds(75, 200, 200, 50);
button2.setBounds(75, 270, 200, 50);
button3.setBounds(75, 340, 200, 50);
//add attap label at bottom left
image = new ImageIcon(MainForm.class.getResource("attap_logo.gif"));
label = new JLabel(image);
pane.add(label);
label.setBounds(30, 380, 270, 90);
label.setBorder(null);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
frame.dispose();
InterchangeLoad.main(null);
}
});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
frame.dispose();
MultipleIntersectionLoad.main(null);
}
});
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
frame.dispose();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Critical Lane Volume");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame, frame.getContentPane());
frame.setSize(350, 500);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
It's not finding your images. Are you sure that you have your images in the same relative position? Are they in the same location as the MainForm.class file? Also I would take exception to the comment that it is easier to create a GUI with NetBeans than Eclipse. I've used both and find both fine to use, but I recommend you avoid using any code generation software until you know Swing well. For instance, you would do well to learn how to use the Swing/AWT layout managers and avoiding using null layout/setBounds.
Your program can't find the file "SHA_logo.gif", so your new ImageIcon(...) is new ImageIcon(null) and that is causing the NullPointerException.

Categories

Resources