Showing PDF in JScrollPane with Aspose - java

I'm trying to use Aspose PDF Kit (4.7.0) to display a PDF in JScrollPane as documented in their javadoc, using PdfViewer.showPdf() method.
The result is that I can only see 1 page of my -very simple- document and it is not being correctly rendered:
Here is my code below:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import com.aspose.pdf.kit.PdfViewer;
public class SimplePdfViewer extends JFrame
{
/**
* serialVersionUID
*/
private static final long serialVersionUID = -494213537688110764L;
public SimplePdfViewer()
{
try
{
// Aspose license initialisation
Aspose.init();
PdfViewer pdfviewer = new PdfViewer();
pdfviewer.openPdfFile("src/main/resources/10 pages.pdf");
//decode the pdf page, I also tried pdfViewer.decodeAllPages() and only the last one is displayed.
pdfviewer.decodePage(1);
pdfviewer.setPdfPageParameters(1, 1);
JScrollPane displayScrollPane = pdfviewer.showPdf();
getContentPane().add(displayScrollPane, BorderLayout.CENTER);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
getContentPane().add(new JLabel(e.getMessage()));
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new SimplePdfViewer();
}
}
Am I missing something ?

Ok, be aware that it is actually not implemented :
http://www.aspose.com/community/forums/permalink/419184/419184/showthread.aspx#419184

Related

How to refresh/reload an image in Swing GUI as the real image file changes?

I am trying to implement Remote FrameBuffer Protocol using Java socket programming.
I have a server side program that takes screenshot of the entire screen using robot and store it in BufferedImage .Then I converted it into a byte array and sending it to the client .
Objective :
To display the entire screen of the server side machine in a Swing GUI of the client side.
Problem i am facing :
i am able to send the image in bytes from server and receive it from the server by the client (client.java) and convert it into a jpg image (output.jpg) using ImageIO and put that image in a Swing frame.
But i am able to see the first image in the Swing and whenever the image gets updated ,the image in the Swing is not updating or refreshing .
What I want :
I want the image to refresh and show updated image every time the server sends the image data .
client.java
package remoteclient;
import java.lang.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class client {
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",5900);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int width=0,height=0;
try {
width = din.readInt(); //getting width and height from server thru socket.
height = din.readInt();
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame("Client");
JLabel label = new JLabel();
f.setSize(width, height);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
boolean continueLoop = true;
while(continueLoop)
{
try {
int len = din.readInt();
byte[] imageInByte = new byte[len];
System.out.println(len);
din.readFully(imageInByte);
System.out.println(imageInByte);
ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
BufferedImage bImage2 = ImageIO.read(bis);
// Image im1 = bImage2.getScaledInstance(width,height, Image.SCALE_SMOOTH);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
bImage2 = ImageIO.read(new File("output.jpg"));
label.setIcon(new ImageIcon(im1));
ImageIcon icon = new ImageIcon(bImage2);
icon.getImage().flush();
label.setIcon( icon );
f.getContentPane().add(label, BorderLayout.CENTER);
f.pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
What I want :
I want the image to refresh and show updated image every time the server sends the image data .
Updated code with comments about demo code that should be removed from your working code:
Here's an example, using default UIManager icons, and SwingWorker, as noted in the comments to the original posting. You would instead use images from your server connection.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
public class SwingLabelWithUpdatedImage {
public static void main(String args[]) throws Exception {
final JLabel label = new JLabel("", SwingConstants.CENTER);
final JFrame frame = new JFrame("Client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label, BorderLayout.CENTER);
final Dimension preferredSize = new Dimension(200, 100);
frame.setPreferredSize(preferredSize);
frame.setVisible(true);
frame.pack();
final ImageUpdateWorker task = new ImageUpdateWorker(label);
task.execute();
}
public static class ImageUpdateWorker extends SwingWorker<Void, IconInfo> {
// iconInfoList is not need in your code. It's here so I can
// supply a dummy set of icons to demonstrate UI updates.
final List<IconInfo> iconInfoList;
private JLabel label;
ImageUpdateWorker(JLabel label) {
this.label = label;
// Delete this in your code
this.iconInfoList = initIconInfoList();
}
#Override
public Void doInBackground() {
boolean isTrue = true;
while (isTrue) {
// Put your socket code to read the next icon from a server.
// You don't need to do the ImageIO.write(), ImageIO.read() dance,
// unless you must save the icon to disk. In that case, you don't need
// to read it back in.
// Here, I just rotate the iconInfoList to make it
// appear as though a new icon was received.
// Your code will not have any need to do this.
Collections.rotate(iconInfoList, -1);
// Just publish the icon you create from the image
// you receive from your remote server.
publish(iconInfoList.get(0));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void process(List<IconInfo> icons) {
// You might check for an empty list.
// #kleopatra's suggestion to get the last icon is correct.
// See https://docs.oracle.com/javase/tutorial/uiswing/concurrency/interim.html
IconInfo iconInfo = icons.get(icons.size() - 1);
label.setIcon(iconInfo.icon);
// Your code will not do this
label.setText(iconInfo.name);
// You can get the icon dimensions just from the icon,
// so you don't really need the IconInfo class.
label.setSize(iconInfo.dimension);
}
/** Demo code only. It doesn't belong in your working code.
*/
protected List<IconInfo> initIconInfoList() {
// Just a quick way to get some icons; don't need to
// fetch from a server just to demonstrate how to
// refresh the UI.
List<IconInfo> iconInfoList = UIManager.getDefaults().keySet().stream()
.filter(this::isIconKey)
.map(IconInfo::new)
.filter(iconInfo -> iconInfo.icon != null)
.collect(Collectors.toList());
return iconInfoList;
}
/** Demo code only. It doesn't belong in your working code.
*/
protected boolean isIconKey(Object key) {
return String.class.isAssignableFrom(key.getClass())
&& ((String) key).toLowerCase().contains("icon");
}
}
/** This is just a convenience to convey
* the icon and its UIManager key (i.e., name).
* Your remote server doesn't supply a name,
* so you don't really need this class.
* It's just to make the demo more expressive.
*/
public static class IconInfo {
final private String name;
final private Icon icon;
final private Dimension dimension;
IconInfo(Object name) {
this.name = name.toString();
icon = UIManager.getIcon(name);
dimension = icon == null
? new Dimension(32, 32)
: new Dimension(icon.getIconWidth(), icon.getIconHeight());
}
}
}

Playing sound in Java using java.applet class

I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}

JTextPane Line Count Including Icons and Components

I've recently been experimenting with the user of JTextPanes for an upcoming project I'll be working on, there have been various posts online detailing how to go about counting the number of lines within the text pane however the solutions I found all seem to fail when inserting Icons or Components into the text pane's document.
The solution I found that worked for plain text was this one (with the solution implemented of course): BadLocationException when using Utilities.getRowStart On hit of Enter key
However once I try to insert a Component (JLabel) or a plain Icon for that matter, the getRowStart() method from Utilities throws a null pointer exception. What I find unusual about this is the Java Doc states that "...This is represented in the associated document as an attribute of one character of content. ", so I assumed it would treat it as any other character but it seems this is not the case.
I've included a code example to replicate the problem if anyone would like to try it. I have a feeling that it just simply isn't possible, which would be a shame.
import java.awt.Dimension;
import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Utilities;
public class Test{
private JFrame frame;
private JTextPane textPane;
private Image img;
private URL imgURL;
public Test(){
frame = new JFrame();
frame.setSize(new Dimension(500,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textPane = new JTextPane();
try {
imgURL = new URL("http://www.freeiconspng.com/uploads/floppy-save-icon--23.png");
img = ImageIO.read(imgURL);
JLabel label = new JLabel(new ImageIcon(img.getScaledInstance(10, 10, Image.SCALE_SMOOTH)));
textPane.insertComponent(label);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frame.getContentPane().add(textPane);
frame.setVisible(true);
}
public JTextPane getTextPane(){
return this.textPane;
}
public int getLineCount(){
int totalCharacters = textPane.getDocument().getLength();
int lineCount = (totalCharacters == 0) ? 1 : 0;
try {
int offset = totalCharacters;
while (offset > 0) {
offset = Utilities.getRowStart(textPane, offset) - 1;
lineCount++;
}
} catch (BadLocationException e) {
e.printStackTrace();
}
return lineCount;
}
public static void main(String[] args){
Test t = new Test();
t.getLineCount();
}
}
The problem was solved after the following comment:
It doesn't throw any exception for me once I wrap the content inside
your main method inside a EventQueue.invokeLater() call. I.e.:
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Test t = new Test();
t.getLineCount();
}
});

fileName cannot be found in addActionListener, JAVA

I'm trying to make a function to play an audio when an user clicks a button. The problem is that when I tried to pass in the fileName from the parameter using "fileName.addActionListener", it says that fileName cannot be found even though it's referenced in the parameter. What did I do wrong, and how can I fix this? Thanks.
package sunaudiodemo;
import static java.awt.Color.blue;
import static java.awt.Color.green;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import sun.audio.*; //import the sun.audio package
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class SunAudioDemo {
public static void playAudioOnClick (final String fileName) {
//*******************************************
fileName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
playAudio(fileName);
} catch (Exception ex) {
Logger.getLogger(SunAudioDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
//*******************************************
}
public static void playAudio (String text) throws Exception {
// identify the sound file as a File class object
File soundFile = new File(text);
// Open an input stream for the File object soundFile
// This allows Java to read the file.
InputStream inFile = new FileInputStream(soundFile);
// Create an AudioStream from the input stream.
// This tells Java to read the incoming data as sound data.
AudioStream audio = new AudioStream(inFile);
// play the sound file using the start method from Audioplayer.player
AudioPlayer.player.start(audio);
}
public static void main(String[] args) throws Exception {
// create a frame to hold our components
JFrame myJFrame = new JFrame();
// create a new a grid layout for the frame - 5 rows x 2 cols, gaps=20
GridLayout myLayout = new GridLayout(5,2);
myLayout.setHgap(20);
myLayout.setVgap(20);
// assign myLayout to be the layout for MyJFrame
myJFrame.setLayout(myLayout);
// Create a button with text OK
JButton wav1 = new JButton("Play Audio 1");
myJFrame.add(wav1); // Add the OK button
playAudioOnClick("wav2.wav");
// set the title, size, location and exit behavior for the JFrame
myJFrame.setTitle("Play Audio");
myJFrame.setSize(360, 480);
myJFrame.setLocation(200, 100);
myJFrame.getContentPane().setBackground( green );
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// make the frame visible (activate the frame)
myJFrame.setVisible(true);
} // end main()
} // end class SunAudioDemo
In the code above, fileName is defined as a String. Assuming this is java.lang.String, there is no method addActionListener(). You need to pass in a reference to your button so you can add the ActionListener to it.

Simple Java editor GUI

Hello i create the GUI code for simple Java editor
i create the menu but i need to match
File: New: Create a new file. asking for the name of the file (and therefore the public class) and the directory in which it will be stored. With the creation of the file is inserted into the structure of the public class, for example public class MyClass{ }.
Open: opens files with source code java ( .java).
Save : saves the current snippet on the same file with this established during the creation of.
Save as : displays the dialog box where you requested the name of the file, the format of the directory in which it will be stored. The format will be java file ( .java). The main part of the window will have the editor to be used by the user to edit a file source Java.
The main part of the window will have the editor to be used by the user to edit a file source Java. information which will be renewed during the processing of a snippet: Number lines Number reserved words in java source code
Formatting Text
Each file will open formatted and will formatted when processed in the following rules: The reserved words of java will appear with color blue.
The comments will appear in green
The String Literals with orange
All other with black
The Font will be Courier Font size 12pt
i will provide the GUI code can anyone help me with the above ?
Regards
Antonis
// ClassEEFrame
package editor.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
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.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class EEFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -1709009137090877913L;
private GridBagLayout layout;
private GridBagConstraints constraints;
private EEMenuBar menuBar;
private EETextPane editor;
private EEConsole console;
private EEStatusBar statusBar;
private File file;
public EEFrame() throws HeadlessException {
super("Elearn Editor");
JScrollPane scrollPane;
layout = new GridBagLayout();
setLayout(layout);
constraints = new GridBagConstraints();
menuBar = new EEMenuBar();
setJMenuBar(menuBar);
editor = new EETextPane();
scrollPane = new JScrollPane(editor);
scrollPane.setBorder(new TitledBorder("Editor"));
setConstraints(1, 100, GridBagConstraints.BOTH);
addComponent(scrollPane, 0, 0, 1, 1);
console = new EEConsole();
scrollPane = new JScrollPane(console);
scrollPane.setBorder(new TitledBorder("Console"));
setConstraints(1, 40, GridBagConstraints.BOTH);
addComponent(scrollPane, 1 ,0 ,1, 1);
statusBar = new EEStatusBar();
setConstraints(1, 0, GridBagConstraints.BOTH);
addComponent(statusBar, 2, 0, 1, 1);
file = null;
}
public JTextPane getTextPane() {
return this.editor;
}
public void setLines(int lines) {
this.statusBar.setLines(lines);
}
public void setWords(int words) {
this.statusBar.setJavaWords(words);
}
private void setConstraints(int weightx, int weighty, int fill) {
constraints.weightx = weightx;
constraints.weighty = weighty;
constraints.fill = fill;
}
private void addComponent(Component component, int row, int column, int width, int height) {
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
add(component);
}
private class EEMenuBar extends JMenuBar {
/**
*
*/
private static final long serialVersionUID = -2176624051362992835L;
private JMenu fileMenu, compilationMenu;
private JMenuItem newItem, openItem, saveItem, saveAsItem, exportItem, compileProcessItem, compileClassItem;
public EEMenuBar() {
super();
fileMenu = new JMenu("File");
newItem = new JMenuItem("New");
newItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/* TODO Dispay dialog with inputs class name and file path */
}
});
fileMenu.add(newItem);
openItem = new JMenuItem("Open");
openItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Open existing java source file*/
}
});
fileMenu.add(openItem);
saveItem = new JMenuItem("Save");
saveItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO save changes to file*/
}
});
fileMenu.add(saveItem);
saveAsItem = new JMenuItem("Save As");
saveAsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Save as new java source file*/
}
});
fileMenu.add(saveAsItem);
exportItem = new JMenuItem("Export to pdf");
exportItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO save as pdf(formatted)
}
});
fileMenu.add(exportItem);
add(fileMenu);
compilationMenu = new JMenu("Compilation");
compileProcessItem = new JMenuItem("Compile with system jdk");
compileProcessItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Compile java source code and show results in teminal(inside editor)*/
}
});
compilationMenu.add(compileProcessItem);
compileClassItem = new JMenuItem("Compile with JavaCompiler Class");
compileClassItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Call system compiler for file*/
}
});
compilationMenu.add(compileClassItem);
add(compilationMenu);
}
}
private class EETextPane extends JTextPane {
/**
*
*/
private static final long serialVersionUID = -7437561302249475096L;
public EETextPane() {
super();
//add styles to document
Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
StyleConstants.setForeground(def, Color.BLACK);
StyleConstants.setFontFamily(def, "Courier");
StyleConstants.setFontSize(def, 12);
Style keyword = addStyle("keyword", def);
StyleConstants.setForeground(keyword, Color.BLUE);
Style literal = addStyle("literal", def);
StyleConstants.setForeground(literal, Color.ORANGE);
Style comment = addStyle("comment", def);
StyleConstants.setForeground(comment, Color.GREEN);
}
}
private class EEConsole extends JTextPane {
/**
*
*/
private static final long serialVersionUID = -5968199559991291905L;
public EEConsole() {
super();
//add styles to document
Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
StyleConstants.setForeground(def, Color.BLACK);
StyleConstants.setFontFamily(def, "Courier");
StyleConstants.setFontSize(def, 12);
Style keyword = addStyle("error", def);
StyleConstants.setForeground(keyword, Color.RED);
Style literal = addStyle("success", def);
StyleConstants.setForeground(literal, Color.GREEN);
}
}
private class EEStatusBar extends JPanel {
/**
*
*/
private static final long serialVersionUID = 185007911993347696L;
private BoxLayout layout;
private JLabel linesLabel, lines, wordsLabel, words;
public EEStatusBar() {
super();
layout = new BoxLayout(this, BoxLayout.X_AXIS);
setLayout(layout);
linesLabel = new JLabel("Lines : ");
linesLabel.setAlignmentX(LEFT_ALIGNMENT);
add(linesLabel);
lines = new JLabel("");
lines.setAlignmentX(LEFT_ALIGNMENT);
add(lines);
add(Box.createRigidArea(new Dimension(10,10)));
wordsLabel = new JLabel("Java Words : ");
wordsLabel.setAlignmentX(LEFT_ALIGNMENT);
add(wordsLabel);
words = new JLabel("");
words.setAlignmentX(LEFT_ALIGNMENT);
add(words);
}
public void setLines(int lines) {
/*TODO set line numbers */
}
public void setJavaWords(int words) {
/*TODO set java keyword numbers*/
}
}
}
//class Main
package editor.app;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import elearning.editor.gui.EEFrame;
import elearning.editor.util.EECodeFormater;
import elearning.editor.util.EEJavaWordCounter;
import elearning.editor.util.EELineCounter;
public class EEditor {
/**
* #param args
*/
public static void main(String[] args) {
try {
// Set cross-platform Java L&F (also called "Metal")
//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
//Set Motif L&F
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
//Set Nimbus L&F
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
//Set System L&F
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//Set GTK L&F --> Same as System L&F on Linux and Solaris\
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
//Set Windows L&F --> Same as System L&F on Windows
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (UnsupportedLookAndFeelException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
catch (InstantiationException e) {
// handle exception
}
catch (IllegalAccessException e) {
// handle exception
}
EEFrame frame = new EEFrame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
/* TODO Instatiate Threads */
/*TODO Start Threads */
}
}
Also i provide a mockup of it:
Mockup
First you should have a look at the File class. It provides you methods to create, open, modify and save files. To read files you also might want to give BufferedReader or any other Reader a shot.
Creating a file: File has the method createNewFile(), use it in combination with exists().
To open and read a file use a try-with-resource (There's actually a nice tutorial about it in the Java Manuals).
To save a file you should check out the FileWriter, it can write strings or append them to files.
For your editor you might want to replace the before mentioned BufferedReader with a LineReader, which also provides methods to get the line number. Other than that you have to figure out yourself how to number the lines. (Actually it's just googling around a lot, there will be some ideas like this one - which I didn't check in detail but it might help).
Of course for the editor you should first read the file into a string, use a formatter for it and then you can present it and reformat it when needed.
Apart from these hints I can not provide you with more detailed answers, as you can also read in the comments it would be easier if you would provide more detailed questions. You now just gave us a GUI which has almost nothing to do with your actual problems.
Show us some of your (problematic) work and we can help you, but otherwise we can not do much more than giving you some hints as I just did. So try to think about your problems, try how to ask for more precise answers and open some new questions if you want.
But don't forget to check out the site for answers, for me almost all of my questions I'd like to ask are already asked somewhere in a similar manner.
Hello again lets split work into steps ,
firstly i would like to create the new,open,save ,save as , export into pdf menu and event
below is the code that i used ,the GUI frame open correctly with new ,open,save, save as ,export into pdf labels but as action nothing happened.
Could someone write to me the correct code for that? be in mind i am very java beginner.
public EEMenuBar() {
super();
fileMenu = new JMenu("File");
//Create the New menu item
newItem = new JMenuItem("New");
newItem.setMnemonic(KeyEvent.VK_N);
newItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
fileMenu.add(newItem);
openItem = new JMenuItem("Open");
openItem.setMnemonic(KeyEvent.VK_0);
openItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
/*TODO Open existing java source file*/
}
});
fileMenu.add(openItem);
saveItem = new JMenuItem("Save");
saveItem.setMnemonic(KeyEvent.VK_S);
saveItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO save changes to file*/
}
});
fileMenu.add(saveItem);
saveAsItem = new JMenuItem("Save As");
saveAsItem.setMnemonic(KeyEvent.VK_A);
saveAsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
/*TODO Save as new java source file*/
}
});
fileMenu.add(saveAsItem);
exportItem = new JMenuItem("Export to pdf");
exportItem.setMnemonic(KeyEvent.VK_E);
exportItem.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO save as pdf(formatted)
}
});
fileMenu.add(exportItem);

Categories