Java syntax highlighting with Highlight.js - highlight.js

I'm using highlight.js to style Java and it's generating markup for strings, keywords and numbers but not for types and literals. I'm using highlight.js/9.11.0.
Suggestions?
See example: https://codepen.io/amandaw/pen/bWMraO
CSS
.hljs-variable {
color: red
}
.hljs-type {
color: orange
}
.hljs-literal {
color: yellow
}
HTML
<pre><code class="java">
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Date d1 = new Date();
Calendar cl = Calendar. getInstance();
cl.setTime(d1);
System.out.println("today is "+ d1.toString());
cl. roll(Calendar.MONTH, 100);
System.out.println("date after a month will be " + cl.getTime().toString() );
cl. roll(Calendar.HOUR, 70);
System.out.println("date after 7 hrs will be "+ cl.getTime().toString() );
}
}
</code></pre>

Related

How to create a restart method using JFrame?

recently I started learning Java, I watched a YT video where a programmer used static methods and variables to create a simple guess game using JFrame.
Afterwards I tried to implement a close/restart button, after reading some Threads I relized static methods arenĀ“t made that for. So my question is now how do I solve my problem now. :)
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ThreadLocalRandom;
public class main extends JFrame {
JLabel text = new JLabel("Please choose a number between 1 & 10 ");
JLabel textVersuch = new JLabel();
JButton button = new JButton("Try");
int myNumber = ThreadLocalRandom.current().nextInt(1,10+1);
JTextField textField = new JTextField();
int count = 0;
//is there a better way to hide all this information, but still keep them useable for my methods?
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.openUI(); //error occurs
}
//How do I manage to start my method openUI() to start my game?
public void openUI(){
JFrame frame = new JFrame("Program");
frame.setSize(400,400);
frame.setLocation(800,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultLookAndFeelDecorated(true);
text.setBounds(0,50,400,25);
textVersuch.setBounds(300,0,100,25);
textField.setBounds(0,150,50,25);
button.setBounds(50,150,100,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String textFromTextfield = textField.getText();
int number = Integer.parseInt(textFromTextfield);
if(number<1 || number>10){
text.setText("Your number has to be between 1 & 10 ");
textField.setText("");
}else{
guess(number);
}
}catch (Exception error){
text.setText("Please enter a digit! ");
textField.setText("");
}
}});
frame.add(button);
frame.add(textField);
frame.add(text);
frame.add(textVersuch);
frame.setLayout(null);
frame.setVisible(true);
}
public void close(JFrame frame){
frame.dispose(); //here I want to close the game
}
public void guess(int number ) throws InterruptedException {
count++;
textVersuch.setText(count + " tries!");
if(number == myNumber){
text.setText("You was right! " + " You tried " + count + " time(s) :)" );
button.setText("Restart");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//How can I restart my JFrame?
}
});
} else if (count < 3) {
text.setText("Wrong guess! Retry");
if (number < myNumber){
text.setText("Your searched number is bigger than" + number );
}else {
text.setText("Your searched number is lower than" + number );
}
} else {
text.setText("Sorry, you lost the number was " + myNumber);
}
textField.setText("");
}
}

Why are my validations not working from input file?

