JPanel paintComponent() won't draw in JFrame - java

Here I have a JPanel object which handles my 2048 game, but when I try to add it to a JFrame, the paintComponent() doesn't do anything.
I know it's not the implementation of paintComponent() as I've tried drawing very simple things (shown below) and I know the JPanel is working (because it prints out "test").
import javax.swing.JFrame;
public class GameEngine
{
public static void main(String[] args)
{
JFrame frame = new JFrame("2048");
frame.setSize(700, 700);
frame.setLocation(100, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new newGamePanel());
frame.setVisible(true);
}
}
/******Different File******/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class newGamePanel extends JPanel{
Color[] colorOfTiles = new Color[8];
Color gridColor = new Color(187, 173, 160);
Color backTileColor = new Color(204, 192, 180);
Color twoFourText = new Color(238, 228, 218);
Color notTwoFourText = new Color(255,255,255);
int[][] tiles;
public newGamePanel(){
System.out.println("test");
colorOfTiles[1] = new Color(238, 228, 218);colorOfTiles[2] = new
Color(236, 224, 200);
colorOfTiles[3] = new Color(242, 177, 121);colorOfTiles[4] = new
Color(246, 141, 83);
colorOfTiles[5] = new Color(245, 124, 95);colorOfTiles[6] = new
Color(233, 89, 55);
colorOfTiles[7] = new Color(241, 208, 75);
setLayout(new BorderLayout());
setPreferredSize(new Dimension(700, 700));
setFont(new Font("Arial", Font.BOLD, 48));
setFocusable(true);
JPanel subpanel = new JPanel();
subpanel.setLayout(new GridLayout(4,4));
add(subpanel, BorderLayout.CENTER);
tiles = new int[4][4];
}
public void paintComponent(Graphics g){
g.setColor(Color.black);
g.fillRect(0, 0, 100 ,100);
}
//The rest of the methods are commented out
}
I expect a black, filled rectangle to be drawn, but nothing appears on the JFrame.

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());
}
}

Objects disappear on resize and when the window is minimized

i need some help with this code.
I already have the functions of paint the objects and clear the objects from the window but how i can make that when i make a resize or when i minimize the windows the objects doesn't disappear?
This is the code i have at the moment:
public class miClass implements ActionListener{
JFrame ventana;
JPanel panel;
JButton p,c;
Graphics g;
Image img;
Font font1,font2,font3;
public miClass(){
ventana = new JFrame("Aplicacion.");
p = new JButton("P");
c = new JButton("C");
panel = new JPanel();
ventana.setLayout(null);
ventana.setBounds(100,100,600,600);
ventana.getContentPane().add(panel);
ventana.add(p);
p.addActionListener(this);
c.addActionListener(this);
p.setBounds(20,20,120,45);
ventana.add(c);
c.setBounds(200,20,120,45);
ventana.setFocusable(true);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
g = ventana.getGraphics();
Toolkit tool = Toolkit.getDefaultToolkit();
img = tool.getImage("prueba.png");
g.drawImage(img,0,100,null);
font1 = new Font("Helvetica",Font.PLAIN,22);
g.setFont(font1);
g.drawString("Hola", 100, 300);
font2 = new Font("TimesRoman",Font.BOLD,20);
g.setFont(font2);
g.drawString("Mundo", 100, 340);
font3 = new Font("Courier",Font.BOLD+Font.ITALIC,25);
g.setFont(font3);
g.drawString("WASAAAA!", 100, 400);
g.setColor(Color.green);
g.drawOval(300, 200, 150, 100);
g.setColor(Color.red);
g.drawArc(200, 400, 250, 64, 135, 46);
g.setColor(Color.blue);
g.drawLine(400, 200, 150, 100);
g.setColor(Color.magenta);
g.drawRect(300, 250, 160, 50);
g.setColor(Color.cyan);
g.fillRect(100,400,20,240);
g.setColor(Color.lightGray);
g.fillOval(100,340,14,30);
if(e.getSource() == c){ //Clean all objects on the window//
g.clearRect(0,100,900,800);
}
}
public static void main(String args[]){
miClass GUI = new miClass();
}
}
Your frame is reset to its initial state when it is resized, and your code only redraws it when a button is clicked, not when it is resized. The paintComponent method on any subclass of Component is called after the parent frame is resized, so you can fix this issue by overriding that method.
package SO;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class miClass implements ActionListener {
JFrame ventana;
JPanel panel;
JButton p, c;
Graphics g;
Image img;
Font font1, font2, font3;
public miClass() {
ventana = new JFrame("Aplicacion.");
p = new JButton("P");
c = new JButton("C");
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
// your stuff
font1 = new Font("Helvetica", Font.PLAIN, 22);
g.setFont(font1);
g.drawString("THIS GETS REDRAWN", 100, 300);
}
};
panel.setSize(400, 400);
ventana.setLayout(null);
ventana.setBounds(100, 100, 600, 600);
ventana.getContentPane().add(panel);
ventana.add(p);
p.addActionListener(this);
c.addActionListener(this);
p.setBounds(20, 20, 120, 45);
ventana.add(c);
c.setBounds(200, 20, 120, 45);
ventana.setFocusable(true);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
g = panel.getGraphics();
Toolkit tool = Toolkit.getDefaultToolkit();
img = tool.getImage("prueba.png");
g.drawImage(img, 0, 100, null);
font1 = new Font("Helvetica", Font.PLAIN, 22);
g.setFont(font1);
g.drawString("Hola", 100, 300);
font2 = new Font("TimesRoman", Font.BOLD, 20);
g.setFont(font2);
g.drawString("Mundo", 100, 340);
font3 = new Font("Courier", Font.BOLD + Font.ITALIC, 25);
g.setFont(font3);
g.drawString("WASAAAA!", 100, 400);
g.setColor(Color.green);
g.drawOval(300, 200, 150, 100);
g.setColor(Color.red);
g.drawArc(200, 400, 250, 64, 135, 46);
g.setColor(Color.blue);
g.drawLine(400, 200, 150, 100);
g.setColor(Color.magenta);
g.drawRect(300, 250, 160, 50);
g.setColor(Color.cyan);
g.fillRect(100, 400, 20, 240);
g.setColor(Color.lightGray);
g.fillOval(100, 340, 14, 30);
if (e.getSource() == c) { // Clean all objects on the window//
g.clearRect(0, 100, 900, 800);
}
}
public static void main(String args[]) {
miClass GUI = new miClass();
}
}

