JList doesn't show on JScrollPane - java

I'm trying to open a text file using JFilechooser and put strings in JList. I think all the strings go into the list but I don't know why the strings don't appear on JScrollPane. Is there any problem with grouplayout? i don't know what to change..
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.List;
public class WordFinder extends JFrame implements ActionListener {
private WordList words = new WordList();
private JScrollPane scroll;
private JLabel label;
private JLabel word;
private JTextField textArea;
private JButton button;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem, menuItem2;
private JFileChooser fc;
private JList list;
static private final String newline = "\n";
private int lineCount;
public WordFinder() {
super("Word Finder");
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
menuBar = new JMenuBar();
menu = new JMenu("File");
menuBar.add(menu);
menuItem = new JMenuItem("Open...");
menuItem.addActionListener(this);
menuItem2 = new JMenuItem("Exit");
menuItem2.addActionListener(this);
menu.add(menuItem);
menu.add(menuItem2);
setJMenuBar(menuBar);
label = new JLabel("Find: ");
word = new JLabel(lineCount + " words total");
textArea = new JTextField();
textArea.setEditable(true);
textArea.setPreferredSize(new Dimension(200, 20));
button = new JButton("Clear");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textArea.setText("");
}
});
scroll = makeListView();
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setPreferredSize(new Dimension(200, 230));
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(label)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(textArea)
.addComponent(word)
.addComponent(scroll))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(button)));
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(label)
.addComponent(textArea)
.addComponent(button))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(word))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
.addComponent(scroll));
setVisible(true);
pack();
// call System.exit() when user closes the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JScrollPane makeListView() {
// String[] labels = {"1", "2", "3"};
// list = new JList(labels);
JScrollPane listScroller = new JScrollPane(list);
return listScroller;
}
private void updateListView(DefaultListModel listModel) {
list = new JList(listModel);
scroll = new JScrollPane(list);
}
public void actionPerformed(ActionEvent e) {
DefaultListModel listModel = new DefaultListModel();
if (e.getSource() == menuItem) {
int returnVal = fc.showOpenDialog(WordFinder.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String fileName = file.getAbsolutePath();
try {
FileReader files = new FileReader(fileName);
BufferedReader br = new BufferedReader(files);
String str;
while((str = br.readLine()) != null) {
listModel.addElement(str);
//System.out.println(str);
lineCount++;
}
System.out.println(lineCount);
updateListView(listModel);
br.close();
} catch (Exception ex) {
ex.printStackTrace(System.out);
System.out.println("can't read file");
}
System.out.println("Opening: " + file.getName() + newline);
}
} else if (e.getSource() == menuItem2) {
setVisible(false);
dispose();
}
}
/**
* Main method. Makes and displays a WordFinder window.
* #param args Command-line arguments. Ignored.
*/
public static void main(String[] args) {
// In general, Swing objects should only be accessed from
// the event-handling thread -- not from the main thread
// or other threads you create yourself. SwingUtilities.invokeLater()
// is a standard idiom for switching to the event-handling thread.
SwingUtilities.invokeLater(new Runnable() {
public void run () {
// Make and display the WordFinder window.
new WordFinder();
}
});
}
}

When you call makeListView the JList is null as it hasn't been initialized yet...thus, you are basically saying scroll = new JScrollPane(null);...which isn't particularly helpful...
Next, when you call updateListView, you create a new instance of the JList and JScrollPane and do nothing with them...
private void updateListView(DefaultListModel listModel) {
list = new JList(listModel);
scroll = new JScrollPane(list);
}
so they will never be displayed on the screen...
To rectify this, you will need to make some modifications...
Create an instance of the JList and assign it to the instance field list, before you create the JScrollPane
Instead of creating new instances of the list and scroll, simply use JList#setModel
You may also like to have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
With JList, you affect the size of the JScrollPane through the use of JList#setVisibleRowCount and JList#setPrototypeCellValue

Related

Jtoolbar isn't displaying