Full respect for your talents, please ignore how awful my code is. I am no natural and appreciate many of you will find my coding offensive!
I am wanting to create a GUI that 1 -chooses a text file, 2- displays the text to text panel and 3- validates the code ( i have a valid and invalid text file to demonstrate the validations work).
I can get points 1 and 2 to work but none of my validations are erroring when i select an invalid text file.
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.JTextArea;
import javax.swing.KeyStroke;
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.util.Scanner;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Image;
public class MainClass extends JFrame implements ActionListener {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
// Creates new Window Frame with title and sets app to close on clicking cross
JFrame frame = new JFrame("SE2 - Graphics Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates JFrame as top level container in hierarchy
Container toplevelContainer = frame.getContentPane();
// Sets Grid Layout
GridLayout layout = new GridLayout(1, 0);
frame.setLayout(layout);
// Splits Panel into 2 halves and sets parameters for text panel and area
String str = "This is the area your imported text will be displayed";
JTextArea TextPanel = new JTextArea(str);
TextPanel.setBackground(Color.YELLOW);
TextPanel.setEditable(false);
TextPanel.setLineWrap(true);
TextPanel.setWrapStyleWord(true);
frame.add(TextPanel);
// calls graphicspanel class
GraphicsPanel grp = new GraphicsPanel();
toplevelContainer.add(grp);
grp.drawLine(Color.BLACK, 100, 100, 200, 100);
grp.drawLine(Color.BLACK, 200, 100, 200, 200);
grp.drawLine(Color.BLACK, 200, 200, 100, 200);
grp.drawLine(Color.BLACK, 100, 200, 100, 100);
// adds graphic panel to frame
frame.pack();
frame.setVisible(true);
// Creates new menubar within frame
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
// Creates new menu with new jmenuitems for File (load,save,exit) with shortcuts
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem load = new JMenuItem("Load");
load.setIcon(new ImageIcon("Images/Looad.png"));
load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, KeyEvent.SHIFT_MASK));
file.add(load);
// enables user to browse and choose files to load from filepath
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try
{
// reads file and displays in text panel
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
TextPanel.read(br, null);
br.close();
TextPanel.requestFocus();
File Fileobject = new File(filename);
#SuppressWarnings("resource")
Scanner fileReader = new Scanner(Fileobject);
fileReader = new Scanner(Fileobject);
while (fileReader.hasNext())
{
String line = fileReader.nextLine();
String[] splitArray = line.split(" ");
String command = splitArray[0];
if (command.contains ("MOVE"))
{
String MOVE = splitArray[0];
String x1 = splitArray[1];
String y1 = splitArray[2];
if (isNumeric(MOVE))
{
JOptionPane.showMessageDialog(null, "Command cannot be a number");
}
if(isLetter(x1))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
if(isLetter(y1))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("LINE"))
{
String LINE = splitArray[0];
String x2 = splitArray[1];
String y2 = splitArray[2];
if (isNumeric(LINE))
{
JOptionPane.showMessageDialog(null, "Command cannot be a number");
}
if(isLetter(x2))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
if(isLetter(y2))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if(command.contains("CIRCLE"))
{
String CIRCLE =splitArray[0];
int r = Integer.parseInt(splitArray[1]);
if(r < 0)
{
JOptionPane.showMessageDialog(null, "Must be positive number");
}
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("SOLID_CIRCLE"))
{
String SOLID_CIRCLE = splitArray[0];
try {
int r = Integer.parseInt(splitArray[1]);
if(r<0)
{
JOptionPane.showMessageDialog(null, "Must be positive number");
}
}
catch(NumberFormatException e) {
}
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("CLEAR"))
{
JOptionPane.showMessageDialog(null, "Commands have been cleared");
}
else if (command.contains("COLOUR"))
{
String Colour = splitArray[0];
int red = Integer.parseInt(splitArray[1]);
int green = Integer.parseInt(splitArray[2]);
int blue = Integer.parseInt(splitArray[3]);
if(red>255)
if(red<0)
if (green>255)
if(green<0)
if(blue>255)
if(blue<0)
{
JOptionPane.showMessageDialog(null, "Colour values must range between 0 and 255");
}
else if (command.contains("TEXT"))
{
String text = null;
if(isNumeric(text))
{
JOptionPane.showMessageDialog(null, "Text must not contain numbers");
}
if (!contains(""))
{
JOptionPane.showMessageDialog(null, "Text must contain double quotation marks");
}
}
}
}
}
}}
//confirm checks are complete for user
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error Check Complete");
}
}
private boolean contains(String string) {
// TODO Auto-generated method stub
return false;
}
private boolean isLetter(String string) {
// TODO Auto-generated method stub
return false;
}
private boolean isNumeric(String command) {
// TODO Auto-generated method stub
return false;
}
});
// adds image icon and shortcut keys to JMenuItems
JMenuItem save = new JMenuItem("Save");
save.setIcon(new ImageIcon("Images/Saveas.png"));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.SHIFT_MASK));
// Attempt at requirement 4 to add functionality to save JMENUITEM
// save.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent ae) {
// JFileChooser fc = new JFileChooser();
// fc.showSaveDialog(this);
// encoder.encode(image);
// byte[] jpgData = bos.toByteArray();
// FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg");
// fos.write(jpgData);
// fos.close();
file.add(save);
JMenuItem exit = new JMenuItem("Exit");
exit.setIcon(new ImageIcon("Images/Exiit.png"));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.SHIFT_MASK));
file.add(exit);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem about = new JMenuItem("About");
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.SHIFT_MASK));
help.add(about);
// Adds Action listener to display dialog box with app description
about.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(about,
"This Application allows you to import, save and display graphical content from a file containing a set of instructions.",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
frame.setVisible(true);
class exitaction implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new exitaction());
}
protected static int isEmpty() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

