Restrict TextArea using Unicode with Java - java

I have a TextArea that I am trying to restrict user inputs to allow only IP addresses format in that Area. So I thought of only allowing digits and decimal points. For multiple IPs, One IP per line, so the TextArea needs to accept new lines. For the most part what I have below is working except for delete. I can't delete any entry even if I am using the associate Unicode. I am running MAC OS 10, not sure if it makes any difference or not but the info is out there just in case.
public class RestrictIpInputTextArea extends TextArea {
#Override
public void replaceText(int i, int il, String string){
if(string.matches("[0-9_\\u000A_\\u232B_\\u0008_\\u2421_._\\u007F]") || string.isEmpty()){
super.replaceText(il, il, string);
}
}
#Override
public void replaceSelection(String string) {
super.replaceSelection(string);
}

I was able to find out the solution for it. Visit the link below for more reference.
http://docs.oracle.com/javafx/2/ui_controls/custom.htm
However, I still want to explore TextFormatter function deployed in JavaFX 8U40
public class numericValue extends TextArea {
#Override
public void replaceText(int start, int end, String text) {
String old = getText();
if (text.matches("[0-9_._\\u000A]*")) {
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text) {
String old = getText();
if (text.matches("[0-9_._\\u000A]*")) {
super.replaceSelection(text);
}
}
}

Related

Desing pattern suggestions for sequential jobs which follows previous steps output

I want to design a subtitle-word parser. It works like that;
Check subtitle provider for availability
Fetch subtitle as inputStream
Convert inputStream to lines of text
Parse lines to sections ( A subtitle file includes 100 - 110 sections )
Parse sections' sentences to words
Save subtitle, section and word to DB
As you see every step follows previous steps output.
Which design pattern(s) I should use?
I'd consider using state design pattern, which is like strategy design pattern but contains current state in its context.
So you'd have something like this:
class ProcessingData {
private State state = new CheckAvailabilityState();
//Fill with all data related to the subtitle-word parser
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
interface State {
void next(ProcessingData processingData);
void prev(ProcessingData processingData);
void execute();
}
class CheckAvailabilityState implements State {
#Override
public void next(ProcessingData processingData) {
processingData.setState(new FetchSubtitlesState());
}
#Override
public void prev(ProcessingData processingData) {
//this is 1st step so no prev
}
#Override
public void execute() {
//Availability check goes here ..
}
}
class FetchSubtitlesState implements State {
#Override
public void next(ProcessingData processingData) {
//ConvertState
}
#Override
public void prev(ProcessingData processingData) {
processingData.setState(new CheckAvailabilityState());
}
#Override
public void execute() {
//Fetching goes here ...
}
}
But I'm not sure about complexity or the need for design patterns considering the problem.

What is a good way to display status of a file using Swing

I want to do the following and I would need some suggestions on what is the best way to do it.
I have a JList which displays the files that the user adds by clicking add (+) button and removes the files when the user clicks remove (-) button. With each added file, I want to associate an icon which should indicate the status of the file. For example, if the user has only added the file and not run the file (I have another JButton for running the application with the selected file), then this icon should be red and once the user runs it, this icon should change to green. Also, if the user removes the file by clicking the (-) button, it should remove the icon associated with that particular file too. Below is a pictorial representation of what I want.
I was thinking of associating a ImageIcon with each added file but I am not sure how to change its appearance to display the status. I am also not sure how the ImageIcon can be removed when the file is removed. Is there any other way (other than ImageIcon) to do it? Any help/suggestions are appreciated.
In programming, data is king. How that data get's represented should not be of consideration to the data, that's the domain/responsibility of the UI/view layers.
This is often represented by the model-view-controller pattern
In your example, you have two pieces of (basic) information. A file and a status (not run, run, deleted), you want to combine this information as "data". In Java, that typically means a Plain Old Java Object (or Pojo)
Because the status only has a limited number of possibilities, we can use a enum to represent it, and thereby restricting the valid values
public enum FileStatus {
NOT_RUN, RUN, DELETED;
}
And then we can create our own pojo...
public class FileOperation {
private File file;
private FileStatus status;
public FileOperation(File file, FileStatus status) {
this.file = file;
this.status = status;
}
public FileOperation(File file) {
this(file, FileStatus.NOT_RUN);
}
public File getFile() {
return file;
}
public FileStatus getStatus() {
return status;
}
public void setStatus(FileStatus newStatus) {
if (status == newStatus) {
return;
}
this.status = newStatus;
}
}
Now, when we want to know the status of the file, we know where to get it.
But what about the JList? You ask, good question. What we really want is some way that the JList can be informed when the status of any FileOperation object changes.
Now, you could iterate over the ListModel, but that's not a very clean solution, a better solution is to allow the FileOperation to generate events when it changes and have the ListModel listen for them and take it's own action.
This is a basic concept of an observer patternÆ’
There's a number of ways you might do this, but I'm lazy, so I'm just going to use the available property change API
public class FileOperation {
private File file;
private FileStatus status;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public FileOperation(File file, FileStatus status) {
this.file = file;
this.status = status;
}
public FileOperation(File file) {
this(file, FileStatus.NOT_RUN);
}
public File getFile() {
return file;
}
public FileStatus getStatus() {
return status;
}
public void setStatus(FileStatus newStatus) {
if (status == newStatus) {
return;
}
FileStatus oldStatus = status;
status = newStatus;
propertyChangeSupport.firePropertyChange("status", oldStatus, status);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
}
And now we need a ListModel which can respond to it...
public class FileOperationListModel extends AbstractListModel<FileOperation> {
private List<FileOperation> items = new ArrayList<FileOperation>(25);
private PropertyChangeListener handler = new PropertyChangeHandler();
public void add(FileOperation fo) {
fo.addPropertyChangeListener(handler);
int size = items.size();
items.add(fo);
fireIntervalAdded(this, size, size);
}
public void remove(FileOperation fo) {
int index = items.indexOf(fo);
if (index < 0) {
return;
}
fo.removePropertyChangeListener(handler);
items.remove(fo);
fireIntervalRemoved(this, index, index);
}
#Override
public int getSize() {
return items.size();
}
#Override
public FileOperation getElementAt(int index) {
return items.get(index);
}
public class PropertyChangeHandler implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (!(evt.getSource() instanceof FileOperation)) {
return;
}
FileOperation fo = (FileOperation) evt.getSource();
int index = items.indexOf(fo);
fireContentsChanged(FileOperationListModel.this, index, index);
}
}
}
Now, the final piece of the puzzle, is you're going to need a custom ListCellRenderer which can display the information you want.
For that, you're going to have to start by reading How to use lists and Writing a Custom Cell Renderer

How to dynamically handle commands in a chat program?

My question is more of a design issue than anything else. I'm currently developing a classic Server-Client chat program in Java. Everything is fine until I get to the commands. I thought it would be convenient for users to send commands that would then be treated by the server for changing their nickname for example. The thing is I want to make flexible code and above all, object-oriented code. To avoid endless if/else if statements to know what command was typed I believe it would be better to create a class for each command which inherit from a superclass Command. Then I could return the specific command through a getCommand() function overriden in all subclasses. But it does not solve my problem at all. The server still needs to test with instanceof what command has been returned. One way to do it dynamically would be to sort of auto downcasting it from the superclass Command and then call the appropriate function in the server class. For example:
public void processCommand(CommandNick c) {}
public void processCommand(CommandKick c) {}
But I haven't found any proper way of doing that and even if I did, I feel like there's still a design issue here. And I am convinced there is a nice and flexible way to do it but days weren't enough for me to figure it out. Any ideas? Thanks in advance! :)
I assume your server receives the message as an Object with a Sender and a String. Create your Command classes, and in the server init code, make a HashMap<String, AbstractCommand> with a String as key and your AbstractCommand class as value. Your commands should extend this class. Register all your commands, like so:
commandRegistry.put("help", new HelpCommandHandler());
I assume a command is a message with a ! before it. So when you receive a message, check if it is a command:
Message message = (Your Message)
String messageBody = message.getBody();
Sender messageSender = message.getSender();
if(messageBody.startsWith("!")) {
// Split the message after every space
String[] commandParts = messageBody.split(" ");
// The first element is the command base, like: !help
String baseCommand = commandParts[0];
// Remove the first character from the base, turns !help into help
baseCommand = baseCommand.substring(1, baseCommand.length());
// Creates a new array for the arguments. The length is smaller, because we won't copy the command base
String[] args = new String[commandParts.length - 1];
// Copy the elements of the commandParts array from index 1 into args from index 0
if(args.length > 0) {
System.arraycopy(commandParts, 1, args, 0, commandParts.length - 1);
}
// Your parse method
processCommand(sender, baseCommand, args);
}
public void processCommand(Sender sender, String base, String[] args) {
if(commandRegistry.containsKey(base)) {
commandRegistry.get(base).execute(sender, args);
} else {
// Handle unknown command
}
}
public abstract class AbstractCommand {
public abstract void execute(Sender sender, String[] args);
}
Sample implementation. I assume your server is a Singleton, and you can get on Object of it with Server.get() or any similar method.
public class HelpCommandHandler extends AbstractCommand { /* !help */
#Override
public void execute(Sender sender, String[] args) {
sender.sendMessage("You asked for help."); // Your code might not work like this.
}
}
public class ChangeNickCommandHandler extends AbstractCommand { /* !changenick newNick */
#Override
public void execute(Sender sender, String[] args) {
// I assume you have a List with connected players in your Server class
String username = sender.getUsername(); // Your code might not work like this
Server server = Server.get(); // Get Server instance
server.getUsers().get(username).setNickname(args[0]); // Argument 0. Check if it even exists.
}
}
// Server class. If it isn't singleton, you can make it one like this:
public class Server {
private static Server self;
public static Server init(/* Your args you'd use in a constructor */) { self = new Server(); return get(); }
public static Server get() { return self; }
private List<User> users = new List<User>();
private HashMap<String, AbstractCommand> commandRegitry = new HashMap<>();
// Make construcor private, use init() instead.
private Server() {
commandRegistry.put("help", new HelpCommandHandler());
commandRegistry.put("changenick", new ChangeNickCommandHandler());
}
// Getters
public List<User> getUsers() {
return users;
}
public HashMap<String, AbstractCommand> getRegistry() {
return commandRegistry;
}
}
This is a bit of pseudo code to illustrate that your controller doesn't need to know about the command processors (no need for instanceof).
abstract class CommandProcessor {
/* return boolean if this Command processed the request */
public static boolean processCommand(String command, User user, Properties chatProperties, Chat chat);
}
/* Handle anything */
public class CommandRemainder extends CommandProcessor {
#Override
public static boolean processCommand(String command, User user, Properties chatProperties, Chat chat) {
chat.appendText("[" + user.getName() + "] " + command);
return true;
}
}
/* Handle color changing */
public class CommandColorizer extends CommandProcessor {
protected static List<String> ALLOWED_COLORS = new ArrayList<>(Arrays.asList("red", "blue", "green"));
#Override
public static boolean processCommand(String command, User user, Properties chatProperties, Chat chat) {
if ("fg:".equals(command.trim().substring(0,3)) {
String color = command.trim().substring(3).trim();
if (ALLOWED_COLORS.contains(color)) {
chat.setForeground(color);
}
return true;
}
return false;
}
}
public class ChatController {
protected Chat chat = new Chat();
protected User user = getUser();
protected Properties chatProperties = getChatProperties();
protected List<CommandProcessor> commandProcessors = getCommandProcessors();
{
chat.addChatListener(new ChatListener(){
#Override
public void userChatted(String userChatString) {
for (CommandProcessor processor : commandProcessors) {
if (processor.processCommand(userChatString, user, chatProperties, chat)) {
break;
}
}
}
});
}
List<CommandProcessor> getCommandProcessors() {
List<CommandProcessor> commandProcessors = new ArrayList<>();
commandProcessors.add(new CommandColorizer());
commandProcessors.add(new CommandRemainder()); // needs to be last
return commandProcessors;
}
}

How to add properly UiHandler for BlurEvent in GWT?

Normally if we have some textField in GWT we can add a BlurHandler by the following code:
textField.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent event) {
//what we need
}
});
But if we use UiBinder and our textField is annotated by #UiField and it is mentioned in our ui.xml file we can add BlurHandler by this code as well:
#UiHandler("textField")
protected void createBlurHandler(BlurEvent event) {
}
I guess I am right here because it works like this. So, the question is, can we actually define BlurHandler inside ui.xml file?
For example, it is possible to add inputMaxLength and some other attributes there, does GWT has some possibility like onChange method or are these ways that I described the only possibilities?
I would like to have something like this:
<g:TextBox ui:field="textField" onBlur="methodName" />
Is it possible?
I am pretty sure what you are asking is not possible. The problem is that you wouldn't be able to use reflection to figure out which method you want to call. However you can extends the TextBox class and use that inside your template. The extended class could have it's own properties that can be set in the template. An example is as follows where I set the default test on my own DefaultTextBox.
public class DefaultTextBox extends TextBox {
/**
* The text color used when the box is disabled and empty.
*/
private static final String TEXTBOX_DISABLED_COLOR = "#AAAAAA";
private final String defaultText;
public #UiConstructor
DefaultTextBox(final String defaultText) {
this.defaultText = defaultText;
resetDefaultText();
// Add focus and blur handlers.
addFocusHandler(new FocusHandler() {
#Override
public void onFocus(FocusEvent event) {
getElement().getStyle().clearColor();
getElement().getStyle().clearFontStyle();
if (defaultText.equals(getText())) {
setText("");
}
}
});
addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent event) {
if ("".equals(getText())) {
resetDefaultText();
}
}
});
}
public String getDefaultText() {
return defaultText;
}
#Override
public void setText(String text) {
if (text == null) {
super.setText(getDefaultText());
} else {
getElement().getStyle().clearColor();
getElement().getStyle().clearFontStyle();
super.setText(text);
}
}
public String getText() {
return super.getText();
}
/**
* This is override so that the editor framework will not get the default
* value but the actual null value when the default text is in the box.
*/
#Override
public String getValue() {
try {
return getValueOrThrow();
} catch (ParseException e) {
return null;
}
}
#Override
public void setValue(String value) {
setText(value);
}
/**
* This is overridden from the parent class because this is
* how the editor gets the value.
*/
public String getValueOrThrow() throws ParseException {
if (defaultText.equals(super.getValueOrThrow())) {
return null;
}
return super.getValueOrThrow();
}
/**
* Reset the text box to the default text.
*/
public void resetDefaultText() {
setText(defaultText);
getElement().getStyle().setColor(TEXTBOX_DISABLED_COLOR);
getElement().getStyle().setFontStyle(FontStyle.ITALIC);
}
}
Then in the template you can set properties like this.
<w:DefaultTextBox defaultText="name" ui:field="nameTextBox" />
This will also work with setters, you can set properties without having to use the #UiConstructor but in my case I wanted to make sure that there was no empty constructor for this class.