I am new to stackoverflow and to learning Java. I am creating an application for one of my courses in college and we have to create a text editor with a menu bar and a toolbar. I have been able to get the menubar to work, but the toolbar isn't displaying even though it isn't breaking in code. Would anyone know what this is happening?
import com.sun.deploy.ui.AboutDialog;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import javafx.scene.control.ToolBar;
import javax.swing.JToolBar;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
#SuppressWarnings("serial")
public class DoesThisWork extends JFrame implements ActionListener {
public static void main(String[] args) {
new DoesThisWork();
}
//============================================
// FIELDS
//============================================
// Menus
private JMenu fileMenu;
private JMenu editMenu;
private JMenu formatMenu;
private JMenu helpMenu;
private JMenuItem newFile, openFile, saveFile, saveAsFile, pageSetup, printFile, exit;
private JMenuItem undoEdit, redoEdit, selectAll, copy, paste, cut;
private JMenu fontColor, fontSize;
private JMenuItem about;
private JMenuItem subColorRed, subColorBlue, subColorGreen, subColorBlack;
private JMenuItem subTimes, subArial, subCourier, subVerdana;
//Toolbar Buttons
private JButton red;
private JButton blue;
private JButton green;
private JButton black;
// private JButton newFile, openFile, saveFile, saveAsFile, pageSetup, printFile, exit;
// private JMenuItem undoEdit, redoEdit, selectAll, copy, paste, cut;
// private JMenu fontColor, fontSize;
// private JMenuItem about;
// private JMenuItem subColorRed, subColorBlue, subColorGreen, subColorBlack;
// private JMenuItem sub8, sub10, sub12, sub50;
// Window
private JFrame editorWindow;
// Text Area
private Border textBorder;
private JScrollPane scroll;
private JTextArea textArea;
private Font textFont;
// Window
private JFrame window;
// Printing
private PrinterJob job;
public PageFormat format;
// Is File Saved/Opened
private boolean opened = false;
private boolean saved = false;
// Record Open File for quick saving
private File openedFile;
// Undo manager for managing the storage of the undos
// so that the can be redone if requested
private UndoManager undo;
//Toolbar
private JToolBar toolBar;
//============================================
// CONSTRUCTOR
//============================================
public DoesThisWork() {
super("Text Editor");
// Create Menus
fileMenu();
editMenu();
formatMenu();
helpMenu();
// Create Text Area
createTextArea();
// Create Undo Manager for managing undo/redo commands
undoMan();
// Create Window
createEditorWindow();
// Create Toolbar
createToolBar();
}
private JFrame createEditorWindow() {
editorWindow = new JFrame("Text Editor");
editorWindow.setVisible(true);
editorWindow.setExtendedState(Frame.MAXIMIZED_BOTH);
editorWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create Menu Bar
editorWindow.setJMenuBar(createMenuBar());
editorWindow.add(scroll, BorderLayout.CENTER);
editorWindow.pack();
// Centers application on screen
editorWindow.setLocationRelativeTo(null);
// Create ToolBar
//editorWindow.add(toolBar, BorderLayout.NORTH);
return editorWindow;
}
private JTextArea createTextArea() {
//textBorder = BorderFactory.createBevelBorder(0, Color.BLACK, Color.BLACK);
textArea = new JTextArea(30, 50);
textArea.setEditable(true);
textArea.setBorder(BorderFactory.createCompoundBorder(textBorder, BorderFactory.createEmptyBorder(2, 5, 0, 0)));
textFont = new Font("Verdana", 0, 14);
textArea.setFont(textFont);
scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
return textArea;
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(formatMenu);
menuBar.add(helpMenu);
return menuBar;
}
private JToolBar createToolBar(){
toolBar = new JToolBar();
toolBar.setFloatable(true);
red = new JButton("Red");
red.setToolTipText("Click here to change font color to Red");
blue = new JButton("Blue");
blue.setToolTipText("Click here to change font color to Blue");
green = new JButton("Green");
green.setToolTipText("Click here to change font color to Green");
black = new JButton("Black");
black.setToolTipText("Click here to change font color to Black");
//add(toolBar, BorderLayout.SOUTH);
// Toolbar Color Buttons
toolBar.add(red);
toolBar.add(blue);
toolBar.add(green);
toolBar.add(black);
add(toolBar, BorderLayout.WEST);
//ToolBar tb = new ToolBar();
toolBar.setVisible(true);
return toolBar;
}
private UndoManager undoMan() {
// Listener for undo and redo functions to document
undo = new UndoManager();
textArea.getDocument().addUndoableEditListener(new UndoableEditListener() {
#Override
public void undoableEditHappened(UndoableEditEvent e) {
undo.addEdit(e.getEdit());
}
});
return undo;
}
private void fileMenu() {
// Create File Menu
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.setPreferredSize(new Dimension(40, 20));
// Add file menu items
newFile = new JMenuItem("New");
newFile.setMnemonic(KeyEvent.VK_N);
newFile.addActionListener(this);
newFile.setPreferredSize(new Dimension(100, 20));
newFile.setEnabled(true);
openFile = new JMenuItem("Open...");
openFile.setMnemonic(KeyEvent.VK_O);
openFile.addActionListener(this);
openFile.setPreferredSize(new Dimension(100, 20));
openFile.setEnabled(true);
saveFile = new JMenuItem("Save");
saveFile.setMnemonic(KeyEvent.VK_S);
saveFile.addActionListener(this);
saveFile.setPreferredSize(new Dimension(100, 20));
saveFile.setEnabled(true);
saveAsFile = new JMenuItem("Save As...");
saveAsFile.setMnemonic(KeyEvent.VK_A);
saveAsFile.addActionListener(this);
saveAsFile.setPreferredSize(new Dimension(100, 20));
saveAsFile.setEnabled(true);
pageSetup = new JMenuItem("Page Setup...");
pageSetup.setMnemonic(KeyEvent.VK_U);
pageSetup.addActionListener(this);
pageSetup.setPreferredSize(new Dimension(100, 20));
pageSetup.setEnabled(true);
printFile = new JMenuItem("Print...");
printFile.setMnemonic(KeyEvent.VK_P);
printFile.addActionListener(this);
printFile.setPreferredSize(new Dimension(100, 20));
printFile.setEnabled(true);
exit = new JMenuItem("Exit");
exit.setMnemonic(KeyEvent.VK_E);
exit.addActionListener(this);
exit.setPreferredSize(new Dimension(100, 20));
exit.setEnabled(true);
// Add items to menu
fileMenu.add(newFile);
fileMenu.add(openFile);
fileMenu.add(saveFile);
fileMenu.add(saveAsFile);
fileMenu.add(pageSetup);
fileMenu.add(printFile);
fileMenu.add(exit);
}
private void editMenu() {
editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
editMenu.setPreferredSize(new Dimension(40, 20));
// Add file menu items
undoEdit = new JMenuItem("Undo");
undoEdit.setMnemonic(KeyEvent.VK_U);
undoEdit.addActionListener(this);
undoEdit.setPreferredSize(new Dimension(100, 20));
undoEdit.setEnabled(true);
redoEdit = new JMenuItem("Redo");
redoEdit.setMnemonic(KeyEvent.VK_R);
redoEdit.addActionListener(this);
redoEdit.setPreferredSize(new Dimension(100, 20));
redoEdit.setEnabled(true);
selectAll = new JMenuItem("Select All");
selectAll.setMnemonic(KeyEvent.VK_S);
selectAll.addActionListener(this);
selectAll.setPreferredSize(new Dimension(100, 20));
selectAll.setEnabled(true);
copy = new JMenuItem("Copy");
copy.setMnemonic(KeyEvent.VK_C);
copy.addActionListener(this);
copy.setPreferredSize(new Dimension(100, 20));
copy.setEnabled(true);
paste = new JMenuItem("Paste");
paste.setMnemonic(KeyEvent.VK_P);
paste.addActionListener(this);
paste.setPreferredSize(new Dimension(100, 20));
paste.setEnabled(true);
cut = new JMenuItem("Cut");
cut.setMnemonic(KeyEvent.VK_T);
cut.addActionListener(this);
cut.setPreferredSize(new Dimension(100, 20));
cut.setEnabled(true);
// Add items to menu
editMenu.add(undoEdit);
editMenu.add(redoEdit);
editMenu.add(selectAll);
editMenu.add(copy);
editMenu.add(paste);
editMenu.add(cut);
}
private void formatMenu() {
formatMenu = new JMenu("Format");
formatMenu.setMnemonic(KeyEvent.VK_O);
formatMenu.setPreferredSize(new Dimension(60, 20));
// Add file menu items
fontColor= new JMenu("Font Color");
fontColor.setMnemonic(KeyEvent.VK_C);
fontColor.addActionListener(this);
fontColor.setPreferredSize(new Dimension(100, 20));
fontColor.setEnabled(true);
fontSize= new JMenu("Font Style");
fontSize.setMnemonic(KeyEvent.VK_S);
fontSize.addActionListener(this);
fontSize.setPreferredSize(new Dimension(100, 20));
fontSize.setEnabled(true);
// Add submenu items
subColorRed= new JMenuItem("Red");
subColorRed.setMnemonic(KeyEvent.VK_R);
subColorRed.addActionListener(this);
subColorRed.setPreferredSize(new Dimension(100, 20));
subColorRed.setEnabled(true);
subColorBlue= new JMenuItem("Blue");
subColorBlue.setMnemonic(KeyEvent.VK_B);
subColorBlue.addActionListener(this);
subColorBlue.setPreferredSize(new Dimension(100, 20));
subColorBlue.setEnabled(true);
subColorGreen= new JMenuItem("Green");
subColorGreen.setMnemonic(KeyEvent.VK_G);
subColorGreen.addActionListener(this);
subColorGreen.setPreferredSize(new Dimension(100, 20));
subColorGreen.setEnabled(true);
subColorBlack= new JMenuItem("Black");
subColorBlack.setMnemonic(KeyEvent.VK_K);
subColorBlack.addActionListener(this);
subColorBlack.setPreferredSize(new Dimension(100, 20));
subColorBlack.setEnabled(true);
subTimes= new JMenuItem("Times New Roman");
subTimes.setMnemonic(KeyEvent.VK_T);
subTimes.addActionListener(this);
subTimes.setPreferredSize(new Dimension(125, 20));
subTimes.setEnabled(true);
subArial= new JMenuItem("Arial");
subArial.setMnemonic(KeyEvent.VK_A);
subArial.addActionListener(this);
subArial.setPreferredSize(new Dimension(100, 20));
subArial.setEnabled(true);
subCourier= new JMenuItem("Courier");
subCourier.setMnemonic(KeyEvent.VK_C);
subCourier.addActionListener(this);
subCourier.setPreferredSize(new Dimension(100, 20));
subCourier.setEnabled(true);
subVerdana= new JMenuItem("Verdana");
subVerdana.setMnemonic(KeyEvent.VK_V);
subVerdana.addActionListener(this);
subVerdana.setPreferredSize(new Dimension(100, 20));
subVerdana.setEnabled(true);
// Add items to menu
formatMenu.add(fontColor);
fontColor.add(subColorRed);
fontColor.add(subColorBlue);
fontColor.add(subColorGreen);
fontColor.add(subColorBlack);
formatMenu.add(fontSize);
fontSize.add(subTimes);
fontSize.add(subArial);
fontSize.add(subCourier);
fontSize.add(subVerdana);
}
private void helpMenu() {
helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.setPreferredSize(new Dimension(40, 20));
// Add file menu items
about = new JMenuItem("About");
about.setMnemonic(KeyEvent.VK_A);
about.addActionListener(this);
about.setPreferredSize(new Dimension(100, 20));
about.setEnabled(true);
// Add items to menu
helpMenu.add(about);
}
// Method for saving files - Removes duplication of code
private void saveFile(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
saved = true;
window.setTitle("Text Editor - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
// Method for quick saving files
private void quickSave(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
} catch (IOException err) {
err.printStackTrace();
}
}
// Method for opening files
private void openingFiles(File filename) {
try {
openedFile = filename;
FileReader reader = new FileReader(filename);
textArea.read(reader, null);
opened = true;
window.setTitle("Text Editor - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == newFile) {
new DoesThisWork();
} else if(event.getSource() == openFile) {
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File file = open.getSelectedFile();
openingFiles(file);
} else if(event.getSource() == saveFile) {
JFileChooser save = new JFileChooser();
File filename = save.getSelectedFile();
if(opened == false && saved == false) {
save.showSaveDialog(null);
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(saveFile, "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else {
quickSave(openedFile);
}
} else if(event.getSource() == saveAsFile) {
JFileChooser saveAs = new JFileChooser();
saveAs.showSaveDialog(null);
File filename = saveAs.getSelectedFile();
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(saveAsFile, "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else if(event.getSource() == pageSetup) {
job = PrinterJob.getPrinterJob();
format = job.pageDialog(job.defaultPage());
} else if(event.getSource() == printFile) {
job = PrinterJob.getPrinterJob();
if(job.printDialog()) {
try {
job.print();
} catch (PrinterException err) {
err.printStackTrace();
}
}
} else if(event.getSource() == exit) {
System.exit(0);
} else if(event.getSource() == undoEdit) {
try {
undo.undo();
} catch(CannotUndoException cu) {
cu.printStackTrace();
}
} else if(event.getSource() == redoEdit) {
try {
undo.redo();
} catch(CannotUndoException cur) {
cur.printStackTrace();
}
} else if(event.getSource() == selectAll) {
textArea.selectAll();
} else if(event.getSource() == copy) {
textArea.copy();
} else if(event.getSource() == paste) {
textArea.paste();
} else if(event.getSource() == cut) {
textArea.cut();
} else if(event.getSource() == about){
//createAboutFrame();
JLabel About = new JLabel();
About.setText("<html>"
+ "<p>This is a custom Text Editor</p>"
+ "<p>Built By Todd Eaton, October 2015</p>"
+ "<p>Brandeis University</p>"
+ "<p>Master of Software Engineering Candidate</p>");
JOptionPane.showMessageDialog(null, About, "About Text Editor", JOptionPane.INFORMATION_MESSAGE);
} else if(event.getSource() == subColorRed){
textArea.setForeground(Color.RED);
} else if(event.getSource() == subColorBlue) {
textArea.setForeground(Color.BLUE);
} else if(event.getSource() == subColorGreen) {
textArea.setForeground(Color.GREEN);
} else if(event.getSource() == subColorBlack) {
textArea.setForeground(Color.BLACK);
} else if(event.getSource() == subTimes){
textFont = new Font("Times New Roman", 0, 14);
textArea.setFont(textFont);
} else if(event.getSource() == subArial){
textFont = new Font("Arial", 0, 14);
textArea.setFont(textFont);
} else if(event.getSource() == subCourier){
textFont = new Font("Courier", 0, 14);
textArea.setFont(textFont);
} else if(event.getSource() == subVerdana){
textFont = new Font("Verdana", 0, 14);
textArea.setFont(textFont);
}
}
//============================================
// GETTERS AND SETTERS
//============================================
public JTextArea getTextArea() {
return textArea;
}
public void setTextArea(JTextArea text) {
textArea = text;
}
}
The below comment
//editorWindow.add(toolBar, BorderLayout.NORTH);
Should be replaced with
editorWindow.add(createToolBar(), BorderLayout.NORTH);
To actually create a toolbar and add it to the UI.
You're adding your JToolBar to the instance of JFrame created by DoesThisWork, but this is never actually shown on the screen.
Start by getting rid of extends JFrame and rely on the instance of JFrame assigned to editorWindow
Then in your createEditorWindow method add
editorWindow.add(createToolBar(), BorderLayout.WEST);
(You'll need to fix a couple other compiler errors generated by removing extends JFrame, but they should be pretty obvious)
//editorWindow.add(toolBar, BorderLayout.NORTH);
You don't add the toolbar to the frame.
Do you realize you have two JFrames in your code? Your class extends JFrame and then in your code your also create another JFrame. Sometimes your code just used the add(...) method to add components to the class. And then sometimes your code uses editorWindow.add(...) to add components to the frame.
Your code is confusing because you have two frames. Don't extend JFrame.
Start with the MenuLookDemo code from the Swing tutorial on How to Make Menus. It will show you how to better structure your code so that you don't have two frames. The "create" methods should actually return components so they can be added to the frame.

How would I fill my TextFields after I select an item from JList

i'm having some trouble with a homework problem, and still trying to wrap my head around GUI logically. I have created all my text fields (contactType, name, address, city, state, etc...) and have created an actionListener to populate my JList with names when I click open from the JMenu. I'm running into trouble filling in the appropriate text fields when I select the name from the list. I tried to just print out to console to see if it would print out at least the name, but that's not even working. Any help would be great, thanks.
Here's some of my code so far:
public class AddressBookGUI extends JFrame
{
private final int WIDTH = 450;
private final int HEIGHT = 300;
private JLabel currentlySelected;
private JTextField contactTypeTextField;
private JTextField nameTextField;
private JTextField streetAddressTextField;
private JTextField cityTextField;
private JTextField stateTextField;
private JTextField zipTextField;
private JTextField phoneTextField;
private JTextField emailTextField;
private JTextField photoTextField;
private JList nameList ;
private DefaultListModel model;
private JTextArea statusTextArea;
private AddressBook addressBook;
private JButton addButton;
private JButton editButton;
private JButton sortByZipButton;
private JMenuItem addItem;
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem exitItem;
private JMenuItem editContactItem;
private JMenuItem aboutItem;
private JMenuItem deleteItem;
private JComboBox<String> jComboStates;
private JComboBox <Enum> jComboContactType;
private String [] readStates()
{
ArrayList<String> array = new ArrayList<>();
try
{
FileInputStream fStream = new FileInputStream ("States.txt");
BufferedReader buffer = new BufferedReader (new InputStreamReader (fStream));
String strLine;
while ((strLine = buffer.readLine()) != null)
{
String line = buffer.readLine();
String [] state = line.split ("\n");
array.add(strLine);
}
buffer.close();
}
catch (Exception e)
{
}
return array.toArray(new String[array.size()]);
}
private ArrayList<String> readContacts()
{
File cFile = new File ("Contacts.txt");
BufferedReader buffer = null;
ArrayList <String> contact = new ArrayList<String>();
try
{
buffer = new BufferedReader (new FileReader (cFile));
String text;
String sep;
while ((sep = buffer.readLine()) != null)
{
String [] name = sep.split (",");
text = name[1];
contact.add(text);
}
}
catch (FileNotFoundException e)
{
System.out.print ("error");
}
catch (IOException k)
{
System.out.print ("error);
}
return contact;
}
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu ("File");
openItem = new JMenuItem ("Open...");
fileMenu.add (openItem);
fileMenu.addSeparator();
saveItem = new JMenuItem ("Save...");
fileMenu.add (saveItem);
fileMenu.addSeparator();
exitItem = new JMenuItem ("Exit");
fileMenu.add (exitItem);
JMenu editMenu = new JMenu ("Edit");
editContactItem = new JMenuItem ("Edit Contact");
editMenu.add (editContactItem);
addItem = new JMenuItem ("Add Contact");
editMenu.add (addItem);
deleteItem = new JMenuItem ("Delete Contact");
editMenu.add (deleteItem);
JMenu helpMenu = new JMenu ("Help");
aboutItem = new JMenuItem ("About");
helpMenu.add(aboutItem);
menuBar.add (fileMenu);
menuBar.add (editMenu);
menuBar.add (helpMenu);
setJMenuBar (menuBar);
//code that creates new text fields for all attributes
//code that sets textfields to uneditable
JPanel topPanel = new JPanel()
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.add (currentlySelected, BorderLayout.CENTER);
leftPanel.add (new JScrollPane(), BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
JPanel infoPanel = new JPanel (new BorderLayout());
GridLayout layout = new GridLayout (9,1);
JPanel labelsPanel = new JPanel (layout);
JPanel valuesPanel = new JPanel (layout);
// code that added lables and values to panel
infoPanel.add (labelsPanel, BorderLayout.WEST);
infoPanel.add (valuesPanel, BorderLayout.CENTER);
centerPanel.add (infoPanel);
setLayout (new BorderLayout());
add (topPanel, BorderLayout.NORTH);
add (leftPanel, BorderLayout.WEST);
add (centerPanel, BorderLayout.CENTER);
addressBook = new AddressBook();
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
openItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
readContacts();
for (String name :readContacts())
{
model.addElement(name);
}
nameList = new JList (model);
add(nameList);
nameList.setVisibleRowCount(10);
nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
nameList.setFixedCellHeight (20);
nameList.setFixedCellWidth (130);
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(nameList), BorderLayout.NORTH);
add (left, BorderLayout.WEST);
nameList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
}
});
editContactItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
nameTextField.setEditable (true);
streetAddressTextField.setEditable (true);
cityTextField.setEditable (true);
jComboStates.setEditable (true);
zipTextField.setEditable (true);
phoneTextField.setEditable (true);
emailTextField.setEditable (true);
photoTextField.setEditable (true);
}
});
saveItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
addressBook.Save ( );
}
});
nameList = new JList ();
nameList.addListSelectionListener (new ListSelectionListener()
{
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting ( ) == false)
{
List <String> string = nameList.getSelectedValuesList();
System.out.print (string);
}
}
});
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = nameList.locationToIndex(e.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
};
nameList.addMouseListener(mouseListener);
}
I tried cut out some of the tedious code to keep it short. If I could get a skeleton or a nudge in the right direction, it would be a great help.
So i've changed it up a bit, once I select open, it populates the JList with the names, then when I double click on a name it only fills the nameTextField, addressTextField, and cityTextField all with the name of the contact I selected
ex) Name: Zoidberg, Address: Zoidberg, City: Zoidberg
here's my code:
openItem.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
readContacts();
for (String name :readContacts())
{
model.addElement(name);
}
nameList = new JList (model);
add(nameList);
nameList.setVisibleRowCount(10);
nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
nameList.setFixedCellHeight (20);
nameList.setFixedCellWidth (130);
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(nameList), BorderLayout.NORTH);
add (left, BorderLayout.WEST);
nameList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = nameList.locationToIndex(e.getPoint());
if (nameList.getModel().getElementAt(index) != null && nameList.getModel().getElementAt(index) instanceof String)
{
nameTextField.setText((String) nameList.getModel().getElementAt (index));
streetAddressTextField.setText((String) nameList.getModel().getElementAt (index));
cityTextField.setText((String) nameList.getModel().getElementAt (index));
stateTextField.setText((String) nameList.getModel().getElementAt (index));
zipTextField.setText((String) nameList.getModel().getElementAt (index));
phoneTextField.setText((String) nameList.getModel().getElementAt (index));
emailTextField.setText((String) nameList.getModel().getElementAt (index));
photoTextField.setText((String) nameList.getModel().getElementAt (index));
}
}
}
};
nameList.addMouseListener(mouseListener);
nameList = new JList (model);
You add data to the JList with the above code.
But then later you do:
nameList = new JList ();
nameList.addListSelectionListener (new ListSelectionListener()
{
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting ( ) == false)
{
List <String> string = nameList.getSelectedValuesList();
System.out.print (string);
}
}
});
Which creates an empty List and adds a ListSelectionListener to this list. This serves no purpose since the JList is empty and is not visible on the GUI anyway.
Add the ListSelectListener to the JList when you create the JList and add data to it:
nameList = new JList (model);
nameList.addListSelectionListener(...);
I second all that Rob Camick writes. Also, you're only adding name Strings to your list and not complete Address objects, and so key information is lost. To gain it, make your JList a list of Address objects, give it a custom cell renderer that shows only the name, but this will allow your selected object to have all the data that you need.

