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
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 making a Smart ATM application for my college project using Swing which can be used by people with visual disabilities as well.
I have added mouse over listeners to every button so that the program plays a clip which speaks about the operation of that button.
The problem is when user hovers over multiple buttons in a short period of time when a clip about previous button is already getting played, two clips get played simultaneously which is not what I want.
My code so far for the current frame is:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.InputMismatchException;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
public class InitialInput extends JFrame implements ActionListener {
JLabel logo;
JPanel logoPanel = new JPanel();
JPanel askPanel = new JPanel();
JPanel pinPanel = new JPanel();
//For adding span
JPanel emptyPanel = new JPanel();
JTextField accountNumberField = new JTextField(10);
JLabel askAccountNumber = new JLabel("Please enter your account Number : ");
public int userAccountNumber;
JTextField pinField = new JTextField(10);
JLabel askPin = new JLabel("Please enter your Pin : ");
public int userPin;
JPanel submitPanel = new JPanel();
JButton submit = new JButton("SUBMIT");
JButton createAccount = new JButton("CREATE NEW ACCOUNT");
JPanel mainPanel = new JPanel(new GridBagLayout());
Clip clipAccountNumberField,clipPinField,clipWelcome,clipSubmit;
InitialInput() {
//Play welcome Music
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(Welcome.class.getResource("WelcomeMusic.wav"));
clipWelcome = AudioSystem.getClip();
clipWelcome.open(audioIn);
clipWelcome.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play deposit music!");
}
buildGUI();
}
//TODO Work on this
/*
public void stopAllClips() {
//Clip clipAccountNumberField,clipPinField,clipWelcome,clipSubmit;
if(clipWelcome.isActive())
clipWelcome.stop();
if(clipAccountNumberField.isActive())
clipAccountNumberField.stop();
if(clipPinField.isActive())
clipPinField.stop();
if(clipSubmit.isActive())
clipSubmit.stop();
}*/
public void buildGUI() {
//Properties of Frame
setSize(400,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
BufferedImage logoI = ImageIO.read(this.getClass().getResource("logo.png"));
logo = new JLabel(new ImageIcon(logoI));
}
catch(Exception e) {
e.getMessage();
}
//On Hover Action for Deposit Button
accountNumberField.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(InitialInput.class.getResource("ClickAndEnterAccountNumber.wav"));
clipAccountNumberField = AudioSystem.getClip();
clipAccountNumberField.open(audioIn);
// stopAllClips();
clipAccountNumberField.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play account number music!");
}
}
});
pinField.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(InitialInput.class.getResource("ClickAndEnterPin.wav"));
clipPinField = AudioSystem.getClip();
clipPinField.open(audioIn);
// stopAllClips();
clipPinField.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play pin music!");
}
}
});
submit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(InitialInput.class.getResource("ClickToSubmit.wav"));
clipSubmit = AudioSystem.getClip();
clipSubmit.open(audioIn);
// stopAllClips();
clipSubmit.start();
}
catch(Exception e) {
System.out.println("Sorry Unable to play submit music!");
}
}
});
//TODO Add music to create account button
//Adds gap between create account and submit button
FlowLayout flow = new FlowLayout(); // Create a layout manager
flow.setHgap(35);
submitPanel.setLayout(flow);
//Adds symbiosis logo to panel
logoPanel.add(logo);
//Adds action listener to text fields
accountNumberField.addActionListener(this);
pinField.addActionListener(this);
//Adds action listener to Create Account Button
createAccount.addActionListener(this);
//Adds labels to panel
askPanel.add(askAccountNumber);
askPanel.add(accountNumberField);
//Adds textfields to panel
pinPanel.add(askPin);
pinPanel.add(pinField);
//Adds buttons to panels
submitPanel.add(createAccount);
submitPanel.add(submit);
//Specifies constraints for grid layout
GridBagConstraints c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
mainPanel.add(logoPanel,c);
c.gridx=0;
c.gridy=1;
mainPanel.add(askPanel,c);
c.gridx=0;
c.gridy=2;
mainPanel.add(emptyPanel,c);
c.gridx=0;
c.gridy=3;
mainPanel.add(pinPanel,c);
c.gridx=0;
c.gridy=4;
mainPanel.add(emptyPanel,c);
c.gridx=0;
c.gridy=5;
mainPanel.add(submitPanel,c);
add(mainPanel);
setVisible(true);
}
//Action listener
public void actionPerformed(ActionEvent e) {
if(e.getSource()==accountNumberField) {
try {
userAccountNumber = Integer.parseInt(accountNumberField.getText());
int numberOfDigitsInAccountNumber = String.valueOf(userAccountNumber).length();
if(numberOfDigitsInAccountNumber !=6) {
throw new InputMismatchException();
}
if(userAccountNumber <= 0) {
throw new Exception();
}
//TODO if(accountNumber) not present in database
}
catch(InputMismatchException e1) {
accountNumberField.setText("");
JOptionPane.showMessageDialog(accountNumberField,"Please enter a 6 digit account number.");
}
catch(Exception e1) {
accountNumberField.setText("");
JOptionPane.showMessageDialog(accountNumberField,"Invalid input.");
}
}
else if(e.getSource()==pinField) {
try {
userPin = Integer.parseInt(pinField.getText());
int numberOfDigitsInAccountNumber = String.valueOf(userPin).length();
if(numberOfDigitsInAccountNumber !=4) {
throw new InputMismatchException();
}
if(userPin <= 0) {
throw new Exception();
}
//TODO if(accountNumber) not match in database
}
catch(InputMismatchException e1) {
pinField.setText("");
JOptionPane.showMessageDialog(pinField,"Please enter a 4 digit pin.");
}
catch(Exception e1) {
pinField.setText("");
JOptionPane.showMessageDialog(pinField,"Invalid input.");
}
}
else if(e.getSource()==createAccount) {
CreateAccount a = new CreateAccount();
this.setVisible(false);
a.setVisible(true);
}
}
}
Override the mouseExited method for each MouseListener, stopping the Clip in the implementation
#Override
public void mouseExited(MouseEvent e){
theClipIManage.stop();
}
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");
i don't know how to change frame's title when an drag and drop event takes place. I 've read Java Docs about DnD and Transferable but i can't find a solution, i've come to an conclusion that i have to play games with DropTargetListener, but i am to a deadlock.Any answer would be a relief!(also in drag n drop i would like to hold the attributes of the text)
The SSCCE is:
package sscceeditor;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.text.BadLocationException;
import rtf.AdvancedRTFDocument;
import rtf.AdvancedRTFEditorKit;
class ExampleFrame extends JFrame{
private JMenuBar bar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem saveItem = new JMenuItem("Save");
private JMenuItem loadItem = new JMenuItem("Load");
private JTextPane txtPane = new JTextPane(new AdvancedRTFDocument());
private JScrollPane scroller = new JScrollPane(txtPane);
private JFileChooser chooser = new JFileChooser();
private AdvancedRTFEditorKit rtfKit = new AdvancedRTFEditorKit();
//ctor begins...
public ExampleFrame(){
super("Example Editor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 400);
this.setLocationRelativeTo(null);
saveItem.addActionListener(new SaveHandler());
loadItem.addActionListener(new LoadHandler());
this.addDragAndDropSupportToJTextPane(txtPane);
//set the kit...
txtPane.setEditorKit(rtfKit);
//create the menu...
fileMenu.add(saveItem);
fileMenu.add(loadItem);
bar.add(fileMenu);
this.setJMenuBar(bar);
//create the main panel...
JPanel mainPane = new JPanel();
mainPane.setLayout(new BorderLayout());
mainPane.add(BorderLayout.CENTER , scroller);
this.setContentPane(mainPane);
}//end of ctor.
//inner event handler classes...
class SaveHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showSaveDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
try(BufferedWriter bw = new BufferedWriter(
new FileWriter(chooser.getSelectedFile().getPath())))
{
rtfKit.write(bw, txtPane.getDocument(), 0, txtPane.getDocument().getLength());
bw.close();
JOptionPane.showMessageDialog( ExampleFrame.this,"Saved");
txtPane.setText("");
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
class LoadHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
int response = chooser.showOpenDialog(ExampleFrame.this);
if(response == JFileChooser.APPROVE_OPTION){
StringBuilder sb = new StringBuilder();
try(BufferedReader bw = new BufferedReader(
new FileReader(chooser.getSelectedFile().getPath())))
{
txtPane.setText("");
rtfKit.read(bw, txtPane.getDocument(), 0);
bw.close();
}catch(IOException | BadLocationException ex){
System.err.println(ex);
}
}
}//end of method.
}
private void addDragAndDropSupportToJTextPane(JTextPane thePane){
thePane.setDragEnabled(true);
thePane.setDropMode(DropMode.INSERT);
}//end of method.
}//end of class ExampleFrame.
public class SSCCEeditor {
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new ExampleFrame().setVisible(true);
}
});
}
}
Thanks a lot for your time!
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.