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.
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 have written a Java GUI program which opens a text file and reads the data in the left panel. Now I want to display a graph of the data read from the same file on the right panel.
I have used JFileChooser to open files and read the data and display them on a text area. I want the data read from the file to be displayed using a two dimensional X-Y graph. The axis of the graph should be labeled using the label information specified in the data file. The values on the X-axis should begin from the x-axis start value specified, with intervals which increment at a rate determined by the x-axis interval value. The values on the Y-axis will need to be determined from the data itself. Each point plotted on the graph should be joined using a single line.
I have used several methods but none worked. I have tried reading each line on the text file as arrays and use the arrays as the dataset, but it didn't work as well. Please help me plot a graph from the data on the text file. Any help would be appreciated. Thanks.
P.S The graph should be plotted using AWT/Swing libraries only.
The data on the file is as follows:
Title: Effect of Age on Ability
Xlabel: Age
Ylabel: Ability
start: 0
interval: 15
0, 3, 4.2, 7, 5.1, 10, 3.2
Following are my code which I have written so far:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.BorderFactory;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
#SuppressWarnings("serial")
public class GUI extends JFrame {
private String[] readLines = new String[6];
public GUI() {
// Setting Title, size and layout
setTitle("Data Visualiser");
setSize(950, 1000);
setLayout(new BorderLayout());
// Creates a menubar for a JFrame
final JMenuBar menuBar = new JMenuBar();
// Add the menubar to the frame
setJMenuBar(menuBar);
// Define and add two drop down menu to the menubar, "file" and "help"
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
// adding menu items and icons to the "file" drop down menu,
final JMenuItem openAction = new JMenuItem("Open", new ImageIcon("images/Open-icon.png"));
final JMenuItem saveAction = new JMenuItem("Save", new ImageIcon("images/save-file.png"));
final JMenuItem exitAction = new JMenuItem("Exit", new ImageIcon("images/exit-icon.png"));
final JMenuItem aboutAction = new JMenuItem("About", new ImageIcon("images/about-us.png"));
//////////////////////////////////////////////////////////////////////////////////////////////
// Create a text area.
final JTextArea textArea = new JTextArea("");
textArea.setFont(new Font("Serif", Font.BOLD, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JScrollPane textScrollPane = new JScrollPane(textArea);
// textArea.add(textScrollPane, BorderLayout.CENTER); //add the
// JScrollPane to the panel
// Scrollbars
textScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textScrollPane.setPreferredSize(new Dimension(350, 550));
textScrollPane.setBorder(
BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Textual Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
// Create an graphics pane.
JPanel graphicsArea = new JPanel();
//graphicsArea.setFont(new Font("Serif", Font.BOLD, 16));
JScrollPane graphicsScrollPane = new JScrollPane(graphicsArea);
// Scrollbars
graphicsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
graphicsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
graphicsScrollPane.setPreferredSize(new Dimension(550, 550));
graphicsScrollPane.setBorder(
BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Graphical Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
// Put the graphics pane and the text pane in a split pane.
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.5);
JPanel rightPane = new JPanel(new GridLayout(1, 0));
rightPane.add(splitPane);
// Put everything together.
JPanel leftPane = new JPanel(new BorderLayout());
add(rightPane, BorderLayout.LINE_END);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// file menu shortcut
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(openAction);
// openAction.addActionListener(this);
openAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(openAction)) {
// using JFileChooser to open the text file
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
// fileChooser.setCurrentDirectory(new
// File(System.getProperty("user.home"))); // setting
// current
// directory
File file = fileChooser.getSelectedFile();
BufferedReader br = null;
try {
// FileReader fr = new FileReader(file);
Scanner f = new Scanner(file);
for (int i = 0; i < 6; i++) {
readLines[i] = f.nextLine();
textArea.setText(textArea.getText() + readLines[i] + "\n");
String array[] = readLines[i].split(" ");
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(new JFrame(), "File not found!", "ERROR!",
JOptionPane.ERROR_MESSAGE); // error message
// if file not
// found
} catch (NullPointerException e) {
// System.out.println(e.getLocalizedMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
});
fileMenu.add(saveAction);
fileMenu.add(exitAction);
// exit button shortcut
exitAction.setMnemonic(KeyEvent.VK_X);
exitAction.addActionListener(new ActionListener() {
// setting up exit button
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(exitAction)) {
System.exit(0);
}
}
});
fileMenu.addSeparator();
helpMenu.addSeparator();
helpMenu.add(aboutAction);
// about button shortcut
aboutAction.setMnemonic(KeyEvent.VK_A);
aboutAction.addActionListener(new ActionListener() {
// clicking on about button opens up a dialog box which contain
// information about the program
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(menuBar.getComponent(0),
"This program is based on the development of a data visualization tool. \n"
+ "The basic concept is to produce a piece of software which reads in raw textual data, \n"
+ "analyses that data, then presents it graphically to the user.",
"About Us", JOptionPane.PLAIN_MESSAGE);
}
});
}
}
Starting from your example, note the following:
Use a ChartPanel for your graphicsArea; then, your openAction() can simply invoke setChart().
Parse the chosen file in creatChart(); the title and data lines are shown, but the remaining attributes are left as an exercise.
Consider using Properties for your file format;
For greater flexibility, use Action as shown here.
To change the chart panel's default size, override getPreferredSize() as shown here.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
P.S. The graph should be plotted using AWT/Swing libraries only.
For a single chart, replace ChartPanel with JPanel and override paintComponent() to perform the rendering. You can transform coordinates using the approach is outlined here or here.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
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.FileReader;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
//* #see https://stackoverflow.com/a/36764715/230513 */
public class GUI extends JFrame {
public GUI() {
super("Data Visualiser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
menuBar.add(fileMenu);
menuBar.add(helpMenu);
final JMenuItem openAction = new JMenuItem("Open", new ImageIcon("images/Open-icon.png"));
final JMenuItem saveAction = new JMenuItem("Save", new ImageIcon("images/save-file.png"));
final JMenuItem exitAction = new JMenuItem("Exit", new ImageIcon("images/exit-icon.png"));
final JMenuItem aboutAction = new JMenuItem("About", new ImageIcon("images/about-us.png"));
final JTextArea textArea = new JTextArea(8, 16);
textArea.setFont(new Font("Serif", Font.BOLD, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JScrollPane textScrollPane = new JScrollPane(textArea);
textScrollPane.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Textual Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
ChartPanel graphicsArea = new ChartPanel(null);
graphicsArea.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Graphical Representation"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textScrollPane, graphicsArea);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.LINE_END);
fileMenu.setMnemonic(KeyEvent.VK_F);
fileMenu.add(openAction);
openAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(openAction)) {
JFileChooser fileChooser = new JFileChooser(new File("."));
if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
graphicsArea.setChart(creatChart(file));
}
}
}
private JFreeChart creatChart(File file) {
String title = null;
String xAxisLabel = null;
String yAxisLabel = null;
BufferedReader in = null;
int start = 0;
int interval = 0;
String data = null;
String line = null;
try {
in = new BufferedReader(new FileReader(file));
while ((line = in.readLine()) != null) {
textArea.append(line + "\n");
if (line.startsWith("Title")) {
title = line.split(":")[1].trim();
}
// parse other lines here
if (!line.contains(":")) {
data = line;
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
XYSeries dataset = new XYSeries(file.getName());
for (String s : data.split(",")) {
dataset.add(start, Double.valueOf(s));
start += interval;
}
return ChartFactory.createXYLineChart(title,
xAxisLabel, yAxisLabel, new XYSeriesCollection(dataset));
}
});
fileMenu.add(saveAction);
fileMenu.add(exitAction);
exitAction.setMnemonic(KeyEvent.VK_X);
exitAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource().equals(exitAction)) {
System.exit(0);
}
}
});
fileMenu.addSeparator();
helpMenu.addSeparator();
helpMenu.add(aboutAction);
aboutAction.setMnemonic(KeyEvent.VK_A);
aboutAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null,
"Visualization tool.",
"About Us", JOptionPane.PLAIN_MESSAGE);
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new GUI();
});
}
}
I'm stuck on how to save a file in a text editor i'm creating.Here's my code if you can help me
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import javax.swing.border.*;
public class test1 {
public static void main ( String[] args )
{
JButton b1 = new JButton("Press to read a file");
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Text Reading Box" ) );
// create the middle panel components
final JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false);
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
//Add Text area in to middle panel
middlePanel.add ( scroll );
// My code
JFrame frame = new JFrame ("Text Reader 0.4 Beta");
frame.add ( middlePanel );
frame.add(b1, BorderLayout.NORTH);
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible ( true );
frame.setLayout(new BorderLayout());
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
display.read(br, null);
br.close();
display.requestFocus();
}
catch(Exception error) {
System.err.println("Could'nt read a file");
}
}
});
}
}
I guess you should have another button say 'Save' to save your edited content back to the file. For that you have to handle action on save button and write contents back to the file.
package com.test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class Random
{
public static void main(String[] args)
{
JButton b1 = new JButton("Press to read a file");
JButton b2 = new JButton("Save");
JPanel middlePanel = new JPanel();
final StringBuilder filename = new StringBuilder("");
middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Text Reading Box"));
// create the middle panel components
final JTextArea display = new JTextArea(16, 58);
display.setEditable(true);
JScrollPane scroll = new JScrollPane(display);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
// Add Text area in to middle panel
middlePanel.add(scroll);
// My code
JFrame frame = new JFrame("Text Reader 0.4 Beta");
frame.add(middlePanel);
frame.add(b1, BorderLayout.NORTH);
frame.add(b2, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filename.append(f.getAbsolutePath());
try
{
FileReader reader = new FileReader(filename.toString());
BufferedReader br = new BufferedReader(reader);
display.read(br, null);
br.close();
display.requestFocus();
}
catch (Exception error)
{
System.err.println("Could'nt read a file");
}
}
});
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
String textToSet = display.getText();
try
{
PrintWriter writer = new PrintWriter(filename.toString(), "UTF-8");
writer.write(textToSet);
writer.close();
}
catch (FileNotFoundException | UnsupportedEncodingException exc)
{
System.err.println("Could'nt write to the file");
}
}
});
}
}
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.
I have been trying to left align buttons contained in a Box to the left, with no success.
They align left alright, but for some reason dont shift all the way left as one would imagine.
I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me.
Thanks, Eric
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.BoxLayout;
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.JScrollPane;
import javax.swing.JTextArea;
public class MainGUI extends Box implements ActionListener{
//Create GUI Components
Box centerGUI=new Box(BoxLayout.X_AXIS);
Box bottomGUI=new Box(BoxLayout.X_AXIS);
//centerGUI subcomponents
JTextArea left=new JTextArea(), right=new JTextArea();
JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right);
//bottomGUI subcomponents
JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info");
//Create Menubar components
JMenuBar menubar=new JMenuBar();
JMenu fileMenu=new JMenu("File");
JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit");
int returnVal =0;
public MainGUI(){
super(BoxLayout.Y_AXIS);
initCenterGUI();
initBottomGUI();
initFileMenu();
add(centerGUI);
add(bottomGUI);
addActionListeners();
}
private void addActionListeners() {
open.addActionListener(this);
save.addActionListener(this);
exit.addActionListener(this);
encrypt.addActionListener(this);
decrypt.addActionListener(this);
close.addActionListener(this);
info.addActionListener(this);
}
private void initFileMenu() {
fileMenu.add(open);
fileMenu.add(save);
fileMenu.add(exit);
menubar.add(fileMenu);
}
public void initCenterGUI(){
centerGUI.add(leftScrollPane);
centerGUI.add(rightScrollPane);
}
public void initBottomGUI(){
bottomGUI.setAlignmentX(LEFT_ALIGNMENT);
//setBorder(BorderFactory.createLineBorder(Color.BLACK));
bottomGUI.add(encrypt);
bottomGUI.add(decrypt);
bottomGUI.add(close);
bottomGUI.add(info);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// find source of the action
Object source=arg0.getSource();
//if action is of such a type do the corresponding action
if(source==close){
kill();
}
else if(source==open){
//CHOOSE FILE
File file1 =chooseFile();
String input1=readToString(file1);
System.out.println(input1);
left.setText(input1);
}
else if(source==decrypt){
//decrypt everything in Right Panel and output in left panel
decrypt();
}
else if(source==encrypt){
//encrypt everything in left panel and output in right panel
encrypt();
}
else if(source==info){
//show contents of info file in right panel
doInfo();
}
else {
System.out.println("Error");
//throw new UnimplementedActionException();
}
}
private void doInfo() {
// TODO Auto-generated method stub
}
private void encrypt() {
// TODO Auto-generated method stub
}
private void decrypt() {
// TODO Auto-generated method stub
}
private String readToString(File file) {
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader br=new BufferedReader(fr);
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String input="";
while(line!=null){
input=input+"\n"+line;
try {
line=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return input;
}
private File chooseFile() {
//Create a file chooser
final JFileChooser fc = new JFileChooser();
returnVal = fc.showOpenDialog(fc);
return fc.getSelectedFile();
}
private void kill() {
System.exit(0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MainGUI test=new MainGUI();
JFrame f=new JFrame("Tester");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(test.menubar);
f.setPreferredSize(new Dimension(600,400));
//f.setUndecorated(true);
f.add(test);
f.pack();
f.setVisible(true);
}
}
Read the section from the Swing tutorial on How to Use Box Layout. It explains (and has an example) of how BoxLayout works when components have different alignments.
The simple solution is to add:
centerGUI.setAlignmentX(LEFT_ALIGNMENT);
Not sure why the buttons are aligned the way they are, but it's probably because they are trying to align with the box above it (I'm sure someone better versed in Swing can give you a better answer to that one). A handy way to debug layout issues is to highlight the components with coloured borders, e.g. in your current code:
centerGUI.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(centerGUI);
bottomGUI.setBorder(BorderFactory.createLineBorder(Color.RED));
add(bottomGUI);
However, if I had those requirements, I'd use a BorderLayout, e.g. this code is loosely based on yours, I removed the unnecessary bits, to concentrate on the layout portion (you should do this when asking questions, it allows others to answer questions more easily)
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Tester {
private JPanel contentPanel;
private JTextArea leftTextArea = new JTextArea();
private JTextArea rightTextArea = new JTextArea();
private JMenuBar menuBar = new JMenuBar();
public Tester() {
initialisePanel();
initFileMenu();
}
public JPanel getContent() {
return contentPanel;
}
public JMenuBar getMenuBar() {
return menuBar;
}
private final void initialisePanel() {
contentPanel = new JPanel(new BorderLayout());
Box centreBox = new Box(BoxLayout.X_AXIS);
JScrollPane leftScrollPane = new JScrollPane(leftTextArea);
JScrollPane rightScrollPane = new JScrollPane(rightTextArea);
centreBox.add(leftScrollPane);
centreBox.add(rightScrollPane);
Box bottomBox = new Box(BoxLayout.X_AXIS);
bottomBox.add(new JButton(new SaveAction()));
bottomBox.add(new JButton(new ExitAction()));
contentPanel.add(centreBox, BorderLayout.CENTER);
contentPanel.add(bottomBox, BorderLayout.SOUTH);
}
private void initFileMenu() {
JMenu fileMenu = new JMenu("File");
fileMenu.add(new SaveAction());
fileMenu.add(new ExitAction());
menuBar.add(fileMenu);
}
class SaveAction extends AbstractAction {
public SaveAction() {
super("Save");
}
#Override
public void actionPerformed(ActionEvent e) {
handleSave();
}
}
void handleSave() {
System.out.println("Handle save");
}
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
}
#Override
public void actionPerformed(ActionEvent e) {
handleExit();
}
}
void handleExit() {
System.out.println("Exit selected");
System.exit(0);
}
public static void main(String[] args) {
Tester test = new Tester();
JFrame frame = new JFrame("Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(test.getContent());
frame.setJMenuBar(test.getMenuBar());
frame.setPreferredSize(new Dimension(600, 400));
frame.pack();
frame.setVisible(true);
}
}
Why not try using MiGLayout?
They have a lot of great online demos with source code, including lots of different alignment examples.