speak text as Type

Javafx:How can text-to speech is done on animated text; I have applied a typewriter effect on text to make animated text, and now i want that it will speak word by word as typed. P.S. for Text-to-Speech iam using the "FreeTTS is a speech synthesis engine"
here is code snippet of my project
public void AnimattedTextToSpeech()
{
// Text to Speech
Voice voice;
VoiceManager vm=VoiceManager.getInstance();
voice=vm.getVoice("kevin16");
voice.allocate();
// TypeWritter Effect to the text
String str="Welcome! This is the Lesson number one";
final IntegerProperty i = new SimpleIntegerProperty(0);
Timeline timeline = new Timeline();
KeyFrame keyFrame = new KeyFrame(Duration.seconds(0.1), event2 -> {
if (i.get() > str.length()) {
timeline.stop();
} else {
textArea.setText(str.substring(0, i.get()));
i.set(i.get() + 1);
textArea.requestFocus();
textArea.end();
}
});
voice.speak(str);
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
But it is speaking every character as it is typing. But i want it speak word by word.
This works but it seems like you need to run the speech on a different thread.
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import java.util.concurrent.atomic.AtomicInteger;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* #author blj0011
*/
public class FreeTTTS extends Application
{
#Override
public void start(Stage primaryStage)
{
TextArea textArea = new TextArea();
// Text to Speech
Voice voice;
VoiceManager vm = VoiceManager.getInstance();
voice = vm.getVoice("kevin16");
voice.allocate();
// TypeWritter Effect to the text
String str = "Welcome! This is the Lesson number one";
final IntegerProperty i = new SimpleIntegerProperty(0);
Timeline timeline = new Timeline();
AtomicInteger startIndex = new AtomicInteger();
AtomicInteger endIndex = new AtomicInteger();
KeyFrame keyFrame = new KeyFrame(Duration.seconds(0.1), event2 -> {
if (i.get() >= str.length()) {
timeline.stop();
startIndex.set(endIndex.get());
endIndex.set(i.get());
String word = str.substring(startIndex.get(), endIndex.get()).trim().replaceAll("[^a-zA-Z ]", "");
System.out.println(word);
voice.speak(word);
}
else {
textArea.appendText(Character.toString(str.charAt(i.get())));
if (str.charAt(i.get()) == ' ') {
if (endIndex.get() == 0) {
endIndex.set(i.get());
String word = str.substring(startIndex.get(), endIndex.get()).trim().replaceAll("[^a-zA-Z ]", "");
System.out.println(word);
voice.speak(word);
}
else {
startIndex.set(endIndex.get());
endIndex.set(i.get());
String word = str.substring(startIndex.get(), endIndex.get()).trim().replaceAll("[^a-zA-Z ]", "");
System.out.println(word);
voice.speak(word);
}
}
i.set(i.get() + 1);
}
});
//voice.speak(str);
StackPane root = new StackPane(textArea);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
//voice.speak("Hello World");
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
I imagine you should divide text into strings, and start TTS the moment you start TypeWritter effect for each string.
Like this:
String str1 = "Welcome! This is the Lesson number one";
String[] temp = str1.split(" ");
final IntegerProperty i = new SimpleIntegerProperty(0);
Timeline timeline = new Timeline();
for (String str : temp) {
KeyFrame keyFrame = new KeyFrame(Duration.seconds(0.1), event2 -> {
if (i.get() > str.length()) {
timeline.stop();
} else {
textArea.setText(str.substring(0, i.get()));
i.set(i.get() + 1);
textArea.requestFocus();
textArea.end();
}
});
voice.speak(str);
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}

GWT - Fading in/out a background image

I have a custom class as follows which works fine, the button grows/shrinks to accomodate the text and the bg image changes on a click.
Probem I want to solve is how to "fadeIN" one or other image when clicked/notClicked is called
Here is my code
public ExpandingOvalButton(String text) {
if (text.length() > 15) {
label.getElement().getStyle().setFontSize(20, Unit.PX);
} else {
label.getElement().getStyle().setFontSize(30, Unit.PX);
}
int width = 120;
initWidget(panel);
label.setText(text);
// width = width + (text.length() * 8);
String widthStr = width + "px";
image.setWidth(widthStr);
image.setHeight("100px");
button = new PushButton(image);
button.setWidth(widthStr);
button.setHeight("50px");
panel.add(button, 0, 0);
panel.add(label, 18, 14);
}
public void isClicked()
{
image.setUrl("images/rectangle_green.png");
}
public void unClicked()
{
image.setUrl("images/rectangle_blue.png");
}
#Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
public void setButtonEnabled(boolean enabled) {
// panel.setVisible(enabled);
// this.label.setVisible(enabled);
this.button.setVisible(enabled);
}
Here's a general utility class to fade any element:
public class ElementFader {
private int stepCount;
public ElementFader() {
this.stepCount = 0;
}
private void incrementStep() {
stepCount++;
}
private int getStepCount() {
return stepCount;
}
public void fade(final Element element, final float startOpacity, final float endOpacity, int totalTimeMillis) {
final int numberOfSteps = 30;
int stepLengthMillis = totalTimeMillis / numberOfSteps;
stepCount = 0;
final float deltaOpacity = (float) (endOpacity - startOpacity) / numberOfSteps;
Timer timer = new Timer() {
#Override
public void run() {
float opacity = startOpacity + (getStepCount() * deltaOpacity);
DOM.setStyleAttribute(element, "opacity", Float.toString(opacity));
incrementStep();
if (getStepCount() == numberOfSteps) {
DOM.setStyleAttribute(element, "opacity", Float.toString(endOpacity));
this.cancel();
}
}
};
timer.scheduleRepeating(stepLengthMillis);
}
}
Calling code for instance:
new ElementFader().fade(image.getElement(), 0, 1, 1000); // one-second fade-in
new ElementFader().fade(image.getElement(), 1, 0, 1000); // one-second fade-out
You could use GwtQuery. It provides fadeIn & fadeOut effects (and many other JQuery goodies), it is cross-browser compatible and seems to be pretty active.

SWT application crashes in Windows 7

I have a java SWT application that works OK with Windows XP and Windows Vista. But when I run it on Windows 7, weird errors occure, and it crashes.
For example, in a method where I call Table.removeAll() I get a java.lang.ArrayIndexOutOfBoundsException: 0. The table has SWT.VIRTUAL in style.
Another problem is when I write something in a text box (there's a ModifyListener which filters something) - after 2 characters, the cursor moves at the beginning (before first character).
The SWT version is 3.5, but I tried with the latest from the eclipse website(3.6M3) and the result is the same.
Are there any known issues? Has anybody encountered this?
Here is a snippet that doesn't work in Windows 7:
import java.util.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class TableCheck {
Shell shell;
Button button1, button2, button3;
UltraTable ut;
public TableCheck() {
Display display = new Display();
shell = new Shell(display);
shell.setLayout(new GridLayout(4, false));
Text text = new Text(shell, SWT.SINGLE | SWT.LEAD | SWT.READ_ONLY | SWT.BORDER);
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
text.setText("SWT " + SWT.getPlatform() + " " + SWT.getVersion() + "; "
+ System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
+ System.getProperty("os.arch"));
SelectionAdapter listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (e.widget == button1) {
ut.setContent(Arrays.asList("01", "34", "test", "test2", "123", "1test", "test2"));
} else if (e.widget == button2) {
ut.setContent(Arrays.asList("Str1", "Str2", "Str3"));
} else {
ut.setContent(Collections.emptyList());
}
}
};
button1 = new Button(shell, SWT.PUSH);
button1.setText("Data 1");
button1.addSelectionListener(listener);
button2 = new Button(shell, SWT.PUSH);
button2.setText("Data 2");
button2.addSelectionListener(listener);
button3 = new Button(shell, SWT.PUSH);
button3.setText("Data 3");
button3.addSelectionListener(listener);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1);
gd.widthHint = gd.heightHint = 320;
ut = new UltraTable(shell, SWT.MULTI | SWT.BORDER | SWT.VIRTUAL | SWT.FULL_SELECTION);
ut.table.setLayoutData(gd);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
class UltraTable {
private Table table;
private static final String DATA_COLLECTION = "<<CC>>", DATA_LISTENER = "<<VL>>";
public UltraTable(Composite parent, int style) {
table = new Table(parent, style);
table.setLinesVisible(true);
table.setHeaderVisible(true);
TableColumn tableColumn = new TableColumn(table, SWT.NONE);
tableColumn.setText("Column");
tableColumn.setWidth(64);
}
void setContent(Collection<?> collection) {
if ((table.getStyle() & SWT.VIRTUAL) != 0) {
table.setData(DATA_COLLECTION, collection);
table.clearAll();
table.setItemCount(collection.size());
if (table.getData(DATA_LISTENER) == null) {
Listener listenerSD = new Listener() {
public void handleEvent(Event event) {
Collection<?> collectionW = (Collection<?>) event.widget.getData(DATA_COLLECTION);
Object object = collectionW.toArray(new Object[collectionW.size()])[event.index];
((TableItem) event.item).setText(0, object.toString());
}
};
table.setData(DATA_LISTENER, listenerSD);
table.addListener(SWT.SetData, listenerSD);
}
}
}
}
public static void main(String[] args) {
new TableCheck();
}
}
The SWT versions I checked is (as shown in the text in the shell):
SWT win32 3550; Windows 7 6.1 x86
SWT win32 3617; Windows 7 6.1 x86
I have resolved this problem after asking the same question.
You must either remove SWT.VIRTUAL or update to the SVN build of SWT. I've posted a bug report on the SWT bug page.
Edit: your code snippet has a bug in it that is causing the ArrayIndexOutOfBoundsException. You can resolve it by changing lines containing listenerSD:
public void handleEvent(Event event) {
Collection<?> collectionW = (Collection<?>) event.widget
.getData(DATA_COLLECTION);
if (collectionW.size() > event.index) {
Object object = collectionW
.toArray(new Object[collectionW.size()])[event.index];
((TableItem) event.item).setText(0, object
.toString());
}
}
On Windows 7, the table updates the visible items immediately when clearAll() is called. So
table.clearAll();
must be after the line
table.setItemCount(collection.size());

Resources