Jtoolbar isn't displaying - java

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.

Related

How do I get the selected item from a JMenu to change the text color of a text area?

I have to write a text editor for my class using JTextArea, and one of the requirements is to have a color menu that changes the text color when one is selected from the menu. I have set up a color menu with several colors and implemented an ActionListener that calls textArea.setForeground(Color), but the text color never changes from black. Here are the two sections that I'm working on, but I've also provided the code for the entire program at the end.
Here is the code for the JMenu:
private void buildColorMenu()
{
// Create the radio button menu items to change
// the color of the text. Add an action listener
// to each one.
black = new JMenuItem("Black");
black.addActionListener(new ColorListener());
red = new JMenuItem("Red");
red.addActionListener(new ColorListener());
green = new JMenuItem("Green");
green.addActionListener(new ColorListener());
blue = new JMenuItem("Blue");
blue.addActionListener(new ColorListener());
orange = new JMenuItem("Orange");
orange.addActionListener(new ColorListener());
pink = new JMenuItem("Pink");
pink.addActionListener(new ColorListener());
yellow = new JMenuItem("Yellow");
yellow.addActionListener(new ColorListener());
colorMenu = new JMenu("Color");
colorMenu.setMnemonic(KeyEvent.VK_O);
colorMenu.add(black);
colorMenu.add(red);
colorMenu.add(green);
colorMenu.add(blue);
colorMenu.add(orange);
colorMenu.add(pink);
colorMenu.add(yellow);
// Add the menu items to the Text menu.
}
And here is the ActionListener code:
private class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (black.isSelected())
textArea.setForeground(Color.BLACK);
else if (red.isSelected())
textArea.setForeground(Color.RED);
else if (green.isSelected())
textArea.setForeground(Color.GREEN);
else if (blue.isSelected())
textArea.setForeground(Color.BLUE);
else if (orange.isSelected())
textArea.setForeground(Color.ORANGE);
else if (pink.isSelected())
textArea.setForeground(Color.PINK);
else if (yellow.isSelected())
textArea.setForeground(Color.YELLOW);
}
}
Can someone please help?
Here is the code for the entire program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
/**
The MenuWindow class demonstrates a menu system.
*/
public class TextEditor extends JFrame
{
// The following will reference menu components.
private JTextArea textArea;
private JMenuBar menuBar; // The menu bar
private JMenu fileMenu; // The File menu
private JMenu colorMenu; // The Color menu
private JMenu fontMenu;
private JMenuItem newItem;
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
private JMenuItem exitItem; // To exit
private JMenuItem black, red, green, blue, orange, pink, yellow;
private JRadioButtonMenuItem Monospaced; // Makes text black
private JRadioButtonMenuItem Serif; // Makes text Serif
private JRadioButtonMenuItem SansSerif; // Makes text SansSerif
private JCheckBoxMenuItem Italic; // Makes text Italic
private JCheckBoxMenuItem Bold;
/**
Constructor
*/
public TextEditor()
{
// Set the title.
setTitle("Text Editor");
// Specify an action for the close button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(true);
add(scrollPane);
// Build the menu bar.
buildMenuBar();
// Pack and display the window.
pack();
setVisible(true);
}
/**
The buildMenuBar method builds the menu bar.
*/
private void buildMenuBar()
{
// Create the menu bar.
menuBar = new JMenuBar();
// Create the file and text menus.
buildFileMenu();
buildColorMenu();
buildFontMenu();
// Add the file and text menus to the menu bar.
menuBar.add(fileMenu);
menuBar.add(fontMenu);
menuBar.add(colorMenu);
// Set the window's menu bar.
setJMenuBar(menuBar);
}
/**
The buildFileMenu method builds the File menu
and returns a reference to its JMenu object.
*/
private void buildFileMenu()
{
// Create an Exit menu item.
newItem = new JMenuItem("New");
newItem.setMnemonic(KeyEvent.VK_N);
newItem.addActionListener(new NewFileListener());
openItem = new JMenuItem("Open");
openItem.setMnemonic(KeyEvent.VK_O);
openItem.addActionListener(new OpenListener());
saveItem = new JMenuItem("Save");
saveItem.setMnemonic(KeyEvent.VK_S);
saveItem.addActionListener(new SaveListener());
saveAsItem = new JMenuItem("Save As");
saveAsItem.setMnemonic(KeyEvent.VK_A);
saveAsItem.addActionListener(new SaveAsListener());
exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.addActionListener(new ExitListener());
// Create a JMenu object for the File menu.
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
// Add the Exit menu item to the File menu.
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
fileMenu.add(saveAsItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
}
/**
The buildcolorMenu method builds the Text menu
and returns a reference to its JMenu object.
*/
private void buildColorMenu()
{
// Create the radio button menu items to change
// the color of the text. Add an action listener
// to each one.
black = new JMenuItem("Black");
black.addActionListener(new ColorListener());
red = new JMenuItem("Red");
red.addActionListener(new ColorListener());
green = new JMenuItem("Green");
green.addActionListener(new ColorListener());
blue = new JMenuItem("Blue");
blue.addActionListener(new ColorListener());
orange = new JMenuItem("Orange");
orange.addActionListener(new ColorListener());
pink = new JMenuItem("Pink");
pink.addActionListener(new ColorListener());
yellow = new JMenuItem("Yellow");
yellow.addActionListener(new ColorListener());
// Create a button group for the radio button items.
// Create a check box menu item to make the text
// visible or invisible.
// Create a JMenu object for the Text menu.
colorMenu = new JMenu("Color");
colorMenu.setMnemonic(KeyEvent.VK_O);
colorMenu.add(black);
colorMenu.add(red);
colorMenu.add(green);
colorMenu.add(blue);
colorMenu.add(orange);
colorMenu.add(pink);
colorMenu.add(yellow);
// Add the menu items to the Text menu.
}
private void buildFontMenu()
{
Monospaced = new JRadioButtonMenuItem("Monospaced", true);
Monospaced.addActionListener(new FontListener());
Serif = new JRadioButtonMenuItem("Serif");
Serif.addActionListener(new FontListener());
SansSerif = new JRadioButtonMenuItem("SansSerif");
SansSerif.addActionListener(new FontListener());
Italic = new JCheckBoxMenuItem("Italic");
Italic.addActionListener(new FontListener());
Bold = new JCheckBoxMenuItem("Bold");
Bold.addActionListener(new FontListener());
ButtonGroup group = new ButtonGroup();
group.add(Monospaced);
group.add(Serif);
group.add(SansSerif);
fontMenu = new JMenu("Font");
fontMenu.setMnemonic(KeyEvent.VK_N);
fontMenu.add(Monospaced);
fontMenu.add(Serif);
fontMenu.add(SansSerif);
fontMenu.addSeparator();
fontMenu.add(Italic);
fontMenu.add(Bold);
}
/**
Private inner class that handles the event that
is generated when the user selects Exit from
the File menu.
*/
private class NewFileListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
textArea.setText(null);
}
}
private class OpenListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showOpenDialog(textArea);
String str="";
if (status == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
Scanner inputFile;
try
{
inputFile = new Scanner(selectedFile);
while (inputFile.hasNext())
{
str = str+inputFile.nextLine();
}
textArea.setText(str);
inputFile.close();
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
private class SaveAsListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showSaveDialog(textArea);
if (status == JFileChooser.APPROVE_OPTION)
{
try
{
File fileSave = fileChooser.getSelectedFile();
PrintWriter outputfile = new PrintWriter(fileSave + ".txt");
outputfile.println(textArea.getText());
outputfile.close();
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
private class SaveListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
{
PrintWriter outputfile = null;
try
{
outputfile = new PrintWriter("Names.txt");
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
outputfile.println(textArea.getText());
outputfile.close();
}
}
}
private class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (black.isSelected())
textArea.setForeground(Color.BLACK);
else if (red.isSelected())
textArea.setForeground(Color.RED);
else if (green.isSelected())
textArea.setForeground(Color.GREEN);
else if (blue.isSelected())
textArea.setForeground(Color.BLUE);
else if (orange.isSelected())
textArea.setForeground(Color.ORANGE);
else if (pink.isSelected())
textArea.setForeground(Color.PINK);
else if (yellow.isSelected())
textArea.setForeground(Color.YELLOW);
}
}
private class ExitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
/**
Private inner class that handles the event that
is generated when the user selects a color from
the Text menu.
*/
private class FontListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
{
if (Monospaced.isSelected())
textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
else if (Serif.isSelected())
textArea.setFont(new Font(Font.SERIF, Font.PLAIN, 14));
else if (SansSerif.isSelected())
textArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14));
}
if (Italic.isSelected() && Bold.isSelected())
textArea.setFont(new Font(textArea.getText(), Font.BOLD +
Font.ITALIC, 14));
else if (Italic.isSelected())
textArea.setFont(new Font(textArea.getText(), Font.ITALIC, 14));
else if (Bold.isSelected())
textArea.setFont(new Font(textArea.getText(), Font.BOLD, 14));
}
}
/**
Private inner class that handles the event that
is generated when the user selects Visible from
the Text menu.
*/
/**
The main method creates an instance of the
MenuWindow class, which causes it to display
its window.
*/
public static void main(String[] args)
{
new TextEditor();
}
}
The problem is in using JMenuItem.isSelected() method in public void actionPerformed(ActionEvent e). JMenuItem.isSelected() works for toggle button. It is present here because it is method from AbstractButton but its value is always set to false.
To solve problem in your case, use ActionEvent.getActionCommand() intead.
Change the definition of public void actionPerformed(ActionEvent e) as following:
public void actionPerformed(ActionEvent e)
{
switch(e.getActionCommand())
{
case "Black": textArea.setForeground(Color.BLACK); break;
case "Red": textArea.setForeground(Color.RED); break;
case "Green": textArea.setForeground(Color.GREEN); break;
case "Blue": textArea.setForeground(Color.BLUE); break;
case "Orange": textArea.setForeground(Color.ORANGE); break;
case "Pink": textArea.setForeground(Color.PINK); break;
case "Yellow": textArea.setForeground(Color.YELLOW); break;
}
}
I'll try to help. First off there is nothing called a ColorListener you are refereing to your own CONSTRUCTOR! (No you are not now when I have seen the entire code, my bad) Instead of writing the line:
black.addActionListener(new ColorListener());
Instead write this to call the actual ActionListener:
black.addActionListener(this);
The keyword "this" in this case is refering to the actionPerformed method.
But do this to all the JMenuItems (black, pink, green etc).
If this doesn't help you. Provide me with all the code files so that I can copy them and run your program.
UPDATE:
private class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == black)
textArea.setForeground(Color.BLACK);
else if (e.getSource() == red)
textArea.setForeground(Color.RED);
else if (e.getSource() == green)
textArea.setForeground(Color.GREEN);
else if (e.getSource() == blue)
textArea.setForeground(Color.BLUE);
else if (e.getSource() == orange)
textArea.setForeground(Color.ORANGE);
else if (e.getSource() == pink)
textArea.setForeground(Color.PINK);
else if (e.getSource() == yellow)
textArea.setForeground(Color.YELLOW);
}
}
This seems to work, but I can't figure out why.
Maybe you can.