Disable modify\delete JTextArea content (but not insert)

I have JTextArea component and I need to disable modify\delete current content in component by users. Users may only add\insert some text at the end, but setText method must work as usual.
tnx
I need to disable modify\delete current content in component by users.
textArea.setEditable( false );
Users may only add\insert some text at the end, but setText method must work as usual.
You should have an "Add Text" button that will take text from a separate text field and then append the text to the Document using the append(...) method of the JTextArea.
Could you post an example of what you already have?
To clarify, if you want users to be unable to certain things, you may need to re-insert the original text manually. I'm unsure of the editor used by a JTextArea, but you could try overriding that.
Horrific code I'm coming up with on the spot incoming, you can probably do this much easier:
private static String mand = "mandatory.";
private static JTextArea test = new JTextArea(mand);
public static String getMand() {
return mand;
}
public static JTextArea getTest() {
return test;
}
public static void setMand(String mand2) {
mand = mand2;
}
public static void setTest(JTextArea test2) {
test = test2;
}
getTest().addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent arg0) {
// do nothing
}
#Override
public void keyReleased(KeyEvent arg0) {
// do nothing
}
#Override
public void keyTyped(KeyEvent arg0) {
if(getTest().getText().startsWith(getMand())) {
System.out.println("good, text still present");
setMand(test.getText());
} else {
getTest().setText(getMand());
}
}
});
WARNING :: if the user makes any mistakes in adding information to the JTextArea, the code will not allow the user to fix these mistakes.
Tested successfully under JDK (/JRE) 7.

Categories

Resources