NullPointerException JFrame
Hi guys,
I am getting this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.ankix.snapxplorer.gui.pane.explorer.events.MenuBarActionListenerImpl$1.run(MenuBarActionListenerImpl.java:134)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)While on this:
public class MenuBarActionListenerImpl implements ActionListener
// CLASS MEMBERS
private Component objRef;
private ProcessPane objProcessPane;
private UsersPane objUsersPane;
// CLASS CONSTRUCTOR
public MenuBarActionListenerImpl(Component pComponent) //pComponent instance of JMenuBar
this.objRef = pComponent;
// CLASS METHODS
public void actionPerformed(ActionEvent e)
if(((JMenuItem)e.getSource()).getText() == "Logout")
this.objProcessPane = null;
this.objUsersPane = null;
SwingUtilities.invokeLater(new Runnable()
public void run()
((javax.swing.JFrame)objRef.getParent().getParent().getParent().getParent()).setContentPane(new LoginPane((javax.swing.JFrame)objRef.getParent().getParent().getParent().getParent()));
((javax.swing.JFrame)objRef.getParent().getParent().getParent().getParent()).validate();
((javax.swing.JFrame)objRef.getParent().getParent().getParent().getParent()).repaint();
}I know "objRef.getParent().getParent().getParent().getParent()" is the instance of the JFrame I am looking for so I can't figure out wthe problem.
Any ideas why this is happening?
Many Thanks,
MeTitus
Aehm, it might be easier to track down your problem by rewriting that actionPerformed:public void actionPerformed( ActionEvent e )
if ("Logout".equals(((JMenuItem)e.getSource()).getText()))
this.objProcessPane = null;
this.objUsersPane = null;
final Window w = SwingUtilities.getWindowAncestor(objRef);
if (w instanceof JFrame)
final JFrame frame = (JFrame)w;
frame.setContentPane(new LoginPane(frame));
frame.validate();
frame.repaint();
}Less method invocations per line narrow down the possibilities for NPEs!
BTW - do not use == to compare Strings!
Similar Messages
-
I am trying to catch if th euser did not select a file, then inform the user (in a pop-up window) that a file must be selected and then prompt the user to select a file, repeating until user selects a file. My logic below is flawed. Any help will be greatly appreciated.
package selectFile;
// SelectFile.java Author: Lynda R. Wallace Date: 04/12/2008
// Demonstrates the use of a file chooser and a text area.
import java.util.Scanner;
import java.io.*;
import javax.swing.*;
public class SelectFile
// Opens a file chooser dialog, reads the selected file and
// loads it into a text area.
public static void main (String[] args)
throws IOException, FileNotFoundException, NullPointerException
JFrame frame = new JFrame ("Display File");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea (20, 30);
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog (null); // status = 1
try
// first try -- no file chosen, status = 1
if (status != JFileChooser.APPROVE_OPTION)
textArea.setText ("No File Chosen"); // status = 1
// second try -- file chosen, status = 0
if (status == JFileChooser.APPROVE_OPTION)
File file = chooser.getSelectedFile();
Scanner scan = new Scanner (file);
String info = "";
while (scan.hasNext())
info += scan.nextLine() + "\n";
textArea.setText (info);
} // end if
} // end try
// first try -- not file chosen, status = 1
catch (NullPointerException e)
textArea.setText ("No File Chosen");
// second try -- file not found, status = 1
catch (FileNotFoundException e)
textArea.setText ("File not found. "
+ "try again.");
do
File file = chooser.getSelectedFile();
Scanner scan = new Scanner (file);
String info = "";
while (scan.hasNext())
info += scan.nextLine() + "\n";
textArea.setText (info);
} while (status != JFileChooser.APPROVE_OPTION);
} // end catch
frame.getContentPane().add (textArea);
frame.pack();
frame.setVisible(true);
} // end main method
} // end SelectFile classMissLynda wrote:
Thank you.
If the user pressed open, not selecting a file, I was trying to send a message "A file must be selected", then give the user a option to try again.Then you need some kind of loop around that code. I see you know about loops, because you wrote one in there to loop while reading data from the file, so certainly you can extend that knowledge to writing a loop around the other logic. -
NullPointerException caused by JFrame.setVisible()
I'm trying to make a status bar class for use with an app. The code for this class is below. Upon testing the thing i come upon the following exception:
Exception in thread "main" java.lang.NullPointerException
at sun.awt.windows.WPanelPeer.restack(Unknown Source)
at sun.awt.windows.WPanelPeer.restack(Unknown Source)
at sun.awt.windows.WPanelPeer.restack(Unknown Source)
at sun.awt.windows.WPanelPeer.restack(Unknown Source)
at sun.awt.windows.WPanelPeer.restack(Unknown Source)
at sun.awt.windows.WPanelPeer.restack(Unknown Source)
at sun.awt.windows.WPanelPeer.restack(Unknown Source)
at sun.awt.windows.WWindowPeer.restack(Unknown Source)
at java.awt.Container.addNotify(Unknown Source)
at java.awt.Window.addNotify(Unknown Source)
at java.awt.Frame.addNotify(Unknown Source)
at java.awt.Window.show(Unknown Source)
at java.awt.Component.show(Unknown Source)
at java.awt.Component.setVisible(Unknown Source)
at java.awt.Window.setVisible(Unknown Source)
at org.bio.sigve.gui.JStatusBar.main(JStatusBar.java:56)I'm at a loss as to why I'm getting this. Line 56 is the line where f.setVisible(true) is called. Here's the class:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
public class JStatusBar extends JPanel {
private Component[] columns;
public JStatusBar(){
super(new FlowLayout());
setBorder(new BevelBorder(BevelBorder.LOWERED));
createJStatusBar(1);
public JStatusBar(int cols) {
super(new FlowLayout());
createJStatusBar(cols);
private void createJStatusBar(int cols) {
columns = new JLabel[cols];
for(int i = 0; i<columns.length;i++) {
columns[i] = new JLabel("");
JPanel p = new JPanel();
p.setBorder(new BevelBorder(BevelBorder.LOWERED));
//p.add(columns);
add(p);
public void setComponent(Component c, int index) {
public Component getComponent(int index) {
return null;
public void setText(String text, int index) {
((JLabel)columns[index]).setText(text);
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel rot = new JPanel(new BorderLayout());
f.getContentPane().add(rot);
JStatusBar status = new JStatusBar();
rot.add(status);
status.setText("Hei!", 0);
f.setVisible(true);Because you override JPane's getComponent(int index) method,and don't write it right way.
-
NullPointerException when JFrame.setVisible is called
Hi,
We are upgrading our app from JDK 1.2.2 to JDK 1.4.
App used to work fine with JDK 1.2.2. Now it throws a
NullPointerException on one of the calls to JFrame.setVisible
method. Here is the error:
java.lang.NullPointerException
at javax.swing.text.PlainView.getLineWidth(PlainView.java:612)
at javax.swing.text.PlainView.getPreferredSpan(PlainView.java:211)
at javax.swing.plaf.basic.BasicTextUI$RootView.getPreferredSpan(BasicTex
tUI.java:1167)
at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:
737)
at javax.swing.JComponent.getPreferredSize(JComponent.java:1262)
at javax.swing.JTextArea.getPreferredSize(JTextArea.java:606)
at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:76
7)
at java.awt.Container.layout(Container.java:980)
at java.awt.Container.doLayout(Container.java:970)
at java.awt.Container.validateTree(Container.java:1048)
at java.awt.Container.validateTree(Container.java:1055)
at java.awt.Container.validateTree(Container.java:1055)
at java.awt.Container.validateTree(Container.java:1055)
at java.awt.Container.validateTree(Container.java:1055)
at java.awt.Container.validateTree(Container.java:1055)
at java.awt.Container.validateTree(Container.java:1055)
at java.awt.Container.validateTree(Container.java:1055)
at java.awt.Container.validate(Container.java:1023)
at java.awt.Window.show(Window.java:455)
at java.awt.Component.show(Component.java:1128)
at java.awt.Component.setVisible(Component.java:1083)
at com.teoco.events.EventViewerFrame.setVisible(EventViewerFrame.java:29
7)
at com.teoco.events.EventViewerFrame.display(EventViewerFrame.java:185)
at com.teoco.ImportGUI.Desktop.initializeApplication(Desktop.java:654)
at com.teoco.ImportGUI.Desktop.initializeApplication(Desktop.java:639)
at com.teoco.ImportGUI.Desktop.<init>(Desktop.java:310)
at com.teoco.ImportGUI.Desktop.<init>(Desktop.java:337)
at com.teoco.ImportGUI.Desktop.main(Desktop.java:1197)
I cannot figure out what could be causing this problem.
Any help is appreciated.
Thanks
JitendraHi Denis,
Thanks for the bug link you provided. I looked at the bug they were talking about, it looks similar to what is happening to me, but they were talking about Solaris and Linux. Our app runs on Windows and the report says they did not test the fix on Windows.
Jitendra -
"AWT-EventQueue-0" java.lang.NullPointerException and JInternalFrame
I have two classes one with main method second with GUI methods (JFrame, JInternalFrame). When I call method to start second JInternalFrame from main everything is working but if i call it form any other method i get:
Exception in thread "main" java.lang.NullPointerException
at pkg1.GUI.createFrame(GUI.java:123)
at pkg1.GUI.startFrame2(GUI.java:66)
at pkg1.Top.cos(Top.java:25)
at pkg1.Top.main(Top.java:20) My code:
GUI class
package pkg1;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.MouseMotionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import oracle.jdeveloper.layout.XYLayout;
public class GUI
public JDesktopPane desktop;
private XYLayout xYLayout1 = new XYLayout();
public int openFrameCount = 0;
JFrame f = new JFrame();
public void GUII() // Prepare JFrame
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 600);
f.setVisible(true);
public void startFrame()
desktop = new JDesktopPane();
createFrame(); //create first "window"
f.setContentPane(desktop);
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
public void startFrame2()
createFrame(); //create second "window"
f.setContentPane(desktop);
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
public void createFrame()
MyInternalFrame frame = new MyInternalFrame();
frame.setVisible(true); //necessary as of 1.3
desktop.add(frame);
frame.add(new GUI2());
} Top class
public class Top
public static void main(String[] args)
GUI g = new GUI();
g.GUII(); //Create JFrame
g.startFrame(); //Create JInternalFrame
Top t = new Top();
t.sth();
public void sth()
GUI gui = new GUI();
gui.startFrame2();
} MyIntternalFrame class
import javax.swing.JInternalFrame;
import java.awt.event.*;
import java.awt.*;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import oracle.jdeveloper.layout.XYConstraints;
import oracle.jdeveloper.layout.XYLayout;
/* Used by InternalFrameDemo.java. */
public class MyInternalFrame extends JInternalFrame {
static int openFrameCount = 0;
static final int xOffset = 30, yOffset = 30;
private XYLayout xYLayout1 = new XYLayout();
private JButton jButton1 = new JButton();
private JLabel jLabel1 = new JLabel();
private JFrame c = new JFrame();
private JPanel d = new JPanel();
private XYLayout xYLayout2 = new XYLayout();
public MyInternalFrame() {
super("Document #" + (++openFrameCount),true /*resizable*/,true /*closable*/,true /*maximizable*/,true);//iconifiable*/
//...Create the GUI and put it in the window...
//...Then set the window size or call pack...
int width = new GUI2().width + 10;
int height = new GUI2().height + 40;
setSize(width,height);
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
} Please tel me where is my mistake or maybe you knew another way to open JInternalFrame with public method form another classSome possibly helpful suggestions:
1) Create one JDesktopPane, and do it in the constructor of GUI. You should call this constructor only once.
2) Get rid of GUII. The GUI constructor will do all this and more.
3) Get rid of startFrame and startFrame2.
4) In GUI2, change your width and height to static variables if you are going to use them in outside classes. There is no reason to have to create a GUI2 object just to get those values. Get them from the class, not the instances.
5) You're doing something funky in your Top class with your mixing of static code and non-static code. My gut tells me that Top is just a static universe that exists to get your code up and running, and that the code within it should all be static, but that's just my personal opinion.
6) In MyInternalFrame, get the height and width from GUI2 (if that's what you want to do) again in a static fashion. Rather than new GUI2().width which makes no sense, use GUI2.width.
Why can't you put the button inside of the JInternalFrame object? I believe that the contentPane of this object which may hold your button (unless you embed a jpanel) uses BorderLayout, so you have to take care how you add jcomponents to the jinternalframe (or more precisely, it's contentPane). -
Passing data from a jFrame to another during runtime
Hi,
I have a JFrame which has a JTable and a button. I want when the user presses the button a new JFrame to open which has some fields that could be filled and after the user fills the fields those infos to be displayed in the first frame in JTable.
How could this be done?
Help is appreciated
Edited by: tomor on Aug 30, 2008 10:18 AMThanks for the reply ..
What I have tried to do is:
I Created a file called eventl10.java which has a constructor that recieves a object of type stdman (which in this case is the frame which contains the table) .. in the same time I have made another constructor which recieves a object of type addgrd as an argument (the frame for inserting the infos) and tried to somehow make a "connection" between these two which seems to throw a NullPointerException. So obivously this is not the way to be done:
package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class eventl10 implements ActionListener {
stdman obj;
addgrd obj2;
public eventl10 (stdman app)
obj = app;
public eventl10 (addgrd app)
obj2 = app;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == obj2.jButton3)
obj.addr_b.setText("Test");
}I just want some tips how could I set the text of a JTextField (which is found in another JFrame running at the moment).
Thanks for your replies -
NullPointerException, how do i get rid of?
Hey guys,
I'm totally puzzled by this one. All i'm trying to do is to change the content of JTextField(), but every time i do i get a NullPointerException. Here's the code:
public class PrivateMessageWindow extends JFrame
private Container container;
private JTextArea textArea;
private JTextField inputField;
private String windowId, messageDestination;
private Message m;
public PrivateMessageWindow(String Id)
super("Private Message");
Container container = getContentPane();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
JTextField inputField = new JTextField();
//ActionListener for inputField
ActionListener k = new PrivateWindowListener();
inputField.addActionListener(k);
//Placement of element on Panel
container.setLayout(new BorderLayout(5,5));
container.add(textArea, BorderLayout.CENTER);
container.add(inputField, BorderLayout.SOUTH);
//Initializes a message of type private Message
setSize( 300, 150);
setVisible(true);
}//end of constructor
private class PrivateWindowListener implements ActionListener
public void actionPerformed(ActionEvent event)
inputField.setText("");
}// end of private class PrivateMessageWindowThe problem occurs anytime i access a variable outside the actionPerformed method i get a NullPointerException. I'm not sure if it helps but this class gets triggered by a JButton object.
any clue of wats happening here?
Tanx.You are not initializing your JTextField inputField. Instead, you instantiate a local variable. The same applies to your JTextArea. You should have:textArea = new JTextArea();
textArea.setEditable(false);
inputField = new JTextField();Moreover, I don't think you really need the field container. -
How to add a table(from TableRenderDemo) to a JFrame again
Hello again:
Thanks for stephen andrews's adivice, I follow your adivice to add code (it is in
EventHandeler of DrawCalendar class, and they indicated by ???????????), but it still not work, please check for me why, Thanks.
My problem
Please run my coding first, and get some view from my coding.
At the movement, I got a problem, I have not idea how to add a table(it is from TableRenderDemo) to JFrame when I click on the button(from DrawCalendar) of the numer 20, and I want the table disply under the buttons(from DrawCalendar).
Please help me to solve this problem, thanks.
*This program for add some buttons and a table on JFrame
import java.awt.*;
import javax.swing.*;public class TestMain extends JFrame{
private static TableRenderDemo tRD;
private static TestMain tM;
protected static Container c;
private static DrawCalendar dC;
public static void main(String[] args){
tM = new TestMain();
tM.setVisible(true);
public TestMain(){
super(" Test");
setSize(800,600);
//set up layoutManager
c=getContentPane();
c.setLayout ( new GridLayout(3,1));
tRD=new TableRenderDemo();
dC=new DrawCalendar();
addItems();//add Buttons to JFrame
private void addItems(){
c.add(dC); //add Buttons to JFrame
//c.add(tRD); //add Table to JFrame
*This program for add some buttons to JPanel
*and add listeners to each button
*I want to display myTable under the buttons,
*when I click on number 20, but why it doesn't
*work, The coding for these part are indicated by ??????????????
[import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.GridLayout;
public class DrawCalendar extends JPanel {
private static DrawCalendar dC;
private static TestMain tM;
private static TableRenderDemo myTable;
private static GridLayout gL;
private static final int nlen = 35;
private static String names[] = new String[nlen];
private static JButton buttons[] = new JButton[nlen];
public DrawCalendar(){
gL=new GridLayout(5,7,0,0);
setLayout(gL);
assignValues();
addJButton();
registerListener();
//assign values to each button
private void assignValues(){
names = new String[35];
for(int i = 0; i < names.length; i++)
names[i] = Integer.toString(i + 1);
//create buttons and add them to Jpanel
private void addJButton(){
buttons=new JButton[names.length];
for (int i=0; i<names.length; i++){
buttons=new JButton(names[i]);
buttons[i].setBorder(null);
buttons[i].setBackground(Color.white);
buttons[i].setFont(new Font ("Palatino", 0,8));
add(buttons[i]);
//add listeners to each button
private void registerListener(){
for(int i=0; i<35; i++)
buttons[i].addActionListener(new EventHandler());
//I want to display myTable under the buttons,
//when I click on number 20, but why it doesn't
//work
private class EventHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
for(int i=0; i<35; i++){
if(i==20){ //????????????????????
tM=new TestMain(); //I want to display myTable under the buttons,
tM.c.removeAll(); //when I click on number 20, but why it doesn't
tM.c.add(dC); //work
tM.c.add(myTable); //???????????????????????????????????????
tM.validate();
if(e.getSource()==buttons[i]){
System.out.println("testing " + names[i]);
break;
*This program create a table with some data
[import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.DefaultCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TableRenderDemo extends JScrollPane {
private boolean DEBUG = true;
public TableRenderDemo() {
// super("TableRenderDemo");
MyTableModel myModel = new MyTableModel();
JTable table = new JTable(myModel);
table.setPreferredScrollableViewportSize(new Dimension(700, 70));//500,70
//Create the scroll pane and add the table to it.
setViewportView(table);
//Set up column sizes.
initColumnSizes(table, myModel);
//Fiddle with the Sport column's cell editors/renderers.
setUpSportColumn(table.getColumnModel().getColumn(2));
* This method picks good column sizes.
* If all column heads are wider than the column's cells'
* contents, then you can just use column.sizeWidthToFit().
private void initColumnSizes(JTable table, MyTableModel model) {
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
try {
comp = column.getHeaderRenderer().
getTableCellRendererComponent(
null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
} catch (NullPointerException e) {
System.err.println("Null pointer exception!");
System.err.println(" getHeaderRenderer returns null in 1.3.");
System.err.println(" The replacement is getDefaultRenderer.");
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, longValues[i],
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
//XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
public void setUpSportColumn(TableColumn sportColumn) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Chasing toddlers");
comboBox.addItem("Speed reading");
comboBox.addItem("Teaching high school");
comboBox.addItem("None");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
//Set up tool tip for the sport column header.
TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer)headerRenderer).setToolTipText(
"Click the sport to see a list of choices");
class MyTableModel extends AbstractTableModel {
final String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
final Object[][] data = {
{"Mary ", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Chasing toddlers", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Angela", "Lih",
"Teaching high school", new Integer(4), new Boolean(false)}
public final Object[] longValues = {"Angela", "Andrews",
"Teaching high school",
new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
* Don't need to implement this method unless your table's
* data can change.
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
if (data[0][col] instanceof Integer
&& !(value instanceof Integer)) {
//With JFC/Swing 1.1 and JDK 1.2, we need to create
//an Integer from the value; otherwise, the column
//switches to contain Strings. Starting with v 1.3,
//the table automatically converts value to an Integer,
//so you only need the code in the 'else' part of this
//'if' block.
try {
data[row][col] = new Integer(value.toString());
fireTableCellUpdated(row, col);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(TableRenderDemo.this,
"The \"" + getColumnName(col)
+ "\" column accepts only integer values.");
} else {
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
System.out.println();
System.out.println("--------------------------");http://forum.java.sun.com/faq.jsp#format
-
JApplet with JFrame fails to load in browser
I have been making a Java program that runs a JApplet the program operates perfectly in NetBeans (the Java development kit), but when I run it in the browser, it fails to load.
The code is...
import java.awt.*;
import javax.swing.*;
public class CalculatorMain extends javax.swing.JApplet {
private Difficulty difficulty = new Difficulty();
private Troop[] troop = new Troop[7];
private Army army = new Army(troop);
private Calculator calculator = new Calculator(difficulty, army);
private CalculatorListener listener;
public void init(){
JPanel supreme = new JPanel();
supreme.setLayout(new BorderLayout());
for (byte i = 0; i < 7; i++) {troop[i] = new Troop();}
DifficultyPanel diffpanel = new DifficultyPanel(difficulty);
ArmyPanel armypanel = new ArmyPanel(troop);
JButton calbut = new JButton("Calculate Experience");
JLabel xpDisplay = new JLabel(" ");
CalculatorPanel calpanel = new CalculatorPanel(calculator, calbut, xpDisplay);
JFrame frame = new JFrame();
listener = new CalculatorListener(xpDisplay, calculator, diffpanel, armypanel, calpanel);
calbut.addActionListener(listener);
supreme.add(diffpanel, BorderLayout.WEST);
supreme.add(armypanel, BorderLayout.CENTER);
supreme.add(calpanel, BorderLayout.SOUTH);
frame.add(supreme);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
As I said, it does not work in the web browser (which is Internet Explorer 6.0). In the information window I open, the message is...
Java Plug-in 1.5.0_06
Anv�nder JRE-version 1.5.0_06 Java HotSpot(TM) Client VM
java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkExit(Unknown Source)
at javax.swing.JFrame.setDefaultCloseOperation(Unknown Source)
at CalculatorMain.init(CalculatorMain.java:31)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception in thread "thread applet-CalculatorMain.class" java.lang.NullPointerException
at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
at sun.plugin.AppletViewer.showAppletException(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Any idea what might be wrong?If you look at your error message you'll see...
java.security.AccessControlException: access deniedAh. Problem # 1 caused at
at CalculatorMain.init(CalculatorMain.java:31)Problem #2
java.lang.NullPointerExceptionat
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)So it says it can't display the init error message. That's ok this should go away when you fix bug #1 -
Multiple Components in a JFrame (simple question)
Hello everyone, I need to put two components in my JFrame, and I have been expieriencing some odd problems. I use this to add my components...
MyComponent mc=new MyComponent();
MyOtherComponent me = new MyOtherComponent();
When I try to access methods they work fine. I can use repaint() in a method and it works. BUT when I try to draw on the component using anything besides paintComponent() It gives me a java.lang.NullPointerException
here is what I tried.....
me.draw(getGraphics());
//later on in the component def..
draw(Graphics g) {
} // I get a java.lang.NullPointerException in main
whenever i use getGraphics() it does'nt work what am I doing wrong?Yup I did that and repaint does jack all. When I run the code all I see the contents of the first component. I know that the methods of the second component are being executed, but the paintComponent method is simply not running. I put a System.out.println("hi"); in and it never showed in the console..
Anyone who can help me gets a duke, here's my second component code..
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MyOtherComponent extends JComponent {
public void paintComponent(Graphics gg) {
System.out.println("paintComponent executed!!!");
Graphics2D g2D = (Graphics2D)gg;
ImageIcon icon = null;
try {icon = new ImageIcon(new URL("http://images.neopets.com/m.gif")); }
catch(MalformedURLException e) {
System.out.println("no"); return;
resize(icon.getIconWidth(),icon.getIconHeight());
Image mark = icon.getImage();
g2D.drawImage(mark,0,0,this);
g2D.drawString("hello folk",40,40);
drawe(g2D);
public void drawe(Graphics2D g2D) {
g2D.drawLine(50,50,500,500);
g2D.fillRect(20,20,20,20);
repaint();
public void line() {
System.out.println("Hello, from MyOtherComponent");
public void re() {
repaint();
System.out.println("re");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -
To use a static variable in another class,but report NullPointerException
when TableMain is running,I run testRecord so that let TableMain add a occur informatin and
happened time in a row in TableMain,but when I run testRecord,java report a NullPointerException and I dont know how to solve this problem,thanks for helping me to check my code;(error report info is in end)
import java.awt.event.*;
import javax.swing.table.*;
import java.io.*;
public class TableMain extends JFrame{
JTable table;
static OwnModel model;
String[] columnHeader={"occur","time"};
class OwnModel extends DefaultTableModel{
public OwnModel(Object[] columnNames,int numRows){
super(columnNames,numRows);
public boolean isCellEditable(int row,int column){
return false;
public TableMain(){
model=new OwnModel(columnHeader,0);
table=new JTable(model);
JScrollPane scroll=new JScrollPane(table);
JButton save=new JButton("save record");
JButton delete=new JButton("delete record");
JPanel buttons=new JPanel();
buttons.add(save);
buttons.add(delete);
JLabel sign=new JLabel("occur record");
Container cp=getContentPane();
cp.add(BorderLayout.NORTH,sign);
cp.add(BorderLayout.CENTER,scroll);
cp.add(BorderLayout.SOUTH,buttons);
this.setSize(300,500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static void main(String[] args){
new TableMain();
import java.util.Vector;
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class testRecord{
public static void main(String[] args){
SimpleDateFormat simpledf=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String tableName="friends";
Calendar occurtime=Calendar.getInstance();
Vector record=new Vector();
record.add("send 'desc' sql, "+"operated table is :"+tableName);
record.add(simpledf.format(occurtime.getTime()));
System.out.println("model is "+Guide.model);
System.out.println("record is "+record);
Guide.model.addRow(record);
error report:
model is null
record is [send 'desc' sql,operated table is :friends, 2004/05/26 11:39:03]
Exception in thread "main" java.lang.NullPointerException
at testRecord.main(testRecord.java:14)but I just use this constructor once,never use twice
with same jvm;I thinks my idea is not too very badIt's a public constructor (if I'm looking in the right
place) - it could be called from anywhere. To
intialize a static variable outside the declaration,
use a static initializer:private static String whatever;static {
whatever = "whatever";
}Or simply (in this case):private static String whatever = "whatever"; -
Hi all,
i have a problem by solving an error in my code. The Code is mainly from Ian Darwin.
The code i am running works with j2sdk1.4.2_04. But now i have to bring it to work with jdk1.6.0_13.
The code parses xml documents. With small xml documents the code works. With large xml documents i get the following error while running the produced class file.
Exception in thread "main" java.lang.NullPointerException
at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.setChunkIndex(DeferredDocumentImpl.java:1944)
at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.appendChild(DeferredDocumentImpl.java:644)
at com.sun.org.apache.xerces.internal.parsers.AbstractDOMParser.characters(AbstractDOMParser.java:1191)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.characters(XMLDTDValidator.java:862)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:463)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208)
at XParse.parse(XParse.java:38)
at XParse$JFileChooserrv.<init>(XParse.java:119)
at XParse.main(XParse.java:213)
I know what a java.lang.NullPointerException mens. But i don't know where i have to look for. Specially i don't know what or where "com.sun.org.apache...." is.
Is there a package that a have to add to the environment? Can some one tell my where i can find this package?
I wrote the code for some years ago, 2006 or so. With the knew jdk1.6.0_13 some thinks chance in the environment. Couldn't find what exactly.
The code has only 215 lines, but some how i can't add it to this Message, because Maximum allowed is only 7500.
Is there an other Forum, which may is better for my question?Here is the code:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.Container;
import javax.swing.JTextArea;
* This code is mainly from @author Ian Darwin, [email protected]
public class XParse {
/** Convert the file */
public static void parse(File file, boolean validate) {
try {
System.err.println("");
String fileName = file.getAbsolutePath();
System.err.println("Parsing " + fileName + "...");
// Make the document a URL so relative DTD works.
//String uri = new File(fileName).getAbsolutePath();
//System.err.println(uri);
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
if (validate)
f.setValidating(true);
DocumentBuilder p = f.newDocumentBuilder();
p.setErrorHandler(new MyErrorHandler(System.err));
//XmlDocument doc = XmlDocument.createXMLDocument(file);
boolean vaild = p.isValidating();
if (vaild) {
System.out.println("yes parsing");
Document doc = p.parse(file); // <<<< ERROR
System.out.println("Parsed OK");
} catch (SAXParseException ex) {
System.err.println("+================================+");
System.err.println("| *SAX Parse Error* |");
System.err.println("+================================+");
System.err.println(ex.toString());
System.err.println("At line " + ex.getLineNumber());
System.err.println("+================================+");
} /**catch (RuntimeException ex) {
System.err.println("+================================+");
System.err.println("| *SAX Parse Error* |");
System.err.println("+================================+");
System.err.println(ex.toString());
//System.err.println("At line " + ex.getLineNumber());
//System.err.println("At line " + ex.getMessage());
System.err.println("+================================+");
}**/ catch (SAXException ex) {
System.err.println("+================================+");
System.err.println("| *SAX Error* |");
System.err.println("+================================+");
System.err.println(ex.toString());
System.err.println("+================================+");
/*}} catch (SAXNotRecognizedException ex) {
System.err.println(" no SAX");*/
} catch (ParserConfigurationException ex) {
System.err.println(" ???");
} catch (IOException ex) {
System.err.println("+================================+");
System.err.println("| *XML Error* |");
System.err.println("+================================+");
System.err.println(ex.toString());
private static class JFileChooserrv {
JFileChooserrv(JFrame f, boolean vverabreiten) {
String openfile;
String verror;
boolean validate = true;
final JFrame frame = f;
String vFilename = "Z:\\Boorberg\\parsen_vista\\daten";
//String vFilename = "C:\\";
File vFile = new File(vFilename);
final JFileChooser chooser = new JFileChooser(vFile);
JFileFilter filter = new JFileFilter();
filter.addType("xml");
filter.addType("sgml");
filter.addType("html");
filter.addType("java");
filter.setDescription("strukturfiles");
chooser.addChoosableFileFilter(filter);
boolean vjeas = true;
chooser.setMultiSelectionEnabled(vjeas);
int returnVal = chooser.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
//Array filearry[] = chooser.getSelectedFiles();
//if (vFile = chooser.getSelectedFiles()) {
//File file[] = chooser.getSelectedFiles();
File vfile[] = chooser.getSelectedFiles();
//String openfile = new String();
int vlenght = vfile.length;
if (vlenght>1) {
int x=0;
while (x< vlenght) {
parse(vfile[x], validate);
x = x +1;
if (vlenght<=1) {
File v2file = chooser.getSelectedFile();
parse(v2file, validate);
} else {
System.out.println("You did not choose a filesystem object.");
System.exit(0);
private static class JFileFilter extends javax.swing.filechooser.FileFilter {
protected String description, vnew;
protected ArrayList<String> exts = new ArrayList<String>();
protected boolean vtrue;
public void addType(String s) {
exts.add(s);
/** Return true if the given file is accepted by this filter. */
public boolean accept(File f) {
// Little trick: if you don't do this, only directory names
// ending in one of the extentions appear in the window.
if (f.isDirectory()) {
return true;
} else if (f.isFile()) {
Iterator it = exts.iterator();
while (it.hasNext()) {
if (f.getName().endsWith((String)it.next()))
return true;
// A file that didn't match, or a weirdo (e.g. UNIX device file?).
return false;
/** Set the printable description of this filter. */
public void setDescription(String s) {
description = s;
/** Return the printable description of this filter. */
public String getDescription() {
return description;
private static class MyErrorHandler implements ErrorHandler {
// Error handler output goes here
private PrintStream out;
MyErrorHandler(PrintStream out) {
this.out = out;
* Returns a string describing parse exception details
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException {
//System.exit(0);
//out.println("Warning: " + getParseExceptionInfo(spe));
public void error(SAXParseException spe) throws SAXException {
//System.exit(0);
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
public void fatalError(SAXParseException spe) throws SAXException {
//System.exit(0);
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
public static void main(String[] av) {
JFrame vframe = new JFrame("chose files to pars");
boolean vverabreiten = true;
boolean validate = true;
JFileChooserrv vdateienwaehlen = new JFileChooserrv(vframe, vverabreiten);
}The Stack Trace i posted in the last Message. But i couldn't read it, i am not a programmer. -
Problem about "Exception in thread "main" java.lang.NullPointerException"
This is t error message once i run the file
Exception in thread "main" java.lang.NullPointerException
at sendInterface.<init>(sendInterface.java:64)
at sendInterface.main(sendInterface.java:133)
* @(#)sendInterface.java
* @author
* @version 1.00 2008/7/18
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.SwingConstants;
import java.io.*;
import java.sql.*;
import java.net.*;
public class sendInterface /*implements ActionListener*/{
JFrame frame = new JFrame();
private Panel topPanel;
private Panel sendMessagePanel;
private Panel sendFilePanel;
private JLabel senderID;
private JLabel receiverID;
private JLabel senderDisplay;
private DefaultListModel receiverListModel = new DefaultListModel();
private JList receiverID_lst = new JList(receiverListModel);
private JRadioButton sendType;
String userName;
String[] userList = null ;
int i=0;
Connection con;
public sendInterface() {
String ListName;
try
JFrame.setDefaultLookAndFeelDecorated( true );
catch (Exception e)
System.err.println( "Look and feel not set." );
frame.setTitle( "Send Interface" );
topPanel.setLayout( new GridLayout( 2 , 1 ) ); //line 64*************************
senderID = new JLabel( "Sender:", SwingConstants.LEFT );
senderDisplay = new JLabel( "'+...+'", SwingConstants.LEFT );
receiverID = new JLabel( "Receiver:", SwingConstants.LEFT);
// receiverID_lst = new JList( ListName );
frame.add(senderID);
frame.add(senderDisplay);
frame.add(receiverID);
// frame.add(receiverListModel);
frame.add(new JScrollPane(receiverID_lst), BorderLayout.CENTER);
frame.setLocation(200, 200);
frame.setSize(250, 90);
frame.setVisible(true);
public void setListName(String user)
try{
userName = user;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/thesis";
con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from user where User_ID!= '" + userName + "'");
System.out.println("Display all results:");
while(rs.next()){
String user_id = rs.getString("User_ID");
System.out.println("\tuser_id= " + user_id );
// receiverListModel.addElement(user_id);
userList=user_id;
i++;
}//end while loop
receiverListModel.addElement(userList);
catch(Exception ex)
ex.printStackTrace();
finally
if (con != null)
try
con.close ();
System.out.println ("Database connection terminated");
catch (Exception e) { /* ignore close errors */ }
public String getUserName()
return userName;
public String[] getUserList()
return userList;
public static void main(String[] args) {
new sendInterface(); //line 133******************************************
thank ur reply:D
Edited by: ocibala on Aug 3, 2008 9:54 AMAnd where do you instantiate topPanel before you invoke setLayout?
db -
Hi guys,
I'm getting a java.lang.NullPointerException (with no other details of error) when i try to write to a textfield on my GUI. the line: TF1.setText("F"); is where the problem is occurring. that line is within a loop ->
if(freq >87 && freq < 100)
System.out.println("Note =F" +freq);
TF1.setText("F");
the textfield has been constructed and initialised and given an initial value. what i need to happen is the string in the textfield to be constantly updated (overwritten) with the new string.
the initial value from TextField TF1= new TextField("", 10);
TF1.setText("blank");
works fine, but one the loop above is entered, the current frequency is printed to the command line and then "java.lang.NullPointerException" is thrown.
I'm struggling with this, and have a deadline to meet so I would much appreciate some help.The Gui class is this:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import javax.swing.JFrame;
import javax.swing.*;
public class Gui extends JFrame{
public static void main(String args[])
Project project = new Project();
project.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
project.setSize( 250, 200 ); // set frame size
project.setVisible( true ); // display frame
// new Project(){//constructor
Panel p, p1;
p = new Panel();
p.setLayout (new FlowLayout(FlowLayout.LEFT,5,5));
project.add(p, BorderLayout.NORTH);
p1 = new Panel();
p1.setLayout (new FlowLayout(FlowLayout.LEFT,5,5));
p1.setLayout (new GridLayout(4,1));
project.setTitle("Guitar Tuner Prototype");
TextField TF1= new TextField("", 10);
TF1.setText("blank");
p1.add(TF1);
TF1.setVisible(true);
p1.setVisible(true);
p.add(p1);
//Capture input data from the microphone
project.captureAudio();
project.captureThread();
}//end constructor
//end main
The project.java class has the "private TextField TF1; at the top. the project.java class also contains the loop thats writing to the texfield as specified in th original post.. -
Java.lang.NullPointerException when scrolling in JComboBox
Hi everybody,
I use a JComboBox in my application. If I scroll it a NullPointerException is thrown:
java.lang.NullPointerException
at javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion(BufferStrategyPaintManager.java:406)
at javax.swing.BufferStrategyPaintManager.copyArea(BufferStrategyPaintManager.java:334)
at javax.swing.RepaintManager.copyArea(RepaintManager.java:1143)
at javax.swing.JViewport.blitDoubleBuffered(JViewport.java:1604)
at javax.swing.JViewport.windowBlitPaint(JViewport.java:1573)
at javax.swing.JViewport.setViewPosition(JViewport.java:1118)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.vsbStateChanged(BasicScrollPaneUI.java:1027)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(BasicScrollPaneUI.java:1016)
at javax.swing.DefaultBoundedRangeModel.fireStateChanged(DefaultBoundedRangeModel.java:348)
at javax.swing.DefaultBoundedRangeModel.setRangeProperties(DefaultBoundedRangeModel.java:285)
at javax.swing.DefaultBoundedRangeModel.setValue(DefaultBoundedRangeModel.java:151)
at javax.swing.JScrollBar.setValue(JScrollBar.java:446)
at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.mouseWheelMoved(BasicScrollPaneUI.java:962)
at java.awt.Component.processMouseWheelEvent(Component.java:6126)
at java.awt.Component.processEvent(Component.java:5810)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchMouseWheelToAncestor(Component.java:4555)
at java.awt.Component.dispatchEventImpl(Component.java:4296)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4015)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)This is the code I execute:
public static void test()
Object[] items = new Object[10];
items[0] = 0;
items[1] = 1;
items[2] = 2;
items[3] = 3;
items[4] = 4;
items[5] = 5;
items[6] = 6;
items[7] = 7;
items[8] = 8;
items[9] = 9;
JFrame frame = new JFrame("Test frame");
JPanel panel = new JPanel();
panel.add(new JLabel("Combobox:"));
panel.add(new JComboBox(items));
frame.add(panel);
frame.pack();
frame.setVisible(true);
}The weird thing is that if I execute this piece of code outside my program, in a test class, everything goes fine. I am not sure how this is possible.
Best regards,
Jethro BorsjeYou not assign any ActionListener to your ComboBox ?Well, in my real-life implementation I plan to do so, however in the test() method I do not. And the problem is still there in the test method, so to answer your question: no I do not add an ActionListener to the JComoBox in my test case.
A little bit more info: when I scroll in the JComboBox the scrollwheel of my mouse, the scrollbar on the right side does not move, however the contents of the JComboBox does move.
Maybe you are looking for
-
What is wrong with my Eclipse??
Dear Sir: I have following problem in Eclipse 3.3.1 When i run in Command console, It success all, But when I put into Eclipse, It fails, I got follwoing error: ERROR>java version "1.6.0" ERROR>Java(TM) SE Runtime Environment (build 1.6.0-b105) ERROR
-
Satellite Pro A210 Upgrade from Vista to Windows 7
Hello Can anyone suggest why I am having problems upgrading from 32bit vista to windows 7 - 32 vista? I'm not sure if it is because there isn't enough RAM Has anyone else had a similiar problem on this laptop? Thanks CLary
-
10.5.7 - VGA connection to LCD TV on new MacBook Pro dead. HELP PLEASE!
I don't have a clue what's gone on here. Just downloaded the latest update and the connection to my TV has gone mental. It changes the resolution on my MacBook screen to something ridiculous and doesn't properly connect to the TV screen. Obviously, t
-
My late 2011 MBP has been randomly restarting lately. Very frustrating. Can anyone tell me what the problem is? Is it a kernal panic, and if so what can I do about it? I have included the error report below. Thanks! Interval Since Last Panic Report:
-
When I click photos or record video in nokia lumnia 520......but not shown in mobile in sd card.......help Plzzzzzzzzzzzzzzzzz......