Java: NullPointerException thrown when JButton is clicked in the Flash Card Game

Details: It's a Flash Card game, each Card has question and answer.
QuizCard is the class of Cards having functions like getQuestion(), getAnswer(), setQuestion(), setAnswer() and two String Instances as question and answer. A parameterised constructor takes two strings, first as question and second as answer.
I saved questions and answers in a text file, where question and answer is separated by a "/". All new questions start from a new line.
E.g. -> What is the Capital of India?/New Delhi
Where is the Taj Mahal?/Agra
Rest of the code can be easily understood.
Problem: When the "nextButton" is clicked it throws a NullPointerException and doesn't change the text on the "nextButton".
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class QuizCardPlayer
{
private JFrame frame;
private JTextArea display;
private boolean isAnswer = true;
private JButton nextButton;
private ArrayList<QuizCard> cardList;
private int currentCardIndex;
public static void main(String[] args)
{
QuizCardPlayer player = new QuizCardPlayer();
player.go();
}
public void go()
{
frame = new JFrame("Quiz Card Player");
display = new JTextArea(6,20);
JPanel mainPanel = new JPanel();
Font bigFont = new Font("serif", Font.BOLD, 24);
display.setFont(bigFont);
JScrollPane scroller = new JScrollPane(display);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
display.setText("Lets Start!");
JButton nextButton = new JButton("Show Question");
mainPanel.add(scroller);
mainPanel.add(nextButton);
nextButton.addActionListener(new NextButtonListener());
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem loadMenuItem = new JMenuItem("Load card set");
loadMenuItem.addActionListener(new LoadMenuListener());
fileMenu.add(loadMenuItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setVisible(true);
frame.setSize(300,300);
}
public class NextButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.print("Called!!");
if(isAnswer)
{
nextButton.setText("Show Answer");
if( currentCardIndex < cardList.size() )
{
display.setText(cardList.get(currentCardIndex).getQuestion());
isAnswer = false;
}
else
{
display.setText("That was last Card.");
nextButton.setEnabled(false);
}
}
else
{
nextButton.setText("Next Card");
display.setText(cardList.get(currentCardIndex).getAnswer());
isAnswer = true;
currentCardIndex++;
}
}
}
public class LoadMenuListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(frame);
loadFile(openFile.getSelectedFile());
}
}
public void loadFile(File loadFile)
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(loadFile));
String line="";
cardList = new ArrayList<QuizCard>();
while( (line = reader.readLine()) != null )
{
String[] result = line.split("/");
QuizCard card = new QuizCard(result[0] , result[1]);
cardList.add(card);
currentCardIndex=0;
}
reader.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
I am novice in Java having a experience of just one month, any suggestion is most welcome.
You are creating nextButton as an instance variable of class QuizCardPlayer, but inside go() method, you initializing the local variable nextButton and adding Listener to this local copy, and adding this local copy of nextButton to the mainPanel (which is visible on the VIEW ).
Though the instance variable remains null, as you never did assigned it to anythingy, and you trying to access this null variable inside NextButtonListener class, as follows:
nextButton.setText("Show Answer");
EDIT 1:
Simply replace this line inside go () method:
JButton nextButton = new JButton("Show Question");
to
nextButton = new JButton("Show Question");
This will work :-)

