NullPointerException, sometimes it runs and sometimes it throws exception - java

When I add JFileChooser and initialize it, then it throws the NullPointerException. Without JFileChooser, the same code runs pretty well every time I compile and run. But when I add JFileChooser then it throws the Exception. Sometimes, it runs successfully and sometimes it doesn't.Exceptionis:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.text.PlainView.getPreferredSpan(PlainView.java:233)
at javax.swing.plaf.basic.BasicTextUI$RootView.getPreferredSpan(BasicTextUI.java:1353)
at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:921)
at javax.swing.plaf.basic.BasicTextAreaUI.getPreferredSize(BasicTextAreaUI.java:120)
at javax.swing.JComponent.getPreferredSize(JComponent.java:1659)
at javax.swing.JTextArea.getPreferredSize(JTextArea.java:619)
at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:791)
at java.awt.Container.layout(Container.java:1508)
at java.awt.Container.doLayout(Container.java:1497)
at java.awt.Container.validateTree(Container.java:1693)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validateTree(Container.java:1702)
at java.awt.Container.validate(Container.java:1628)
at java.awt.Container.validateUnconditionally(Container.java:1665)
at java.awt.Window.show(Window.java:1033)
at java.awt.Component.show(Component.java:1654)
at java.awt.Component.setVisible(Component.java:1606)
at java.awt.Window.setVisible(Window.java:1014)
at notepad.Notepad.<init>(Notepad.java:66)
at notepad.Notepad.main(Notepad.java:144)
My code is:
package notepad;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Notepad extends JFrame implements ActionListener{
private JTextArea area;
private ImageIcon frameicon;
private JMenu filemenu;
private JMenu editmenu;
private JMenu formatmenu;
private JMenu helpmenu;
private JScrollPane scroll;
private Font font;
private JMenuBar menubar;
private JMenuItem newmenuitem;
private JMenuItem openmenuitem;
private JMenuItem savemenuitem;
private JMenuItem exitmenuitem;
private int msg;
private int returnVal;
private JFileChooser choose;
public Notepad(){
initComponents();
setComponents();
setTitle("Simple Notepad");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(500, 100);
setResizable(true);
setSize(600,600);
setJMenuBar(menubar);
menubar.add(filemenu);
menubar.add(editmenu);
menubar.add(formatmenu);
menubar.add(helpmenu);
filemenu.add(newmenuitem);
filemenu.add(openmenuitem);
filemenu.add(savemenuitem);
filemenu.add(exitmenuitem);
add(scroll);
setIconImage(frameicon.getImage());
setVisible(true);
}
public final void initComponents(){
area = new JTextArea();
scroll = new JScrollPane (area, //no need of add textArea when added in JScrollPane
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
menubar = new JMenuBar();
filemenu = new JMenu(" File");
editmenu = new JMenu(" Edit");
formatmenu = new JMenu(" Format");
helpmenu = new JMenu(" Help");
newmenuitem = new JMenuItem(" New");
openmenuitem = new JMenuItem(" Open");
savemenuitem = new JMenuItem(" Save");
exitmenuitem = new JMenuItem(" Exit");
choose = new JFileChooser("E:");
font = new Font("Calibri",Font.PLAIN,26);
frameicon = new ImageIcon(getClass().getResource("/res/setting.png"));
}
public final void setComponents(){
area.setSize(600,600);
area.setBackground(Color.WHITE);
area.setFont(font);
//adding ActionListener
newmenuitem.addActionListener(this);
exitmenuitem.addActionListener(this);
openmenuitem.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
//if newmenuitemclicked
if(e.getSource()==newmenuitem) {
if(area.getText()!=""){
msg = JOptionPane.showConfirmDialog(menubar, "DO you want to save changes?");
if(msg == JOptionPane.YES_OPTION){
try {
FileOutputStream file = new FileOutputStream("E:\\newdocument.txt");
String s = area.getText();
byte c[] = s.getBytes();
file.write(c);
area.setText("");
JOptionPane.showMessageDialog(menubar, "File saved as E:\\newdocument.txt");
file.close();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}
if(msg == JOptionPane.NO_OPTION){
}
}
}
if(e.getSource() == exitmenuitem){
msg = JOptionPane.showConfirmDialog(menubar, "Are you sure you want to exit?");
if(msg == JOptionPane.YES_OPTION)
System.exit(0);
}
if(e.getSource() == openmenuitem){
}
}
public static void main(String[] args) {
Notepad n = new Notepad();
}
}

No relevance to JFileChooser I think. Seems one of your components is not instantiated properly.
at java.awt.Window.setVisible(Window.java:1014)
And you can't call its setVisible(true) method.
Anyway to realize the true cause you should include your code.
Update: since your code is included, you can't use setVisible method in constructor. Use it in init() method.
It's because your object won't get instanced properly before constructor execution ends.

Related

JTextPane - line wrap

i am working on a word processor and my hope is to allow the user do what all word processors allow them to do. My issue at the moment is trying to understand how to force text that is being wrote by the user on to the next line once the maximum width has been reached (the size of the frame). For example if i am writing a sentence (or question on stack overflow) once my text hits the boundary of the text area it automatically brings me to the next line without me pressing Enter/return. After doing some research into line wrapping i came across the following
http://www.java-forums.org/awt-swing/59790-line-wrapping-jtextpane.html
Toggling text wrap in a JTextpane
however i cannot seem to get the behavior i want from the JTextPane below is my code, as always i appreciate any assistance offered.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class WordFrame{
private JFrame appFrame;
private JMenuBar menuBar;
private JMenu fileMenu, editMenu, viewMenu;
JMenuItem saveMenuItem, openMenuItem, newMenuItem, exitMenuItem, fontMenuItem;
JTextPane textArea = new JTextPane();
static final int WIDTH = 1280, HEIGHT = 980;
private JScrollPane scrollBar = new JScrollPane(textArea);
JPanel wordPanel = new JPanel();
JFileChooser fileChooser = new JFileChooser();
private int textHeight = 12;
private Font defaultFont = new Font(Font.SANS_SERIF, 2, textHeight);
public WordFrame(){
appFrame = new JFrame();
setUI();
addMenuBar();
textArea.setFont(defaultFont);
}
public JFrame getAppFrame(){
return appFrame;
}
public void setFrameVisibility(boolean isVisible){
if(isVisible == true){
appFrame.setVisible(true);
}
else{
appFrame.setVisible(false);
}
}
public void setUI(){
appFrame.setTitle("Word Processor");
appFrame.setIconImage(new ImageIcon(this.getClass().getResource("Bridge.jpg")).getImage());
appFrame.setSize(WIDTH, HEIGHT);
appFrame.setLocation(0,0);
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// scrollbar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
wordPanel.setLayout(new BorderLayout());
appFrame.add(wordPanel);
textArea.setPreferredSize(new Dimension(400,500));
appFrame.add(scrollBar);
wordPanel.add(textArea);
scrollBar.setViewportView(wordPanel);
}
public void addMenuBar(){
menuBar = new JMenuBar();
fileMenu = new JMenu(" File ");
editMenu = new JMenu("Edit ");
viewMenu = new JMenu("View ");
newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
fileMenu.addSeparator();
fileMenu.setMnemonic('f');
openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
saveMenuItem = new JMenuItem("Save");
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
fontMenuItem = new JMenuItem("Font");
editMenu.add(fontMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);
appFrame.setJMenuBar(menuBar);
}
public void setFontSize(int i){
this.textHeight = i;
}
public void addListener(ActionListener listener){
openMenuItem.addActionListener(listener);
exitMenuItem.addActionListener(listener);
saveMenuItem.addActionListener(listener);
}
}
After inserting code that i found on the internet. The text wraps once the edge (right) is hit by the text (basically if it goes to the max right of the application screen it automatically drops down to a new line. However a new issue has occurred this involves the JScrollBar, as everyone would expect, once text hits the bottom of the application screen a scrollbar would update to offer the user the ability to scroll up and down the page, this would make sense, however my code doesn't allow this. Here is the ammended code after my attempt to fix the line wrap issue (i still consider this the same question), further more if the following is commented out, text wrapping no longer works
textArea.setPreferredSize(new Dimension(400,500));
the code up there causes text wrap to fail completely.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class WordFrame{
private JFrame appFrame;
private JMenuBar menuBar;
private JMenu fileMenu, editMenu, viewMenu;
JMenuItem saveMenuItem, openMenuItem, newMenuItem, exitMenuItem, fontMenuItem;
JTextPane textArea = new JTextPane();
static final int WIDTH = 1280, HEIGHT = 980;
private JScrollPane scrollBar = new JScrollPane(textArea);
JPanel wordPanel = new JPanel();
JFileChooser fileChooser = new JFileChooser();
private int textHeight = 12;
private Font defaultFont = new Font(Font.SANS_SERIF, 2, textHeight);
public WordFrame(){
appFrame = new JFrame();
setUI();
addMenuBar();
textArea.setFont(defaultFont);
}
public JFrame getAppFrame(){
return appFrame;
}
public void setFrameVisibility(boolean isVisible){
if(isVisible == true){
appFrame.setVisible(true);
}
else{
appFrame.setVisible(false);
}
}
public void setUI(){
appFrame.setTitle("Word Processor");
appFrame.setIconImage(new ImageIcon(this.getClass().getResource("Bridge.jpg")).getImage());
appFrame.setSize(WIDTH, HEIGHT);
appFrame.setLocation(0,0);
appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollBar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
wordPanel.setLayout(new BorderLayout());
// appFrame.getContentPane().add(scrollBar, BorderLayout.CENTER);
textArea.setPreferredSize(new Dimension(400,500));
appFrame.add(wordPanel);
appFrame.add(scrollBar);
wordPanel.add(textArea);
// appFrame.add(textArea);
scrollBar.setViewportView(wordPanel);
textArea.setEditorKit(new WrapEditorKit());
}
public void addMenuBar(){
menuBar = new JMenuBar();
fileMenu = new JMenu(" File ");
editMenu = new JMenu("Edit ");
viewMenu = new JMenu("View ");
newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
fileMenu.addSeparator();
fileMenu.setMnemonic('f');
openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
saveMenuItem = new JMenuItem("Save");
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
fontMenuItem = new JMenuItem("Font");
editMenu.add(fontMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);
appFrame.setJMenuBar(menuBar);
}
public void setFontSize(int i){
this.textHeight = i;
}
public void addListener(ActionListener listener){
openMenuItem.addActionListener(listener);
exitMenuItem.addActionListener(listener);
saveMenuItem.addActionListener(listener);
fontMenuItem.addActionListener(listener);
}
class WrapEditorKit extends StyledEditorKit {
ViewFactory defaultFactory=new WrapColumnFactory();
public ViewFactory getViewFactory() {
return defaultFactory;
}
}
class WrapColumnFactory implements ViewFactory {
public View create(Element elem) {
String kind = elem.getName();
if (kind != null) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new WrapLabelView(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (kind.equals(AbstractDocument.SectionElementName)) {
return new BoxView(elem, View.Y_AXIS);
} else if (kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
// default to text display
return new LabelView(elem);
}
}
class WrapLabelView extends LabelView {
public WrapLabelView(Element elem) {
super(elem);
}
public float getMinimumSpan(int axis) {
switch (axis) {
case View.X_AXIS:
return 0;
case View.Y_AXIS:
return super.getMinimumSpan(axis);
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
}
}

JOptionPane not showing up (null parameter, called from inner class)

I am completely new to JAVA, I am trying to make a simple application and there is no way I can get my JOptionPane to show correctly and I guess I am missing something:
here's the code:
import java.awt.Color;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Frame extends JFrame
{
private static final long serialVersionUID = 1L;
final static int WIDTH = 400;
final static int HEIGHT = 400;
public Frame()
{
super("Convert to Dxf alpha ver. - survey apps 2014");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocation(100, 100);
setBackground(Color.WHITE);
setVisible(true);
WelcomePanel welcomePanel = new WelcomePanel(this);
add(welcomePanel);
}
public void createMenuPanel()
{
MenuPanel menu = new MenuPanel();
setJMenuBar(menu.createMenu(this));
}
}
class MenuPanel extends JPanel implements ActionListener
{
private JMenuItem open,save,close;
private JMenu file,about;
private Frame frame;
private static final long serialVersionUID = 1L;
public JMenuBar createMenu(Frame frame)
{
this.frame = frame;
JMenuBar menuBar = new JMenuBar();
file = new JMenu("File");
about = new JMenu("About");
menuBar.add(file);
menuBar.add(about);
open = new JMenuItem("Open");
save = new JMenuItem("Save");
close = new JMenuItem("Close");
file.add(open);
file.add(save);
file.addSeparator();
file.add(close);
open.addActionListener(this);
save.addActionListener(this);
close.addActionListener(this);
about.addActionListener(this);
return menuBar;
}
public MenuPanel()
{
setVisible(true);
setOpaque(true);
setBackground(Color.WHITE);
setSize(Window.WIDTH,Window.HEIGHT);
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == open)
{
frame.dispose();
}
if(source == save)
{
}
if(source == close)
{
}
if(source == about)
{
JOptionPane.showMessageDialog(frame, "EasyDxfCreator - alpha version");
}
}
}
(I skipped the WelcomeFrame because it's just like a welcome screen that disappears after a mouse click)
JMenu does not operate in that way. TO get JMenu Events you need to implement MenuListener instead of ActionListener. ActionListener is good for JMenuItem.
Hope this helps.

System.exit(0) trouble

I am relatively new to java(started coding about a month ago),and after doing basic examples of gui programs,i decided to create a very simple text editor(something like Notepad).
I've made a menu bar,with menu File,with menu items Open,Save,Exit.Everything works perfectly but the Exit menu item.
So here is the whole code.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Editor {
JTextArea TextAr = new JTextArea();
JFileChooser chooser = new JFileChooser();
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Editor window = new Editor();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Editor() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
TextAr.setBounds(10, 11, 414, 218);
frame.getContentPane().add(TextAr);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmOpen = new JMenuItem("Open");
mnFile.add(mntmOpen);
performer performance = new performer();
mntmOpen.addActionListener(performance);
JMenuItem mntmSaveAs = new JMenuItem("Save as");
mnFile.add(mntmSaveAs);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
mntmSaveAs.addActionListener(performance);
}
public class performer implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getActionCommand().equals("Save as")){
chooser.setDialogTitle("Choose where to save the file");
FileNameExtensionFilter txtfilter = new FileNameExtensionFilter("Text File", "txt");
chooser.addChoosableFileFilter(txtfilter);
int val = chooser.showSaveDialog(null);
if(val == JFileChooser.APPROVE_OPTION){
try(FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt")){
fw.write(TextAr.getText());
}catch (IOException e){
e.printStackTrace();
}
}
}else if (event.getActionCommand().equals("Open")){
chooser.setDialogTitle("Choose a text file");
FileNameExtensionFilter textfilter = new FileNameExtensionFilter("Text Files", "txt");
chooser.addChoosableFileFilter(textfilter);
chooser.setAcceptAllFileFilterUsed(false);
int returnval = chooser.showOpenDialog(null);
if(returnval == JFileChooser.APPROVE_OPTION){
try(BufferedReader a = new BufferedReader(new FileReader(chooser.getSelectedFile().getPath()))){
StringBuilder str = new StringBuilder();
String line;
while((line = a.readLine()) != null){
str.append(line);
str.append("\n");
}
TextAr.append(str.toString());
}catch (IOException e){
e.printStackTrace();
}
}else if(event.getActionCommand().equals("Exit")){
System.exit(0);
}
}
}
}
}
I have to mention that I use the ECLIPSE IDE with WindowBuilder.I tried to fix the problem by repositioning the
else if(event.getActionCommand().equals("Exit")){
System.exit(0);
}
to different locations around the code.
On your mntmExit you should attach action listener in order to get action.
You can do that on several ways, but here is the one:
/** exit menu event */
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0); //close the application
}
});
You don't have
mntmExit.addActionListener(performance);
anywhere.
Edit: that was problem one. There appears to be another one.
The other problem is the last else if statement currently is in the wrong place. You need to move it out one more block.