Find and Replace not working Java Swing

I'm making a simple text editor in Java and for some reason my find and replace actions won't work, i made two separate frames, one for the find action, and the other to open up another frame with 2 jtextfields for find and replace. i have in my actionperformed
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
and in my findFrame i have the action that should be carried out when the user clicks on the JMenuItem called "Find".
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
In my Replace frame where i want the user to find a word and replace it, anything you type into the find textfield and click the find button, it finds the first 3 characters on the text field, and the replace action just doesn't work at all,
here is my replace frame
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
the find and replace are two separate JMenuItems, when the user clicks on Find it opens up findframe and when they click on "replace" it opens up the replace frame which has a find textfield and a replace textfield.
here is the whole runnable code :
//Programmer Aly Badran – Project 10
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.DefaultEditorKit.CutAction;
class saveFrame extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel labelpanel = new JPanel();
JButton savebutton = new JButton("Save");
JButton dontsave = new JButton("Dont Save");
JLabel savelabel = new JLabel("Are you sure you want to close"?);
public saveFrame(){
setSize(400,100);
setLocation(500, 300);
setTitle("Saving...");
labelpanel.add(savelabel);
panel.add(savebutton);
panel.add(dontsave);
Container cpane = getContentPane();
cpane.add(panel, "South");
cpane.add(labelpanel, "Center");
setVisible(true);
savebutton.addActionListener(this);
dontsave.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if(source == savebutton){
System.exit(0);
}
else if(source == dontsave){
System.exit(0);
}
}
}
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
class MenuFrame extends JFrame implements ActionListener, MouseListener{
static JTextArea textarea = new JTextArea();
static JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenuItem copy = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cut = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem Paste = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenuItem copyAction = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cutAction = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem pasteAction = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenu search = new JMenu("Search");
JMenuItem open = new JMenuItem("Open");
JMenuItem close = new JMenuItem("Close");
JMenuItem quit = new JMenuItem("Quit");
JMenuItem find = new JMenuItem("Find");
JMenuItem replace = new JMenuItem("Replace");
JMenu font = new JMenu("Font");
JCheckBoxMenuItem bold = new JCheckBoxMenuItem("Bold");
JCheckBoxMenuItem italic = new JCheckBoxMenuItem("Italic");
JPopupMenu popup;
public MenuFrame(){
Container cpane = getContentPane();
cpane.add(textarea);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenheight = d.height;
int screenwidth = d.width;
setSize(screenwidth, screenheight);
JPanel panel = new JPanel();
ImageIcon closeicon = new ImageIcon("bin/close.png");
ImageIcon openicon = new ImageIcon("bin/open.png");
ImageIcon quiticon = new ImageIcon("bin/quit.jpeg");
ImageIcon findicon = new ImageIcon("bin/find.png");
ImageIcon replaceicon = new ImageIcon("bin/replace.png");
ImageIcon boldicon = new ImageIcon("bin/bold.png");
ImageIcon italicicon = new ImageIcon("bin/italic.png");
ImageIcon copyicon = new ImageIcon("bin/copy.png");
ImageIcon cuticon = new ImageIcon("bin/cut.png");
ImageIcon pasteicon = new ImageIcon("bin/paste.png");
Border matte = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK);
Border etched = BorderFactory.createEtchedBorder();
popup = new JPopupMenu();
copy.setText("Copy");
cut.setText("Cut");
Paste.setText("Paste");
copy.setIcon(copyicon);
cut.setIcon(cuticon);
Paste.setIcon(pasteicon);
copyAction.setText("Copy");
cutAction.setText("Cut");
pasteAction.setText("Paste");
copyAction.setIcon(copyicon);
cutAction.setIcon(cuticon);
pasteAction.setIcon(pasteicon);
popup.add(cut);
popup.addSeparator();
popup.add(copy);
popup.addSeparator();
popup.add(Paste);
popup.addSeparator();
popup.add(find);
popup.addSeparator();
popup.add(replace);
edit.add(cutAction);
edit.addSeparator();
edit.add(copyAction);
edit.addSeparator();
edit.add(pasteAction);
find.setIcon(findicon);
replace.setIcon(replaceicon);
close.setIcon(closeicon);
menubar = new JMenuBar();
textarea = new JTextArea("He has achieved success.", d.width, d.height);
JScrollPane scroll = new JScrollPane(textarea);
cpane.add(scroll);
open = new JMenuItem("Open", openicon);
close = new JMenuItem("Close", closeicon);
quit = new JMenuItem("Quit", quiticon);
find = new JMenuItem("Find", findicon);
replace = new JMenuItem("Replace", replaceicon);
bold = new JCheckBoxMenuItem("Bold", boldicon);
italic = new JCheckBoxMenuItem("Italic", italicicon);
textarea.setLineWrap(true);
file.add(open);
file.addSeparator();
file.add(close);
file.addSeparator();
file.add(quit);
menubar.add(file);
menubar.add(edit);
menubar.add(search);
menubar.add(font);
search.add(find);
search.addSeparator();
search.add(replace);
font.add(bold);
font.addSeparator();
font.add(italic);
copy.setEnabled(false);
cut.setEnabled(false);
Paste.setEnabled(false);
find.addActionListener(this);
italic.addActionListener(this);
bold.addActionListener(this);
quit.addActionListener(this);
close.addActionListener(this);
find.addActionListener(this);
replace.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
Paste.addActionListener(this);
cut.addMouseListener(this);
textarea.addMouseListener(this);
copy.addMouseListener(this);
Paste.addMouseListener(this);
textarea.setComponentPopupMenu(popup);
file.setBackground(Color.BLACK);
edit.setBackground(Color.BLACK);
search.setBackground(Color.BLACK);
font.setBackground(Color.BLACK);
panel.add(menubar);
menubar.setBorder(matte);
menubar.setBackground(Color.BLACK);
textarea.setBorder(etched);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
String command = evt.getActionCommand();
String s = textarea.getSelectedText();
Font f = new Font("Italic", Font.ITALIC, 13);
Font f2 = new Font("Bold", Font.BOLD, 13);
if(italic.isSelected()){
textarea.setFont(f);
}
if(bold.isSelected()){
textarea.setFont(f2);
}
if(bold.isSelected() && italic.isSelected()){
textarea.setFont(f);
textarea.setFont(f2);
}
if(command.equals("Quit"))
System.exit(0);
if(command.equals("Close")){
JFrame frame = new saveFrame();
frame.setVisible(true);
}
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
if(command.equals("Replace")){
JFrame frame2 = new replaceFrame();
frame2.setVisible(true);
}
}
public void mouseClicked(MouseEvent e) {
boolean s = textarea.getSelectedText() != null;
if(s){
copy.setEnabled(true);
cut.setEnabled(true);
Paste.setEnabled(true);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
}
public class Menus {
public static void main(String [] args){
JFrame frame = new MenuFrame();
frame.setJMenuBar(MenuFrame.menubar);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Your basic problem comes down to the fact that the "selection" highlight won't be painted while the JTextArea doesn't have focus, I know, awesome.
However, you could use a Highlighter instead, for example...
if (source == find) {
try {
DefaultHighlighter.DefaultHighlightPainter highlighter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor("TextArea.selectionBackground"));
MenuFrame.textarea.getHighlighter().addHighlight(n, n + search.length(), highlighter);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
Which will paint a "highlight" over the specified area.
You may want to have a look at this for away to remove it
This and this may also be of interest
In your replace method, you are using the text of the find JButton instead of the findtext JTextField
//String search = find.getText();
String search = findtext.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
Your codes also a mess (sorry, took me a while to navigate it).
For example, you're adding a ActionListener twice to the find menu item and probably some others, which caused to find windows to appear.
I'd avoid using Toolkit#getScreenSize(); in connection with JFrame#setSize, a better solution would be to use JFrame#setExtendedState and pass it JFrame#MAXIMIZED_BOTH, as this will also take into consideration the other UI assets that the OS may have fixed on the screen (like docks and task bars).
You really should be using dialogs instead of JFrames for your "short term input" mechanisms
Your also recreating a bunch of stuff you've already created, for example...
static JTextArea textarea = new JTextArea();
//...
textarea = new JTextArea("He has achieved success.", d.width, d.height);
What's worse, is you add the original instance of the textarea to the frame BEFORE you create the new one, which runs the risk of not knowing which component you are actually dealing with...which is just compounded by the fact that you're using a static reference to it so other classes can access it, which they shouldn't be allowed to do...
In replaceFrame, you are taking text to search from the find field (button), but you should take it from findtext (you are always searching for text "Find").
This is one of the reasons why code duplication is bad - you should extract the finding logic to one place and reuse it in both classes.

JList doesn't show on JScrollPane

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

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

When printing chars to a file in my Java program, only first char shows up, and I get error

I am in the middle of making a Java program that ciphers a message typed by the user and returns it to them. It is supposed to read the text in the text area and output it to a file, which is then taken character by character and changed into a coded message, which is outputted onto another file and then scanned and displayed. Right now I am just trying to make it so that the text is entered, then outputted, then taken character by character and outputted to another file and read and displayed; basically everything but changing the characters.
However, only the first character of the message or word is outputted to the second file and displayed, and I get a java.util.NoSuchElementException exception. Getting the text from the text area to the first file works fine though.
Here is the code; the problem is probably in createCipher() where I have it marked
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
public class CodeMaker {
public File Cipher;
public int l;
public File message;
public char cipherChar;
public String finalCipher;
public Scanner charScan;
public Scanner scan;
public String cipherWord;
public int z;
public int words;
public File cipherFile;
public int n;
public String cipher;
public JPanel panel;
public JButton saveButton;
public JTextArea textArea;
boolean create = true;
private JFrame frame;
public static void main (String[] args) {
CodeMaker gui = new CodeMaker();
gui.start();
}
private void start() {
frame = new JFrame("Project TrenchCoat: Cipher Creator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.DARK_GRAY);
makeMenus();
makeContent();
frame.setVisible(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
}
private void makeMenus() {
JMenuBar menuBar;
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu menu;
menu = new JMenu("File");
JMenuItem menuItem = new JMenuItem("New Cipher");
menuItem.addActionListener(new NewListener());
menuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_N,
Event.CTRL_MASK));
menu.add(menuItem);
JMenuItem menuitem = new JMenuItem("Read Cipher");
menuitem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_R,
Event.CTRL_MASK));
menu.add(menuitem);
menu.addSeparator();
menuItem = new JMenuItem("Exit");
menuItem.addActionListener(new ExitListener());
menuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_Q,
Event.CTRL_MASK));
menu.add(menuItem);
menuBar.add(menu);
JMenu helpMenu = new JMenu("Help");
JMenuItem helpItem = new JMenuItem("Help");
menuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_H,
Event.CTRL_MASK));
helpMenu.add(helpItem);
menuBar.add(helpMenu);
JMenu aboutMenu = new JMenu("About");
JMenuItem aboutItem = new JMenuItem("About");
menuItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_A,
Event.CTRL_MASK));
aboutMenu.add(aboutItem);
menuBar.add(aboutMenu);
}
private void makeContent() {
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
JLabel label = new JLabel("Click a button to use its function");
label.setForeground(Color.white);
label.setFont(new Font("Lucida Console", Font.PLAIN, 14));
contentPane.add(label, BorderLayout.NORTH);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
panel.setBackground(Color.DARK_GRAY);
JButton createButton = new JButton("Create Cipher");
createButton.addActionListener(new NewListener());
createButton.setBackground(Color.DARK_GRAY);
createButton.setFont(new Font("Lucida Console", Font.PLAIN, 14));
createButton.setForeground(Color.green);
panel.add(createButton);
JButton readButton = new JButton("Read Cipher");
readButton.addActionListener(new ReadListener());
readButton.setBackground(Color.DARK_GRAY);
readButton.setFont(new Font("Lucida Console", Font.PLAIN, 14));
readButton.setForeground(Color.green);
panel.add(readButton);
JButton aboutButton = new JButton("About Cipher Creator");
aboutButton.setBackground(Color.DARK_GRAY);
aboutButton.setFont(new Font("Lucida Console", Font.PLAIN, 14));
aboutButton.setForeground(Color.green);
panel.add(aboutButton);
JButton helpButton = new JButton("Help");
helpButton.setBackground(Color.DARK_GRAY);
helpButton.setFont(new Font("Lucida Console", Font.PLAIN, 14));
helpButton.setForeground(Color.green);
panel.add(helpButton);
frame.add(panel, BorderLayout.WEST);
JButton saveButton = new JButton("Save Cipher");
saveButton.addActionListener(new SaveListener());
saveButton.setBackground(Color.DARK_GRAY);
saveButton.setFont(new Font("Lucida Console", Font.PLAIN, 14));
saveButton.setForeground(Color.green);
panel.add(saveButton);
textArea = new JTextArea(10,25);
contentPane.add(textArea, BorderLayout.CENTER);
}
private class NewListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
textArea.append("Type your message to be ciphered below, then click 'Save Cipher'. Remember, everything in the text area will be in your message, so delete this line.\n");
}
}
private class SaveListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
createCipher();
}
}
private class ReadListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(frame);
cipherFile = fc.getSelectedFile();
if (cipherFile == null) {
return;
}
readCipher();
}
}
private void readCipher() {
try
{
Scanner scan = new Scanner(cipherFile);
while (scan.hasNext())
{
String cipher = scan.next();
textArea.append(cipher);
textArea.append("\n");
}
scan.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(frame,
"I/O error in file\n\n " +
cipherFile.getName() +
"\n\nThis program will close",
"I/O Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private void createCipher() {
try
{
cipher = textArea.getText();
PrintStream oFile = new PrintStream("Message.txt");
message = new File("Message.txt");
oFile.print(cipher);
oFile.close();
}
catch(IOException ioe)
{
System.out.println("\n*** I/O Error ***\n" + ioe);
}
//problem is probably just below here
try {
PrintStream oFile = new PrintStream("Cipher.txt");
File Cipher = new File("Cipher.txt");
scan = new Scanner(message);
while (scan.hasNext()) {
cipherWord = scan.next();
l = cipherWord.length();
charScan = new Scanner(cipherWord);
while (n<l) {
cipherChar = charScan.next().charAt(n);
oFile.print(cipherChar);
}
}
}
catch(Exception ioe) {
System.out.println("\n*** Print to Cipher.txt Error ***\n" + ioe);
}
viewCipher();
}
private void viewCipher() {
textArea.append("Below is the cipher you created.\n Now you can copy/paste in and email it to the desired recipient.");
try
{
File Cipher = new File("Cipher.txt");
Scanner scan = new Scanner(Cipher);
textArea.append("\n");
while (scan.hasNextLine())
{
String cipher = scan.nextLine();
textArea.append(cipher);
textArea.append("\n");
}
}
catch(IOException e)
{
JOptionPane.showMessageDialog(frame,
"I/O error in file\n\n " +
cipherFile.getName() +
"\n\nThis program will close",
"I/O Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
private class ExitListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
If you run the program, what is supposed to happen is that when you type in the text area and click save cipher, the text you typed is outputted back to you.
Any help is really appreciated...
Thanks!
In createCipher, change-
while (n<l) {
cipherChar = charScan.next().charAt(n);
oFile.print(cipherChar);
}
To-
for(int i = 0; i < cipherWord.length(); i++){
cipherChar = cipherWord.charAt(i);
oFile.print(cipherChar);
}
Read first on Scanner and its methods and try to understand before using them. Close readers/writers in a finally block. If an exception/error occurs while opening or reading or writing to a file, you won't be closing them in your current program as catch will be executed and close call won't be.
The issue you are having is that the Scanner uses delimiters to retrieve text, and your code is balking when it can't find a complete token.

Categories