Java Menu AWT into Panel

I am trying to write a clipboard program that can copy/paste and save to a txt file.
While the program works, I am trying to change the buttons into a Menu with MenuItems,
however, I cannot figure out how to use the Menu item properly, as I cannot add it to a panel.
Please notice I am using AWT and not Swing, so no JPanel/JFrame, etc.
Any tip/help is appreciated.
This is my code and attempt at changing it into a menu, please let me know what I am doing wrong:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class CheesyWP extends Frame implements ActionListener {
/**
* #param args
*/
//new panel for menu
Panel north;
//original
Panel center;
Panel south;
Button save;
Button load;
Button clip;
Button finish;
Menu mn;
MenuItem mSave;
MenuItem mLoad;
MenuItem mClip;
MenuItem mFinish;
TextArea ta;
public static void main(String[] args) {
// TODO Auto-generated method stub
CheesyWP cwp = new CheesyWP();
cwp.doIt();
}
public void doIt() {
center = new Panel();
south = new Panel();
clip = new Button("Open Clipboard");
save = new Button("Save");
load = new Button("Load");
finish = new Button("Finish");
//menu items
north = new Panel();
mn = new Menu();
mSave = new MenuItem("Save");
mLoad = new MenuItem("Load");
mClip = new MenuItem("Open Clipboard");
mFinish = new MenuItem("Finish");
mn.add(mSave);
mn.add(mLoad);
mn.add(mClip);
mn.add(mFinish);
mSave.addActionListener(this);
mLoad.addActionListener(this);
mClip.addActionListener(this);
mFinish.addActionListener(this);
//north.add(mn); <-------//PROBLEM HERE
clip.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
finish.addActionListener(this);
ta = new TextArea(20, 80);
center.add(ta);
south.add(load);
south.add(save);
south.add(clip);
south.add(finish);
this.add(center, BorderLayout.CENTER);
this.add(south, BorderLayout.SOUTH);
this.setSize(600, 300);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == save) {
try {
File junk = new File("junk.txt");
FileWriter fw = new FileWriter(junk);
fw.write(ta.getText()); // write whole TextArea contents
fw.close();
} catch (IOException ioe) {
}
}// ends if
if (ae.getSource() == load) {
String temp = "";
try {
File junk = new File("junk.txt");
FileReader fr = new FileReader(junk);
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
ta.append(temp + "\n");
}
br.close();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
if (ae.getSource() == finish) {
System.exit(0);
}
if(ae.getSource()==clip){
new ClipBoard();
}
}
class ClipBoard extends Frame {
public ClipBoard() { // a constructor
this.setTitle("Clipboard");
this.setLayout(new FlowLayout());
this.add(new TextArea(10, 50));
this.setSize(400, 160);
this.setVisible(true);
}
}
}
Just change this
Panel north;
To this
MenuBar north;
Because using awt library , you cannot add Menu to Panel , however you can add Menu to MenuBar
this.validate();
Swing components have a default state of being invalid and won't be painted to the screen unless validated (by calling the .validate() method on either the component itself or on one of the parent containers).