JMenu Item Action Listener is not being detected

I am making a library database for a school project and am having a little trouble with my menu. So the main problem is that in the Action Listener method when I write
(e.getSource()==m1Frame1)
my program does not detect the menu item and gives me an error. I have looked at multiple tutorials etc. online but cannot seem to find any way to fix it and make it so that if a specific item is clicked a specific action occurs. Any help/resolution regarding this issue would be much appreciated.
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.*;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import java.awt.event.*;
import javax.swing.Icon;
import java.awt.*;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Color;
public class m1 extends JFrame {
JPanel pane = new JPanel();
JFrame a = new JFrame("Main Frame");
JFrame b = new JFrame("Sub Frame");
JButton checkOutButton = new JButton("check");
JButton returnButton = new JButton("return");
JMenu mb2 = new JMenu("Books");
// mb2.setForeground(Color.white);
JMenu open = new JMenu("Students");
// open.setForeground(Color.white);
public m1() {
JMenuBar mb;
mb = new JMenuBar() {
public void paintComponent(Graphics g) {
g.drawImage(Toolkit.getDefaultToolkit().getImage("G:"), 0, 0, this);
}
};
setSize(400, 400);
setBackground(Color.BLACK);
setTitle("Screen 2");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb.add(open);
JMenuItem m1Frame1 = new JMenuItem("Create");
JMenuItem m1Frame2 = new JMenuItem("Delete");
JMenu m1Frame3 = new JMenu("Look-Up");
JMenuItem m1Frame4 = new JMenuItem("Check Fine");
JMenuItem m1Frame5 = new JMenuItem("Check Borrowed Books");
JMenuItem subM1 = new JMenuItem("Name");
JMenuItem subM2 = new JMenuItem("Student #");
open.add(m1Frame1);
open.add(m1Frame2);
open.add(m1Frame3);
open.add(m1Frame4);
open.add(m1Frame5);
m1Frame3.add(subM1);
m1Frame3.add(subM2);
mb.add(mb2);
JMenuItem m2Frame1 = new JMenuItem("Create");
JMenuItem m2Frame2 = new JMenuItem("Delete");
JMenu m2Frame3 = new JMenu("Look-Up");
JMenuItem subB1 = new JMenuItem("Title");
JMenuItem subB2 = new JMenuItem("Author");
JMenuItem subB3 = new JMenuItem("Category");
JMenuItem subB4 = new JMenuItem("ISBN");
JMenuItem m2Frame4 = new JMenuItem("Compare Star Rating");
JMenuItem m2Frame5 = new JMenuItem("Check If Checked Out");
JMenuItem m2Frame6 = new JMenuItem("Lost Book");
mb2.add(m2Frame1);
mb2.add(m2Frame2);
mb2.add(m2Frame3);
mb2.add(m2Frame4);
mb2.add(m2Frame5);
mb2.add(m2Frame6);
m2Frame3.add(subB1);
m2Frame3.add(subB2);
m2Frame3.add(subB3);
m2Frame3.add(subB4);
a.setJMenuBar(mb);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setSize(1280, 720);
a.setVisible(true);
b.setSize(600, 400);
m handler = new m();
pane.add(checkOutButton);
pane.add(returnButton);
add(pane);
checkOutButton.setVisible(false);
returnButton.setVisible(false);
checkOutButton.setBounds(60, 440, 220, 30);
returnButton.setBounds(60, 404, 100, 50);
checkOutButton.addActionListener(handler);
returnButton.addActionListener(handler);
}
public class m implements ActionListener, ItemListener {
public void actionPerformed(ActionEvent e) {
(e.getSource() == m1Frame1) {
a.setVisible(false);
setVisible(true);
checkOutButton.setVisible(true);
returnButton.setVisible(true);
}
}
public void itemStateChanged(ItemEvent e) {
}
}
public static void main(String[] args) {
m1 aa = new m1();
}
}
Ok, there are a few issues with your code, but I'll go over the two specifics that answer your question:
1) You're not adding your action listener to any of your MenuItems in your code. When I added your handler to the MenuItems using addActionListener(handler); It started triggering.
2) You're adding handler as the actionListener to two buttons that are invisible (and you've got other layout issues)

