This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
When I run my simple Java browser, I try and visit a webpage such as http://google.com and it returns the NullPointerException error from my try catch code, how would I fix this?
Frame Class:
public class Frame extends JFrame {
public EditorPane pane;
public URLBar urlbar;
public static void main(String[] args) throws Exception {
Frame frame = new Frame();
}
public Frame() throws Exception {
super("Java Browser v1.0");
JPanel mainPanel = new JPanel(new BorderLayout());
URLBar addressBar = new URLBar("Enter URL here!", pane);
EditorPane contentDisplay = new EditorPane(urlbar);
mainPanel.add(contentDisplay, BorderLayout.CENTER);
mainPanel.add(addressBar, BorderLayout.NORTH);
add(mainPanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(700, 400);
add(new JScrollPane(mainPanel));
setVisible(true);
}
}
URLBar Class:
public class URLBar extends JTextField {
public EditorPane pane;
public URLBar(String text, EditorPane pane) {
super(text);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadContent(event.getActionCommand());
}
}
);
}
public void loadContent(String userInput) {
try
{
pane.setPage(userInput);
setText(userInput);
}
catch (Exception e)
{
System.out.println("A wild exception appeared! Type: " + e);
}
}
}
EditorPane Class:
public class EditorPane extends JEditorPane {
public URLBar urlbar;
public EditorPane(URLBar urlbar) {
setEditable(false);
setVisible(true);
addHyperlinkListener(
new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent event) {
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED) {
urlbar.loadContent(event.getURL().toString());
}
}
}
);
}
}
It looks like you forgot to init the pane member in your URLBar constructor, which means it is null when you call loadContent.
Here's a fix:
public URLBar(String text, EditorPane pane) {
super(text);
this.pane = pane; // add this
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadContent(event.getActionCommand());
}
}
);
}
Related
I'm trying to close a JPanel that's on top of my JFrame.
Now I want to close this panel by clicking a button that's on top of this panel and open another panel on the same frame.
All my panels and my frame is in a separated class.
Here is my idea:
JFrame Class
public MainFrame() throws IOException {
InitializeStartScreen();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLocationRelativeTo(null);
this.setIconImage(FrameTopIcon.getImage());
this.setTitle("test");
this.setVisible(true);
}
private void InitializeStartScreen() {
StartPanel startPNL = new StartPanel();
this.add(startPNL);
// pack();
}
public static void main(String args[]) throws IOException {
try {
new MainFrame();
}
catch (IOException e) {
throw e;
}
}
JPanel Class
import javax.swing.*;
import java.awt.*;
public class StartPanel extends JPanel {
private LabelButtonCategory Button1 = new LabelButtonCategory("test");
public StartPanel() {
this.setLayout(new GridBagLayout());
InitializeLabelButtons();
this.setBackground(backgroundColor);
this.add(gridPanel);
this.setVisible(true);
}
private void InitializeLabelButtons() {
button1Panel.setBackground(backgroundColor);
ImageIcon iconBtn1 = new ImageIcon("./src/images/CreateBill.png");
Button1.setIcon(iconBtn1);
Button1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
Button1MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
Button1MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
Button1MouseExited(evt);
}
});
button1Panel.add(Button1);
gridPanel.add(button1Panel);
private void Button1MouseClicked(java.awt.event.MouseEvent evt) {
// CLOSE THIS PANEL AND OPEN ANOTHER PANEL ON FRAME
}
I'm getting an AWT-EventQueue-0 Null Pointer Exception in the below code and I can't get to fix it.
I want to have a main frame, from which by pressing a button
I open a second frame, where I have the option to create new players,
which would show up in the main frame.
I passed the references to the constructors, but I still keep getting the error.
I would be very happy for some help, thanks!
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new App();
}
});
}
}
public class App extends JFrame {
private MainPanel mainPanel;
private SecondPanel secondPanel;
public App() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
secondPanel = new SecondPanel(mainPanel);
mainPanel = new MainPanel(secondPanel);
add(mainPanel);
}
}
public class MainPanel extends JPanel {
private JTextArea textArea;
private JScrollPane scrollPane;
private JButton options;
public MainPanel(SecondPanel secondPanel) {
textArea = new JTextArea();
textArea.setColumns(20);
textArea.setRows(5);
textArea.setSize(300, 300);
textArea.setVisible(true);
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
scrollPane.setSize(new Dimension(400, 400));
options = new JButton("Options");
options.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
secondPanel.setVisible(true);
}
});
add(scrollPane);
add(options);
}
public JTextArea getTextArea() {
return textArea;
}
public void setTextArea(JTextArea textArea) {
this.textArea = textArea;
}
}
public class SecondPanel extends JFrame {
private JButton create, remove;
private JPanel panel;
public SecondPanel(MainPanel mainPanel) {
setVisible(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
panel = new JPanel();
panel.setLayout(new BorderLayout());
create = new JButton("create");
create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mainPanel.getTextArea().append("New Player Created");
}
});
remove = new JButton("remove");
remove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mp.getTextArea().setText("Player removed");
}
});
add(panel);
panel.add(create, BorderLayout.EAST);
panel.add(remove, BorderLayout.WEST);
}
}
Well, it has to be "null", because you don't initialise your MainPanel before you hand it over to the secondPanel.
Instead, make an own method for setting the MainPanel on the secondPanel and to set the secondPanel on the MainPanel.
I see that you need the secondPanel for instance in your constructor to set an ActionListener. Do that in your "setSecondPanel(SecondPanel sPanel)"-Method which, as I mentioned before, you should create.
I want to have a menu bar in my GUI. The menu is not visible.
public class GUI extends JPanel implements ItemListener{
final static String RUN_TEST = "Test 4G";
final static String SETTINGS = "Settings";
JPanel p;
JPanel cards = new JPanel(new CardLayout());
public GUI(){
JFrame window = new JFrame();
TestRun runTest = new TestRun();
cards.add(runTest , RUN_TEST);
cards.add(runTest , SETTINGS);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, RUN_TEST);
window.setContentPane(cards);
window.pack();
window.setVisible(true);
}
#Override
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
}
How can I show to the user the menu "Test 4G" and "settings" so that they can change the JPanel?
Thanks for your help
This is an example of using JMenuBar in JFrame and JPopupMenu in JPanel (view).
public class MainFrame extends JFrame {
final static String RUN_TEST = "Test 4G";
final static String SETTINGS = "Settings";
private JPanel viewPanel = new JPanel();
public MainFrame() throws HeadlessException {
super("MainFrame");
cretaeGUI();
}
private void cretaeGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setJMenuBar(cretaeMenuBar());
setMinimumSize(new Dimension(800, 600));
viewPanel.setLayout(new CardLayout());
viewPanel.add(new Test4GView(this), RUN_TEST);
viewPanel.add(new SettingsView(this), SETTINGS);
add(viewPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JMenuBar cretaeMenuBar() {
JMenuItem testMenuItem = new JMenuItem("Test 4G");
testMenuItem.addActionListener(this::showTest4GView);
JMenuItem settingsMenuItem = new JMenuItem("Settings");
settingsMenuItem.addActionListener(this::showSettingsView);
JMenu viewMenu = new JMenu("View");
viewMenu.add(testMenuItem);
viewMenu.add(settingsMenuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(viewMenu);
return menuBar;
}
private void showView(String name) {
((CardLayout)viewPanel.getLayout()).show(viewPanel, name);
}
public void showTest4GView(ActionEvent event) {
showView(RUN_TEST);
}
public void showSettingsView(ActionEvent event) {
showView(SETTINGS);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}
аnd these are both views
public class Test4GView extends JPanel {
private MainFrame mainFrame;
public Test4GView(MainFrame mainFrame) {
this.mainFrame = mainFrame;
add(new JLabel("Test 4G"));
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
#Override
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
private void showPopupMenu(MouseEvent e) {
if(!e.isPopupTrigger()) {
return;
}
JMenuItem showSettingsView = new JMenuItem("Settings");
showSettingsView.addActionListener(mainFrame::showSettingsView);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(showSettingsView);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
public class SettingsView extends JPanel {
private MainFrame mainFrame;
public SettingsView(MainFrame mainFrame) {
this.mainFrame = mainFrame;
add(new JLabel("Settings"));
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
#Override
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
private void showPopupMenu(MouseEvent e) {
if(!e.isPopupTrigger()) {
return;
}
JMenuItem showSettingsView = new JMenuItem("Test 4G");
showSettingsView.addActionListener(mainFrame::showTest4GView);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(showSettingsView);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
I'm using webcam-capture libraries and AWT to develop a simple interface for taking pictures from a webcam. The buttons and the combobox in my JFrame disappear after minimizing the window or after moving another window on top of it. Moving the pointer over the frame restores the components' visibility. I'm not skilled with Java UI, I can't figure out what's wrong with my code.
#SuppressWarnings("serial")
public class ImageCaptureManager extends JFrame {
private class SkipCapture extends AbstractAction {
public SkipCapture() {
super(“Skip”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class SnapMeAction extends AbstractAction {
public SnapMeAction() {
super(“Snap”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class captureCompleted extends AbstractAction {
public captureCompleted() {
super(“Completed”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class saveImage extends AbstractAction {
public saveImage() {
super(“Save”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class deleteImage extends AbstractAction {
public deleteImage() {
super(“Delete”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class StartAction extends AbstractAction implements Runnable {
public StartAction() {
super(“Start”);
}
#Override
public void actionPerformed(ActionEvent e) {
btStart.setEnabled(false);
btSnapMe.setEnabled(true);
executor.execute(this);
}
#Override
public void run() {
panel.start();
}
}
private Executor executor = Executors.newSingleThreadExecutor();
private Dimension captureSize = new Dimension(640, 480);
private Dimension displaySize = new Dimension(640, 480);
private Webcam webcam = Webcam.getDefault();
private WebcamPanel panel;
private JButton btSnapMe = new JButton(new SnapMeAction());
private JButton btStart = new JButton(new StartAction());
private JButton btComplete = new JButton(new captureCompleted());
private JButton btSave = new JButton(new saveImage());
private JButton btDelete = new JButton(new deleteImage());
private JButton btSkip = new JButton(new SkipCapture());
private JComboBox comboBox = new JComboBox();
public ImageCaptureManager() {
super(“Frame”);
this.addWindowListener( new WindowAdapter()
{
#Override
public void windowDeiconified(WindowEvent arg0) {
}
public void windowClosing(WindowEvent e)
{
}
});
List<Webcam> webcams = Webcam.getWebcams();
for (Webcam webcam : webcams) {
System.out.println(webcam.getName());
if (webcam.getName().startsWith("USB2.0 Camera 1")) {
this.webcam = webcam;
break;
}
}
panel = new WebcamPanel(webcam, displaySize, false);
webcam.setViewSize(captureSize);
panel.setFPSDisplayed(true);
panel.setFillArea(true);
btSnapMe.setEnabled(false);
btSave.setEnabled(false);
btDelete.setEnabled(false);
setLayout(new FlowLayout());
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(10, 1));
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSnapMe);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSave);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btDelete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btComplete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSkip);
JLabel label1 = new JLabel("Test");
label1.setText(“Bla bla bla”);
JLabel label2 = new JLabel("Test");
label2.setText(" ");
Panel captionAndWebcamPanel = new Panel();
captionAndWebcamPanel.add(label1);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(panel);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(comboBox);
captionAndWebcamPanel.setLayout(new BoxLayout(captionAndWebcamPanel, BoxLayout.Y_AXIS));
add(captionAndWebcamPanel);
add(buttonPanel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
btStart.doClick();
setSize(900,600);
}
}
You are mixing AWT and Swing components.
"Historically, in the Java language, mixing heavyweight and lightweight components in the same container has been problematic."
http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html
I suggest you try using JPanels instead of Panels for captionAndWebcamPanel and buttonPanel, I'd also set layout to captionAndWebcamPanel before adding components.
I'm currently running this in a class that extends a JFrame. When I close the window, I don't see RAN EVENT HANDLER in the console. This is not the main window, and more than one instance of this window can exist at the same time.
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
}
});
This method is inside a method called initialiseEventHandlers() which is called in the constructor, so I'm sure the code is running.
What am I doing wrong?
Thank you!
EDIT: Here's the full (summarised) code:
public class RacesWindow extends JFrame {
private JPanel mainPanel;
private JLabel lblRaceName;
private JTable races;
private DefaultTableModel racesModel;
public RacesWindow() {
this.lblRaceName = new JLabel("<html><strong>Race: " + race.toString()
+ "</strong></html>");
initialiseComponents();
this.setMinimumSize(new Dimension(500, 300));
this.setMaximumSize(new Dimension(500, 300));
initialiseEventHandlers();
formatWindow();
pack();
setVisible(true);
}
public void initialiseComponents() {
mainPanel = new JPanel(new BorderLayout());
races = new JTable();
racesModel = new DefaultTableModel();
races.setModel(racesModel);
}
public void initialiseEventHandlers() {
System.out.println("EVENTHANDLER CODE IS CALLED"); //for debugging
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
appManager.removeOpenWindow(race.toString());
}
});
}}
public void formatWindow() {
mainPanel.add(lblRaceName, BorderLayout.NORTH);
mainPanel.add(new JScrollPane(races), BorderLayout.CENTER);
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
this.add(mainPanel);
}
}
I found out I was using the wrong method: windowClosed(). I should use windowClosing()!
This should work
this.addWindowListener(new WindowListener() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
}
});
Add this to your constructor.
setDefaultCloseOperation(EXIT_ON_CLOSE);
The code below worked for me.
// parent class {
// constructor {
...
this.addWindowListener(new GUIFrameListener());
...
}
class GUIFrameListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Window Closed");
}
}
} // end of parent class