Problems with JList

Our teacher doesn't want us doing anything inside of the GUI class so all of our adding and removing of elements has to be outside in its own class. I've read about vectors and the adding and removing of elements in JList but like i stated we are not allowed to do it that way. My question is how i would go about clearing my list or refreshing it when I need to populate it with a new one or update the original. What my problem is the list duplicates itself every time I click the open button, When what I need it to do is refresh every time it is clicked.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.util.Collections;
import java.io.*;
/* Simple example of using the contents of a file to populate a JList
*
* #author Jill Courte
*/
public class JListFromFile extends JFrame {
private TextField wordA;
private TextField wordB;
private JButton openButton;
private JButton newButton;
private JButton addButton;
private JButton deleteButton;
private JButton saveButton;
private TextField output;
private JList listFromFile;
private JPanel listPanel;
private JPanel textPanel;
private JPanel inputPanel;
private JPanel buttonsPanel;
private DataSource2 dataSource;
private WordPair wordPair;
public JListFromFile ()
{
// create the object to provide the data
dataSource = new DataSource2();
wordPair = new WordPair();
// use a border layout for the main window
getContentPane().setLayout(new BorderLayout(20, 20));
buttonsPanel = new JPanel();
openButton = new JButton("Open");
newButton = new JButton("New");
addButton = new JButton("Add");
deleteButton = new JButton("Delete");
saveButton = new JButton("Save");
addButton.setEnabled( false );
deleteButton.setEnabled( false );
saveButton.setEnabled( false );
buttonsPanel.add(openButton);
buttonsPanel.add(newButton);
buttonsPanel.add(addButton);
buttonsPanel.add(deleteButton);
buttonsPanel.add(saveButton);
//add the button listeners
openButton.addActionListener(new OpenButtonListener());
addButton.addActionListener(new AddButtonListener());
add(buttonsPanel, BorderLayout.NORTH);
// create the panel to hold the list
listPanel = new JPanel();
// create your JList
listFromFile = new JList();
listFromFile.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listFromFile.setSelectedIndex(0);
//add the list selection listener
listFromFile.addListSelectionListener(new WordSelection());
//add the translation text box
textPanel = new JPanel();
output = new TextField();
output.setEditable(false);
output.setPreferredSize(new Dimension(200, 25));
textPanel.add(output);
// add scroll bars to list
JScrollPane listScrollPane = new JScrollPane(listFromFile);
listScrollPane.setPreferredSize(new Dimension(150, 200));
//add user input textfield
wordA = new TextField ("Word to Add");
wordB = new TextField ("Translated word");
wordA.setPreferredSize(new Dimension(200, 25));
wordB.setPreferredSize(new Dimension(200, 25));
wordA.setEnabled(false);
wordB.setEnabled(false);
//create panel to hold input textfield
inputPanel = new JPanel();
inputPanel.add(wordA);
inputPanel.add(wordB);
//add the list (via the scroll pane) to the panel
listPanel.add(listScrollPane);
//add the panels to the frame
add(listPanel, BorderLayout.WEST);
add(textPanel, BorderLayout.CENTER);
add(inputPanel, BorderLayout.SOUTH);
pack();
}
private File findFile ()
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// Start in current directory
chooser.setCurrentDirectory(new File("."));
int status = chooser.showOpenDialog(null);
if (status != JFileChooser.APPROVE_OPTION)
{
JOptionPane.showMessageDialog(null, "No File Selected");
throw new NoFileChoosenException();
}
else
{
File file = chooser.getSelectedFile();
System.out.println(file.getName());
System.out.println(file.getPath());
return file;
}
}
private class OpenButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
File file = null;
try
{
file = findFile();
//tell the data source what file to use
dataSource.readDataFromFile(file);
//JList needs an array of strings, retrieve it from the data source
String [] data = dataSource.getData();
data = dataSource.insertion(data);
data = wordPair.remove(data);
listFromFile.setListData(data);
}
catch (Exception e)
{
}
addButton.setEnabled(true);
deleteButton.setEnabled(true);
saveButton.setEnabled(true);
wordA.setEnabled(false);
wordB.setEnabled(false);
}
}
private class AddButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
wordA.setEnabled(true);
wordB.setEnabled(true);
}
}
private class WordSelection implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent event)
{
int index = listFromFile.getSelectedIndex();
if (index >= 0)
{
String s = wordPair.getWord(2, index);
output.setText(s);
}
}
}
public static void main(String[] args)
{
JListFromFile jListFromFile = new JListFromFile();
jListFromFile.setVisible(true);
}
}

Categories