How to configure JComboBox not to select FIRST element when created?

Problem:
Update:
From the Java SE 6 API:
public JComboBox() Creates a JComboBox
with a default data model. The default
data model is an empty list of
objects. Use addItem to add items. By
default the first item in the data
model becomes selected.
So I changed to JComboBox(model) as the API says:
public JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes its
items from an existing ComboBoxModel.
Since the ComboBoxModel is provided, a
combo box created using this
constructor does not create a default
combo box model and may impact how the
insert, remove and add methods behave.
I tried the following:
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.setSelectedItem(null);
suggestionComboBox = new JComboBox(model);
suggestionComboBox.setModel(model);
But could not get it to work, the first item is still being selected.
Anyone that can come up with a working example would be very much appreciated.
Old part of the post:
I am using JComboBox, and tried using setSelectionIndex(-1) in my code (this code is placed in caretInvoke())
suggestionComboBox.removeAllItems();
for (int i = 0; i < suggestions.length; i++) {
suggestionComboBox.addItem(suggestions[i]);
}
suggestionComboBox.setSelectedIndex(-1);
suggestionComboBox.setEnabled(true);
This is the initial setting when it was added to a pane:
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
suggestionComboBox.addActionListener(new SuggestionComboBoxListener());
When the caretInvoke triggers the ComboBox initialisation, even before the user selects an element, the actionPerformed is already triggered (I tried a JOptionPane here):
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo1.png
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo2.png
http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo3.png
The problem is: My program autoinserts the selected text when the user selects an element from the ComboBox. So without the user selecting anything, it is automatically inserted already.
How can I overcome the problem in this situation? Thanks.
Here is my SSCCE: (finally)
package components;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
public class Temp extends JFrame {
JTextPane textPane;
AbstractDocument doc;
JTextArea changeLog;
String newline = "\n";
private JComboBox suggestionComboBox;
private JPanel suggestionPanel;
private JLabel suggestionLabel;
private JButton openButton, saveButton, aboutButton;
public Temp() {
super("Snort Ruleset IDE");
//Create the text pane and configure it.
textPane = new JTextPane();
textPane.setCaretPosition(0);
textPane.setMargin(new Insets(5, 5, 5, 5));
StyledDocument styledDoc = textPane.getStyledDocument();
if (styledDoc instanceof AbstractDocument) {
doc = (AbstractDocument) styledDoc;
//doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));
} else {
System.err.println("Text pane's document isn't an AbstractDocument!");
System.exit(-1);
}
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(700, 350));
//Create the text area for the status log and configure it.
//changeLog = new JTextArea(10, 30);
//changeLog.setEditable(false);
//JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
//Create a JPanel for the suggestion area
suggestionPanel = new JPanel(new BorderLayout());
suggestionPanel.setVisible(true);
suggestionLabel = new JLabel("Suggestion is not active at the moment.");
suggestionLabel.setPreferredSize(new Dimension(100, 50));
suggestionLabel.setMaximumSize(new Dimension(100, 50));
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
//suggestionComboBox.addActionListener(new SuggestionComboBoxListener());
suggestionComboBox.addItemListener(new SuggestionComboBoxListener());
//suggestionComboBox.setSelectedIndex(-1);
//add the suggestionLabel and suggestionComboBox to pane
suggestionPanel.add(suggestionLabel, BorderLayout.CENTER);
suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);
JScrollPane sp = new JScrollPane(suggestionPanel);
JScrollPane scrollPaneForSuggestion = new JScrollPane(suggestionPanel);
//Create a split pane for the change log and the text area.
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
scrollPane, scrollPaneForSuggestion);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(1.0);
//Disables the moving of divider
splitPane.setEnabled(false);
//splitPane.setDividerLocation(splitPane.getHeight());
//splitPane.setPreferredSize(new Dimension(640,400));
//Create the status area.
JPanel statusPane = new JPanel(new GridLayout(1, 1));
CaretListenerLabel caretListenerLabel =
new CaretListenerLabel("Status: Ready");
statusPane.add(caretListenerLabel);
//Create the toolbar
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
openButton = new JButton("Open Snort Ruleset");
toolBar.add(openButton);
saveButton = new JButton("Save Ruleset");
toolBar.add(saveButton);
toolBar.addSeparator();
aboutButton = new JButton("About");
toolBar.add(aboutButton);
//Add the components.
getContentPane().add(toolBar, BorderLayout.PAGE_START);
getContentPane().add(splitPane, BorderLayout.CENTER);
getContentPane().add(statusPane, BorderLayout.PAGE_END);
JMenu editMenu = createEditMenu();
JMenu styleMenu = createStyleMenu();
JMenuBar mb = new JMenuBar();
mb.add(editMenu);
mb.add(styleMenu);
setJMenuBar(mb);
//Put the initial text into the text pane.
//initDocument();
textPane.setCaretPosition(0);
//Start watching for undoable edits and caret changes.
textPane.addCaretListener(caretListenerLabel);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textPane.requestFocusInWindow();
}
});
}
//This listens for and reports caret movements.
protected class CaretListenerLabel extends JLabel
implements CaretListener {
public CaretListenerLabel(String label) {
super(label);
}
//Might not be invoked from the event dispatch thread.
public void caretUpdate(CaretEvent e) {
caretInvoke(e.getDot(), e.getMark());
}
protected void caretInvoke(final int dot, final int mark) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Rectangle caretCoords = textPane.modelToView(dot);
//Find suggestion
suggestionComboBox.removeAllItems();
for (int i = 0; i < 5; i++) {
suggestionComboBox.addItem(Integer.toString(i));
}
//suggestionComboBox.setSelectedItem(null);
suggestionComboBox.setEnabled(true);
suggestionLabel.setText("The following keywords are normally used as well. Click to use keyword(s). ");
//changeLog.setText("The following keywords are suggested to be used together: " + str);
} catch (BadLocationException ble) {
setText("caret: text position: " + dot + newline);
System.out.println("Bad Location Exception");
}
}
});
}
}
public class SuggestionComboBoxListener implements ItemListener {
//public void actionPerformed(ActionEvent e) {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox cb = (JComboBox)e.getSource();
String selection = (String) cb.getSelectedItem();
JOptionPane.showMessageDialog(null, "Item is selected", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
}
/*
* Menu Creation
*/
//Create the edit menu.
protected JMenu createEditMenu() {
JMenu menu = new JMenu("Edit");
return menu;
}
protected JMenu createStyleMenu() {
JMenu menu = new JMenu("Style");
return menu;
}
private static void createAndShowGUI() {
//Create and set up the window.
final Temp frame = new Temp();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//The standard main method.
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
You need to remove the ItemListener before you make any changes to the combo-box and add it back when you are done.
Something like this:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Suggestions {
private JFrame frame;
private JTextPane textPane;
private JComboBox suggestionComboBox;
private SuggestionComboBoxListener selectionListener;
public Suggestions() {
frame = new JFrame("Snort Ruleset IDE");
textPane = new JTextPane();
textPane.setCaretPosition(0);
textPane.setMargin(new Insets(5, 5, 5, 5));
textPane.addCaretListener(new SuggestionCaretListener());
JScrollPane textEntryScrollPane = new JScrollPane(textPane);
textEntryScrollPane.setPreferredSize(new Dimension(300, 400));
selectionListener = new SuggestionComboBoxListener(frame);
suggestionComboBox = new JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(new Dimension(25, 25));
suggestionComboBox.addItemListener(selectionListener);
JPanel suggestionPanel = new JPanel(new BorderLayout());
suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);
frame.getContentPane().add(textEntryScrollPane, BorderLayout.NORTH);
frame.getContentPane().add(suggestionPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private final class SuggestionCaretListener implements CaretListener {
#Override
public void caretUpdate(CaretEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generateSuggestions();
}
});
}
}
public static final class SuggestionComboBoxListener implements ItemListener {
Component parent;
public SuggestionComboBoxListener(Component parent) {
this.parent = parent;
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox cb = (JComboBox) e.getSource();
String selection = (String) cb.getSelectedItem();
JOptionPane.showMessageDialog(parent, "The selected item is: " + selection, "Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
void generateSuggestions() {
suggestionComboBox.removeItemListener(selectionListener);
suggestionComboBox.removeAllItems();
for (int i = 0; i < 5; i++) {
suggestionComboBox.addItem(Integer.toString(i));
}
suggestionComboBox.setEnabled(true);
suggestionComboBox.addItemListener(selectionListener);
}
public static void main(String[] args) {
new Suggestions();
}
}
BTW, what you posted is not an SSCCE it is a dump of your code. An SSCCE should only have enough code to reproduce the issue you are experiencing.
use
setSelectedItem(null);
Please try with ItemListener instead of ActionListener.
if You want that after 1st entry you made and immediately you combox is empty then just write down the under mentioned code which is:
jComboBox1.setSelectedIndex(0);
and your combox will reset Automatically

Categories

Resources