I have been working on an html text editing program for a while and i wondered if anyone could help me with this small problem. I have two jmenus but one of them are misbehaving. i have two problems. 1 the menu item in the menu has a submenu arrow although it is not a sub menu
is that i have added an action listener to the menu but when i click the action doesent happen. here is the code.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Window {
static boolean saved = false;
static boolean opened = false;
static File saveDirectory = null;
static File openDirectory = null;
static final JTextArea editor = new JTextArea(10,50);
public static void openWindowEditor(){
JFrame f = new JFrame("Easy HTML Text editor");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu viewMenu = new JMenu("View");
JMenuItem fileMenuSave = new JMenuItem("Save");
JMenuItem fileMenuOpen = new JMenuItem("Open");
JMenuItem fileMenuSaveAs = new JMenuItem("Save as...");
JMenuItem viewMenuEasyInsert = new JMenu("Easy insert");
fileMenu.setMnemonic(KeyEvent.VK_A);
viewMenu.setMnemonic(KeyEvent.VK_A);
menuBar.add(fileMenu);
menuBar.add(viewMenu);
fileMenu.add(fileMenuSave);
fileMenu.add(fileMenuOpen);
fileMenu.add(fileMenuSaveAs);
viewMenu.add(viewMenuEasyInsert);
fileMenuSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
save(editor.getText());
}
});
fileMenuOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
open();
}
});
fileMenuSaveAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveAs();
}
});
viewMenuEasyInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
openEasyInsertWindow();
}
});
f.setJMenuBar(menuBar);
f.add(editor);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLayout(new GridLayout(1,1));
f.pack();
f.setVisible(true);
}
public static void open(){
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showDialog(null, "open");
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = chooser.getSelectedFile();
try{
editor.read(new FileReader(file), null);
}catch(IOException e){
JOptionPane.showMessageDialog(null, e);
}
}
}
public static void save(String text){
JFileChooser chooser = new JFileChooser();
File file = null;
int returnVal = chooser.showDialog(null, "Save");
if(returnVal == JFileChooser.APPROVE_OPTION){
file = (chooser.getSelectedFile());
String result = text.replace("\n", System.getProperty("line.separator"));
saveDirectory = chooser.getSelectedFile();
try{
FileWriter fw = new FileWriter(file);
fw.write(result);
fw.close();
saved = true;
}catch(IOException e){
JOptionPane.showMessageDialog(null, e);
}
}
}
public static void saveAs(){
JFileChooser chooser = new JFileChooser();
File dir;
int returnVal = chooser.showDialog(null, "Save as...");
if(returnVal == JFileChooser.APPROVE_OPTION){
dir = chooser.getSelectedFile();
try{
FileWriter fw = new FileWriter(dir);
fw.write(editor.getText());
fw.close();
}catch(IOException e){
JOptionPane.showMessageDialog(null, e);
}
}
}
public static void openEasyInsertWindow(){
JFrame f = new JFrame("easy insert");
JButton insertDivButton = new JButton("Insert <div> element");
JButton openInsertSettings = new JButton("Open the insert settings");
f.setLayout(new GridLayout(2,1));
f.add(insertDivButton);
f.add(openInsertSettings);
f.pack();
f.setVisible(true);
JOptionPane.showMessageDialog(editor, "Easy insert");
}
}
Because you've defined it as a JMenu and not a JMenuItem
JMenuItem viewMenuEasyInsert = new JMenu("Easy insert");
should be
JMenuItem viewMenuEasyInsert = new JMenuItem("Easy insert");
Related
I am making a notepad program and I wanted to add all the Fonts selection to the JMenu but when the JMenuItems are too many it runs out of space from the screen and I cannot navigate through the fonts below my screen
How do I put a scrollbar in a JMenu or is there anything that I can add to help me navigate through the list of fonts?
The picture below is my JMenu with all the Fonts and below is my notepad frame class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Writter extends JFrame implements ActionListener {
JTextArea textArea;
JMenuItem openFileItem;
JMenuItem saveFileItem;
JMenuItem saveAsFileItem;
JMenuItem closeFileItem;
JMenuItem foregroundColorItem;
JMenuItem backgroundColorItem;
JScrollPane scrollPane;
JScrollPane scrollPaneMenu;
ArrayList<JMenuItem> menuitemsList = new ArrayList<JMenuItem>();
JMenuItem menuitems;
File openFile = null;
JLabel filePathLabel;
String[] fonts;
Color colorFont;
Writter() {
ImageIcon notepadIcon = new ImageIcon("notepadIcon.png");
fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
filePathLabel = new JLabel("File Path: " + "Null");
filePathLabel.setForeground(Color.white);
this.setTitle("Writter App");
this.setIconImage(notepadIcon.getImage());
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 600));
this.setResizable(true);
this.setAlwaysOnTop(true);
JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(Color.black);
menuBar.setBorderPainted(false);
JPanel panelMenu = new JPanel();
panelMenu.setLayout(new BorderLayout());
panelMenu.setBackground(Color.black);
panelMenu.add(menuBar, BorderLayout.CENTER);
panelMenu.add(filePathLabel, BorderLayout.EAST);
JMenu fileMenu = new JMenu("File");
JMenu optionMenu = new JMenu("Option");
JMenu fontsMenu = new JMenu("Fonts");
//
fileMenu.setForeground(Color.white);
optionMenu.setForeground(Color.white);
fileMenu.setMnemonic(KeyEvent.VK_F);
optionMenu.setMnemonic(KeyEvent.VK_O);
menuBar.add(fileMenu);
menuBar.add(optionMenu);
optionMenu.add(fontsMenu);
openFileItem = new JMenuItem("Open");
saveFileItem = new JMenuItem("Save");
saveAsFileItem = new JMenuItem("Save As");
closeFileItem = new JMenuItem("Close");
foregroundColorItem = new JMenuItem("Set Font Color");
backgroundColorItem = new JMenuItem("Set Background Color");
for (int i = 0; i < fonts.length; i++) {
fontsMenu.add(menuitems = new JMenuItem(fonts[i]));
menuitems.setFont(new Font(fonts[i], Font.PLAIN, 15));
menuitems.addActionListener(this);
menuitemsList.add(menuitems);
}
openFileItem.setMnemonic(KeyEvent.VK_O);
saveFileItem.setMnemonic(KeyEvent.VK_S);
saveAsFileItem.setMnemonic(KeyEvent.VK_A);
closeFileItem.setMnemonic(KeyEvent.VK_C);
foregroundColorItem.setMnemonic(KeyEvent.VK_F);
backgroundColorItem.setMnemonic(KeyEvent.VK_B);
openFileItem.addActionListener(this);
saveFileItem.addActionListener(this);
saveAsFileItem.addActionListener(this);
closeFileItem.addActionListener(this);
foregroundColorItem.addActionListener(this);
backgroundColorItem.addActionListener(this);
fileMenu.add(openFileItem);
fileMenu.add(saveFileItem);
fileMenu.add(saveAsFileItem);
fileMenu.add(closeFileItem);
optionMenu.add(foregroundColorItem);
optionMenu.add(backgroundColorItem);
textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setFont(new Font("Arial", Font.PLAIN, 20));
scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(400, 550));
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.add(panelMenu, BorderLayout.NORTH);
this.add(scrollPane);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openFileItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("C:/Users/User/Desktop"));
int response = fileChooser.showOpenDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
textArea.setText("");
openFile = new File(fileChooser.getSelectedFile().getAbsolutePath());
filePathLabel.setText(fileChooser.getSelectedFile().getAbsolutePath());
Scanner inputFile = null;
try {
inputFile = new Scanner(openFile);
while (inputFile.hasNext()) {
String text = inputFile.nextLine() + "\n";
textArea.append(text);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
inputFile.close();
}
}
}
if (e.getSource() == saveFileItem) {
if (openFile == null) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("C:/Users/User/Desktop"));
int response = fileChooser.showSaveDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
PrintWriter outputFile;
try {
outputFile = new PrintWriter(file);
outputFile.println(textArea.getText());
outputFile.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
} else {
PrintWriter outputFile;
try {
outputFile = new PrintWriter(openFile);
outputFile.println(textArea.getText());
outputFile.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
if (e.getSource() == saveAsFileItem) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
fileChooser.setCurrentDirectory(new File("C:/Users/User/Desktop"));
int response = fileChooser.showSaveDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
PrintWriter outputFile;
try {
outputFile = new PrintWriter(file);
outputFile.println(textArea.getText());
outputFile.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
if (e.getSource() == closeFileItem) {
this.dispose();
}
if (e.getSource() == foregroundColorItem) {
new JColorChooser();
colorFont = JColorChooser.showDialog(null, "Set Font Color", Color.black);
textArea.setForeground(colorFont);
}
if (e.getSource() == backgroundColorItem) {
new JColorChooser();
Color color = JColorChooser.showDialog(null, "Set Background Color", Color.black);
textArea.setBackground(color);
}
if(e.getSource() == menuitems) {
System.out.println(menuitems.getText());
}
for(int i=0; i<fonts.length; i++) {
if(e.getSource()==menuitemsList.get(i)) {
textArea.setFont(new Font(menuitemsList.get(i).getText(), Font.PLAIN, 20));
}
}
}
}
I am creating a simple Wordpad editor application. I am using JTextPane. I have added code to read '.rtf' file using RTFEditorKit. Initialization code:
RTFEditorKit rtfKit = new RTFEditorKit();
JTextPane textPane = new JTextPane();
textPane.setEditorKit(rtfKit);
Now I need to read plain text file '.txt' using 'RTFEditorKit' into the same JTextPane, so that I can view plain text file and rtf file in the same application. How can I achieve this?
My application minimal code:
import static java.awt.event.InputEvent.CTRL_DOWN_MASK;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.Document;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
public class MyNotepad implements ActionListener {
public JFrame frame;
public JPanel panel;
public JTextPane textPane;
public RTFEditorKit rtf;
public StyleContext styleContext;
public Document document;
public JScrollPane scrollPane;
public JMenuBar menuBar;
public JMenu fileMenu;
public JMenuItem newSubMenu;
public JMenuItem openSubMenu;
public JFileChooser fc;
public boolean openFileExtFlag = true;
public boolean saveFileExtFlag = true;
public File openFile;
public File saveFile;
public boolean saveWindowTitle = false;
public boolean openFileFlag;
public boolean saveFileFlag;
public boolean saved = true;
public boolean dontSaveOption;
public BufferedReader br;
public boolean saveForNewOpenExitListener;
public boolean saveAsFlag;
public int returnVal;
public String filePath;
public boolean flagForOpenListener;
public StyledDocument styledDocument;
public Style defaultStyle;
public MutableAttributeSet mas;
public MyNotepad() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
frame = new JFrame("My Notepad");
panel = new JPanel(new BorderLayout());
rtf = new RTFEditorKit();
textPane = new JTextPane();
textPane.setEditorKit(rtf);
textPane.setMargin(new Insets(10,5,5,5));
styleContext = new StyleContext();
mas = textPane.getInputAttributes();
styledDocument = textPane.getStyledDocument();
textPane.setDocument(styledDocument);
scrollPane = new JScrollPane();
scrollPane.getViewport().add(textPane);
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
newSubMenu = new JMenuItem("New");
newSubMenu.setAccelerator(KeyStroke.getKeyStroke('N', CTRL_DOWN_MASK));
openSubMenu = new JMenuItem("Open...");
openSubMenu.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK));
defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
fc= new JFileChooser();
openSubMenu.addActionListener(this);
newSubMenu.addActionListener(this);
scrollPane.setPreferredSize(new Dimension(700,500));
fileMenu.add(newSubMenu);
fileMenu.add(openSubMenu);
menuBar.add(fileMenu);
textPane.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(new JLabel(" "), BorderLayout.EAST);
panel.add(new JLabel(" "), BorderLayout.WEST);
panel.add(new JLabel(" "), BorderLayout.SOUTH);
frame.setJMenuBar(menuBar);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(900,200));
frame.pack();
textPane.requestFocus();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new MyNotepad();
}
public void actionPerformed(ActionEvent ae) {
if ((ae.getSource() == openSubMenu)) {
openActionListener();
}
}
public boolean openActionListener() {
if (openFileExtFlag && saveFileExtFlag) {
fc.setAcceptAllFileFilterUsed(false);
fc.addChoosableFileFilter(new FileNameExtensionFilter("Rich Text File (*.rtf)", "rtf"));
fc.addChoosableFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
openFileExtFlag = false;
}
do {
returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
openFile = fc.getSelectedFile();
filePath = openFile.getPath();
if (openFile.exists()) {
break;
}
JOptionPane.showMessageDialog(frame, "File not found, please verify the file name and the path", "Cannot open", JOptionPane.OK_OPTION);
} else {
return false;
}
} while (true);
try {
System.out.println("---opening document...");
textPane.setText("");
InputStream in = new FileInputStream(filePath);
System.out.println("Opening file - " + filePath);
if (filePath.endsWith(".rtf")) {
rtf.read(in, textPane.getDocument(), 0);
in.close();
} else if (filePath.endsWith(".txt")) {
textPane = new JTextPane();
FileReader fileReader = new FileReader(filePath);
textPane.read(fileReader, openFile);
fileReader.close();
}
textPane.requestFocus();
textPane.setCaretPosition(0);
frame.setTitle("My Notepad " + "- " + filePath);
System.out.println("----File opened successfully");
} catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Cannot open, Invalid RTF file", "Cannot open", JOptionPane.OK_OPTION);
}
return true;
}
}
textPane = new JTextPane();
FileReader fileReader = new FileReader(filePath);
textPane.read(fileReader, openFile);
fileReader.close();
You are creating a new JTextPane which will never be added to the UI, and the text is added inside this very textPane instead of the one you see in the UI...
Just remove the line : textPane = new JTextPane();
Sorry for late answer.
A friend and myself are making a NotePad. We are trying to get fonts to change when you click the appropriate button. For example if I press the Italic Button the text I write after that will be Italic until I press the Normal button which will turn it back to the normal font. As far as I can tell the code looks pretty good but when I press the font buttons nothing happens. Here is ALL the code.
package com.note.pad;
import javax.swing.*; // for the main JFrame design
import java.awt.*; // for the GUI stuff
import java.awt.event.*; // for the event handling
import java.util.Scanner; // for reading from a file
import java.io.*; // for writing to a file
public class Notepad extends JFrame implements ActionListener{
private TextArea textArea = new TextArea("", 0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
private MenuBar menuBar = new MenuBar(); //First, create a menu bar.
private Menu file = new Menu(); //File menu.
private Menu fonts = new Menu(); //Font menu.
private MenuItem italicFont = new MenuItem();
private MenuItem normalFont = new MenuItem();
private MenuItem openFile = new MenuItem(); //Open option
private MenuItem saveFile = new MenuItem(); //Save option
private MenuItem close = new MenuItem(); //Close option
public Notepad(){
this.setSize(500, 300); //Size of Notepad
this.setTitle("BenPad"); //Name of Notepad
setDefaultCloseOperation(EXIT_ON_CLOSE); //Closes when you hit X button
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); //Font
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(textArea);
this.setMenuBar(this.menuBar);
this.menuBar.add(this.file);
this.menuBar.add(this.fonts);
this.file.setLabel("File");
this.fonts.setLabel("Fonts");
this.italicFont.setLabel("Italic");
this.normalFont.setLabel("Normal");
this.fonts.add(this.italicFont);
this.openFile.setLabel("Open");
this.fonts.add(this.normalFont);
this.openFile.addActionListener(this);
this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_0, false));
this.file.add(this.openFile);
this.saveFile.setLabel("Save");
this.saveFile.addActionListener(this);
this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
this.file.add(this.saveFile);
this.close.setLabel("Close");
this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
this.close.addActionListener(this);
this.file.add(this.close);
}
public void actionPerformed (ActionEvent e) {
if (e.getSource() == this.close)
this.dispose();
else if (e.getSource() == this.openFile) {
JFileChooser open = new JFileChooser();
int option = open.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
this.textArea.setText("");
try {
Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
while (scan.hasNext())
this.textArea.append(scan.nextLine() + "\n");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
else if (e.getSource() == this.italicFont) {
this.textArea.setFont(new Font("Italic", Font.ITALIC, 12));
}
else if (e.getSource() == this.normalFont) {
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12));
}
else if (e.getSource() == this.saveFile) {
JFileChooser save = new JFileChooser();
int option = save.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
out.write(this.textArea.getText());
out.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void main(String args[]) {
Notepad app = new Notepad();
app.setVisible(true);
}
}
Try this:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class Notepad extends JFrame implements ActionListener{
private TextArea textArea = new TextArea("");//, 0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
private MenuBar menuBar = new MenuBar(); //First, create a menu bar.
private Menu file = new Menu(); //File menu.
private Menu fonts = new Menu(); //Font menu.
private MenuItem italicFont = new MenuItem();
private MenuItem normalFont = new MenuItem();
private MenuItem openFile = new MenuItem(); //Open option
private MenuItem saveFile = new MenuItem(); //Save option
private MenuItem close = new MenuItem(); //Close option
public Notepad(){
setSize(500, 300); //Size of Notepad
setTitle("BenPad"); //Name of Notepad
setDefaultCloseOperation(EXIT_ON_CLOSE); //Closes when you hit X button
textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); //Font
setVisible(true);
setLayout(new BorderLayout());
add(textArea);
setMenuBar(this.menuBar);
menuBar.add(this.file);
menuBar.add(this.fonts);
file.setLabel("File");
fonts.setLabel("Fonts");
italicFont.setLabel("Italic");
normalFont.setLabel("Normal");
fonts.add(this.italicFont);
openFile.setLabel("Open");
fonts.add(this.normalFont);
italicFont.addActionListener(this);
normalFont.addActionListener(this);
openFile.addActionListener(this);
openFile.setShortcut(new MenuShortcut(KeyEvent.VK_0, false));
file.add(this.openFile);
saveFile.setLabel("Save");
saveFile.addActionListener(this);
saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
file.add(this.saveFile);
close.setLabel("Close");
close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
close.addActionListener(this);
file.add(this.close);
}
#Override
public void actionPerformed (ActionEvent e) {
if (e.getSource() == this.close)
this.dispose();
else if (e.getSource() == this.openFile) {
JFileChooser open = new JFileChooser();
int option = open.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
this.textArea.setText("");
try {
Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
while (scan.hasNext())
this.textArea.append(scan.nextLine() + "\n");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
else if (e.getSource() == this.italicFont) {
this.textArea.setFont(new Font("Times New Roman", Font.ITALIC, 12));
}
else if (e.getSource() == this.normalFont) {
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12));
}
else if (e.getSource() == this.saveFile) {
JFileChooser save = new JFileChooser();
int option = save.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
out.write(this.textArea.getText());
out.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void main(String args[]) {
Notepad app = new Notepad();
//app.setVisible(true);
}
}
If you want text you insert before you press italic font menu then you have to use JEditorPane/JTextPane
I am wondering why the JTabbedPane only adds 1 tab. When I use the method addTab and then reuse it to create a new tab, it overrides the first tab created. Here is the code: BTW, most of the code that might be related to the problem is at actionlistener.
package com.james.client;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.Element;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String [] args)
{
//JTextArea
final JTextArea code = new JTextArea();
final JTextArea lines = new JTextArea("1");
final JScrollPane scroll = new JScrollPane(code);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
lines.setBackground(Color.LIGHT_GRAY);
lines.setEditable(false);
code.getDocument().addDocumentListener(new DocumentListener(){
public String getText(){
int caretPosition = code.getDocument().getLength();
Element root = code.getDocument().getDefaultRootElement();
String text = "1" + System.getProperty("line.separator");
for(int i = 2; i < root.getElementIndex( caretPosition ) + 2; i++){
text += i + System.getProperty("line.separator");
}
return text;
}
#Override
public void changedUpdate(DocumentEvent de) {
lines.setText(getText());
}
#Override
public void insertUpdate(DocumentEvent de) {
lines.setText(getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
lines.setText(getText());
}
});
scroll.getViewport().add(code);
scroll.setRowHeaderView(lines);
//JFrame
JFrame window = new JFrame("MinecraftProgrammer++");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(1000, 700);
window.setResizable(false);
window.setLocationRelativeTo(null);
//JMenuBar
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenu newfile = new JMenu("New");
//JTabbedPane
final JTabbedPane tabs = new JTabbedPane();
tabs.setBackground(Color.gray);
//JMenu items
JMenuItem classfile = new JMenuItem("Class");
JMenuItem packagefolder = new JMenuItem("Package");
JMenuItem other = new JMenuItem("Other");
JMenuItem open = new JMenuItem("Open");
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
JFileChooser chooseFile = new JFileChooser();
chooseFile.setAcceptAllFileFilterUsed(false);
FileFilter filter1 = new ExtensionFileFilter("Java Class", new String[] {"JAVA"});
FileFilter filter2 = new ExtensionFileFilter("Text File", new String[] {"TXT"});
chooseFile.setFileFilter(filter2);
chooseFile.setFileFilter(filter1);
chooseFile.showOpenDialog(chooseFile);
String filePath = chooseFile.getSelectedFile().getAbsolutePath();
FileReader readFile = new FileReader(filePath);
String fileName = chooseFile.getSelectedFile().getName();
tabs.addTab(fileName, scroll);
#SuppressWarnings("resource")
Scanner fileReaderScan = new Scanner(readFile);
String storeAllString = "";
while(fileReaderScan.hasNextLine())
{
String temp = fileReaderScan.nextLine() + "\n";
storeAllString = storeAllString + temp;
}
code.setText(storeAllString);
code.setLineWrap(true);
code.setWrapStyleWord(true);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(e);
}
}
});
JMenuItem save = new JMenuItem("Save");
JMenuItem saveas = new JMenuItem("Save As...");
//Compile menu bar
file.add(newfile);
file.add(open);
file.add(save);
file.add(saveas);
newfile.add(classfile);
newfile.add(packagefolder);
newfile.add(other);
menu.add(file);
window.add(tabs);
window.setJMenuBar(menu);
window.setVisible(true);
}
}
You're adding the JScrollPane "scroll" to the JTabbedPane. How many times do you construct this component? Answer -- once only. So you're only adding and re-adding the same component every time.
final JScrollPane scroll = new JScrollPane(code); // here you create scroll
// .....
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
JFileChooser chooseFile = new JFileChooser();
// ....
// you add the same component here
tabs.addTab(fileName, scroll);
// ....
}
Since you can't add a component to a container more than once and see it in both containers, the solution is to create any components needed for the new tab inside of the ActionListener's actionPerformed(...) method each time you need to add something to the JTabbedPane.
I need to filter files in a filechooser that only allows image files to be chosen. I cant seem to figure out whats wrong with my code here:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Viewer extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JMenuItem open;
private JMenuItem exit;
private JFileChooser fileChooser;
private JLabel image;
public Viewer(){
super("Picture Viewer");
this.setLayout(new BorderLayout());
//this.setSize(400, 400);
JPanel canvas = new JPanel();
this.add(canvas, BorderLayout.CENTER);
image = new JLabel();
canvas.add(image, BorderLayout.CENTER);
JMenuBar menubar = new JMenuBar();
this.add(menubar, BorderLayout.NORTH);
JMenu menu = new JMenu("File");
menubar.add(menu);
open = new JMenuItem("Open...");
open.addActionListener(this);
menu.add(open);
exit = new JMenuItem("Exit");
exit.addActionListener(this);
menu.add(exit);
this.setVisible(true);
this.pack();
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == open){
fileChooser = new JFileChooser();
fileChooser.showOpenDialog(this);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setFileFilter(new ImageFileFilter());
int returnVal = fileChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// bmp, gif, jpg, png files okay
BufferedImage bi;
try {
bi = ImageIO.read(file);
image.setIcon(new ImageIcon(bi));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// catch IOException
}
this.pack();
}
else if(e.getSource() == exit){
System.exit(0);
}
}
public static void main(String[] args){
Viewer viewer = new Viewer();
}
public class ImageFileFilter implements FileFilter{
private final String[] okFileExtensions =
new String[] {"jpg", "png", "gif", "bmp"};
public boolean accept(File file)
{
for (String extension : okFileExtensions)
{
if (file.getName().toLowerCase().endsWith(extension))
{
return true;
}
}
return false;
}
}
}
It's telling me that my custom filter class that implements FileFilter isnt of type FileFilter. :/
The JFileChooser needs you to extend an instance of javax.swing.filechooser.FileFilter. Since you have implements your IDE is importing java.io.FileFilter instead.
Your file filter should accept directories as well.
if (file.isDirectory())
return true;
even tho your file selection mode is files only (which is correct).
Since Java7 you can simply use FileNameExtensionFilter(String description, String... extensions) instead of subclassing FileFilter.
A simple JFileChooser analog to the example would be:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp"));
I know the question was answered long ago, but this is actually the simplest solution.