JButton on JFrame with Graphics [duplicate]

This question already has answers here:
Components in second JFrame not showing up
(2 answers)
Closed 7 years ago.
I'm trying to make a JFrame that will have graphics and 5 JButtons (which correspond with graphics on screen).
Yesterday my code ran, but now it is glitching and the graphics and buttons only appear when I am resizing the JFrame (pulling it with the cursor!). This is for a game I am making for a class project. If know what the problem may be/is, please tell me. I've been staring at this for so long and I think someone with fresh eyes or more skill than myself could see why the code is wrong. >.<
It has 2 classes, one for graphics and one with a main.
The class for the graphics:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Polygon;
public class drawingComponentMap extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
drawingComponentMap DCM = new drawingComponentMap(); // this is used in
// the class
// below
Color door = new Color(255, 218, 185); // the graphics are making a
// house, hence the colours
Color glass = new Color(173, 216, 230);
Color mapGrass = new Color(144, 238, 144);
g.setColor(mapGrass);
g2.fillRect(0, 0, 500, 500);
// circles to correspond with buttons (as in each button reps a circle)
Color minigame = new Color(221, 160, 221);
g.setColor(minigame);
g2.fillOval(10, 20, 50, 50);
g2.fillOval(220, 70, 50, 50);
g2.fillOval(20, 200, 50, 50);
g2.fillOval(100, 300, 50, 50);
g2.fillOval(200, 200, 50, 50);
Color black = new Color(0, 0, 0);
g.setColor(black);
g2.drawOval(10, 20, 50, 50);
g2.drawOval(220, 70, 50, 50);
g2.drawOval(20, 200, 50, 50);
g2.drawOval(100, 300, 50, 50);
g2.drawOval(200, 200, 50, 50);
// the house graphic
Color walls = new Color(210, 105, 3);
g.setColor(walls);
g2.fillRect(300, 300, 150, 200);
Color roof = new Color(165, 42, 42);
g.setColor(roof);
g2.drawRect(300, 300, 150, 200);
int[] xPoints = { 300, 375, 450 };
int[] yPoints = { 300, 225, 300 };
Polygon imageTriangle = new Polygon(xPoints, yPoints, 3);
g2.fillPolygon(imageTriangle);
g.setColor(black);
g2.drawPolygon(imageTriangle);
g.setColor(glass);
g2.fillRect(380, 350, 50, 50);
g.setColor(door);
g2.fillRect(325, 450, 30, 50);
g.setColor(black);
g2.drawRect(325, 450, 30, 50);
g2.fillOval(330, 470, 5, 5);
g2.drawRect(380, 350, 50, 50);
g2.drawString("Where do you want to go?", 10, 400);
}
}
this is the class which uses the graphics, and where the jframe, jlabel, and jbuttons are made.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Map {
JFrame window = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton();
public static void main(String[] args) {
JFrame window = new JFrame();
JPanel panel = new JPanel();
window.setSize(500, 500);
window.setTitle("Map");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JButton button1 = new JButton("World 1");
JButton button2 = new JButton("World 2");
JButton button3 = new JButton("World 3");
JButton button4 = new JButton("World 4");
JButton button5 = new JButton("World 5");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
window.add(panel);
panel.setVisible(true);
drawingComponentMap DCM = new drawingComponentMap();
window.add(DCM);
}
}
Sorry about the formatting of the code/text portion of this question. I'm in class right now.
It's just a single statement issue - window.setVisible(true).
Move your window.setVisible(true) statement to the end. Your main method contents should now look like this (just for your reference):
JFrame window = new JFrame();
JPanel panel = new JPanel();
window.setSize(500, 500);
window.setTitle("Map");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("World 1");
JButton button2 = new JButton("World 2");
JButton button3 = new JButton("World 3");
JButton button4 = new JButton("World 4");
JButton button5 = new JButton("World 5");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
window.add(panel);
panel.setVisible(true);
drawingComponentMap DCM = new drawingComponentMap();
window.add(DCM);
window.setVisible(true);

Errors running Java program

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.

Categories

Resources