Java ClipBoard Problem - java

I am writing a GUI for animation in Java. I am completely stumped on one element. I have a 2 JTextAreas that are called InputText, and OutputText where the input is copied to the output area with the use of a copy Jbutton. I then have a Next and Previous Button that should switch through frames on the OutputText area. I used a JLabel as a counter in between these two buttons.
What I am trying to do is use the clipboard to hold each "frame" if you will, on the Output JTextArea as I flip through the counter. As well as return the text once I flip backwards through the counter. Is this even possible? I have looked through multiple links online that describe Clipboard usage, but none of the examples that I have come across give a solid understanding how to do this.
Please see code below:
*Note I have left out unimportant elements that I already know work! Thanks!
This is called at the top of my Java file:
private Clipboard clipbd = getToolkit().getSystemClipboard();
public static final int MAX_COUNT = 10;
//sets maximum for count
public static final int MIN_COUNT = 1;
//sets minimum for count
private int count = 1;
//sets up integer for counter
This is called in the ActionListener:
public void actionPerformed ( ActionEvent event ) {
boolean status = false;
String OutputText1;
if(event.getSource()== CopyButton){
//get text from InputText
OutputText1 = InputText.getText();
//put text into OutputText field
OutputText.setText(OutputText1);
}//end if for CopyButton
if(event.getSource() == NextButton){
//LabelOutPut.setText("Next");
if (count < MAX_COUNT) {
count++;
}//end if
LabelCounter.setText("" + count);
OutputText.setText("");
}//end if for NextButton
if(event.getSource() == PreviousButton){
//LabelOutPut.setText("Previous");
if(count > MIN_COUNT){
count--;
}//end if
LabelCounter.setText("" + count);
}//end if for PreviousButton

Why would you use a Clipboard to hold text. Just use a String and the data is in the control of your program. I don't see any reason to complicate your processing.
Also, follow standard Java naming conventions. Varible names should NOT start with an upper cased character.
LabelCounter ==> labelCounter

You only need the SystemClipboard if you want to get copied/pasted data from places outside your program. If you just have to copy between 2 places in your own program, and you need history etc... just use a variable in your code (string, or list of strings, or whatever) and just update this when they click the button. Camickr mentions the same as well...

Related

Fix to Eclipse 3.6.2 bug that displays Combo text right aligned

Eclipse 3.6.2 has this bug documented here
https://bugs.eclipse.org/bugs/show_bug.cgi?id=358183
There are a couple of suggested workarounds. The first one did not work for me, but the second one did.
combo.addListener(SWT.Resize, new Listener() {
#Override
public void handleEvent(final Event e) {
//We need the original text, not the displayed substring which would return methods such as combo.getText() or combo.getItem(combo.getSelectionIndex())
String text = combo.getItem((int) combo.getData("selectionIndex"));
//reset text limit
combo.setTextLimit(text.length());
GC gc = new GC(combo);
//exact dimensions of selected text
int textWidth = gc.stringExtent(text).x;
int magicConst = 14;
int comboWidth = combo.getClientArea().width - magicConst;
//In case the text is wider then the area on which it's displayed, we need to set a textLimit
if (textWidth > comboWidth) {
//find text limit - first we set it according to average char width of our text
int averageCharWidth = textWidth / text.length();
int tempLimit = comboWidth / averageCharWidth;
//sometimes on resize it can happen that computed tempLimit is greater than text length
if (tempLimit >= text.length()) {
tempLimit = text.length() - 1;
}
//then we fine-tune the limit - it must be as precise as possible
while (tempLimit > 0 && (comboWidth < gc.stringExtent(text.substring(0, tempLimit + 1)).x)) {
tempLimit--;
}
//textLimit must not be zero
if (tempLimit == 0) {
tempLimit++;
}
combo.setTextLimit(tempLimit);
}
combo.setText(text);
gc.dispose();
}
});
However, when I implement this, the widget thinks that user has changed some data (state change). This may be because of the call above to
combo.setText(text);
As our system is set up, there is a call to
org.eclipse.ui.forms.ManagedForm.isDirty()
which results in a prompt to the user to save the data every time user exits the form.
I am not familiar at all with SWT or jFace. Can anyone tell me
Is there any other way to get around the Eclipse 3.6 bug?
If not, is there a way for me to clear the dirty state of the Combo box so that the user is not prompted to save?
Thanks
Just setting the text of a Combo won't automatically set a ManagedForm to be dirty. So you must be adding a modify listener to the combo in order to do the set dirty.
You can remove the modify listener from the combo just before you do the setText and then add it back after the setText. This should stop the dirty flag from being set.

JTextArea updating after KeyListener? [duplicate]

First off I making a simple typing program. If you type the a letter and hit the spacebar the TTextArea will be matched with the label text to see if it matches. But it keeps coming out wrong cause there is space added before the letter after the first output everytime and I do not understand why? Is this something that just happens or can ypu
The is my code
public void keyTyped(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_SPACE){
input = textArea.getText();
if(input.length() <= 0){
JOptionPane.showMessageDialog(null, "Type something first");
} else {
input.trim();
System.out.println(input);
gameLogic.score(input, letterLabel.getText());
gameLogic.error(input, letterLabel.getText());
scoreLabel.setText("Score: " + String.valueOf(gameLogic.score));
errorLabel.setText("Errors: " + String.valueOf(gameLogic.error));
gameLogic.changeDifficulty();
letterLabel.setText( gameLogic.changeText());
textArea.setText("");
textArea.setCaretPosition(0);
}
}
this is my output
l
l
x
k
ss
Several things...
KeyListener is not a recommend way to deal with monitoring or effecting the changes to any text component. If you are lucky enough that the key stroke isn't consumed by the component, the component has already being updated with the last key stroke.
A better approach would be to use a DocumentListener if you just wanted to monitor changes to the text component or a DocumentFilter if you want to change what is being passed to the field.
Check out Using Text Components for more details

How to collect only one value from a JToggleButton when a mouse moves over the container?

I am working on doing a word finder puzzle game. When I am trying to get to happen is a user clicks on a letter then moves his mouse across other letters to create a word. I am having some problems with the listeners. I have been going back and fourth using mouseDragged and mouseMoved. So far mouseMoved seems to work better because it dynamically grabs values. The problem is I can't figure out how to get it only grab one value. In an ideal world it would move of a Button or label grab that value once and ignore the value till it reaches a new button or label. Currently it just grabs values at every instant a mouse is on that container. The logic for my Mouse method is below:
public void mouseMoved(MouseEvent e) {
int count = countClicked;
int num = 0;
for(JToggleButton row : puzzleGrid){
if(e.getComponent() == row && count == 1) {
if(num == 0){
num++;
for(JLabel l: solWords)
{
sb.append(row.getText());
System.out.println(l.getText()+" = "+ sb.toString());
if(l.getText().contentEquals(row.getText()))
System.out.println(row.getText());
}
}
}
}
}
I am using the value gathered from the containers to check against an array of JLabels containing the solution values.
You could store the last letter in a static variable:
static String lastLetter = null;
mouseMoved(...) {
if(row.getText().equals(lastLetter)) {
continue;
}
lastLetter = row.getText();
}

Text editor in NetBeans

I am trying to implement a text editor in NetBeans with simple functions like: text styling (bold, italic, underlined ...), open file, save file and search. Search function searches for a specified string in the document and highlights the results. The problem occurs when I am trying to remove those highlights or add new ones for different search. Currently I use StyledDocument object together with jTextPane.
private void textHighlight(int startAt, int endAt, Color c) {
Style sCh;
sCh = textEditor.addStyle("TextBackground", null);
StyleConstants.setBackground(sCh, c);
StyledDocument sDoc = textEditor.getStyledDocument();
sDoc.setCharacterAttributes(startAt, endAt - startAt, sCh, false);
}
private void textFind(java.awt.event.ActionEvent evt) {
int searchIndex = 0;
String searchValue = searchField.getText();
if(lastIndex != -1) {
while(searchIndex < lastIndex) {
countOccurencies++;
int i = textEditor.getText().indexOf(searchValue, searchIndex);
textHighlight(i, i+searchValue.length(), Color.MAGENTA);
searchIndex = i+searchValue.length();
}
statusLabel.setText(countOccurencies + " rezultatov.");
} else {
statusLabel.setText("Ni rezultatov!");
}
}
}
private void searchEnd(java.awt.event.ActionEvent evt) {
textEditor.removeStyle("TextBackground");
}
removeStyle() doesn't seem to be working.
Must admit I don't know how Styles work, but maybe the attributes of the Style are copied to the Document at the time you add the Style?
Another option is to use the Highlighter class. See textPane.getHighlighter(). Then you can keep track of the individual highlights you add in an ArrayList and then use the ArrayList to remove the highlights when you want the clear the text pan.
Also, inside your search loop you have a couple of problems:
Don't use the getText() method. This can cause problems with text offsets being off by one for every line of text in the text pane. See Text and New Lines for more information and the solution.
You are getting the text inside the loop which is not very efficient. You should only get the text once outside the loop.

Comparing components via setName() .

I am coding an image puzzle game and one part of the code is to compare the pieces the user has selected to the pieces of the correct image.
Each image piece is already added to a JButton as an ImageIcon.
An identifier is required to differentiate each image piece apart and also for comparision.
I am setting a setName() for each JButton created as the identifier.
The comparison starts when the user releases the mouse after he drags the puzzle pieces from the original 3x3 grid where the shuffled pieces are to the other 3x grid for matching.
I have problems removing the error from the comparison if statement.
I got the comparison idea from this SO thread - link
private JButton[] button = new JButton[9];
private JButton[] waa = new JButton[9];
private String id;
private int cc;
private String id2;
private int cc2;
// setName for each of the 9 buttons in the original 3x3 grid being created
// which stores the shuffled puzzle pieces
for(int a=0; a<9; a++){
button[a] = new JButton(new ImageIcon());
id += Integer.toString(++cc);
button[a].setName(id);
}
// setName for each of the 9 buttons in the other 3x3 grid
// where the images will be dragged to by the user
for(int b=0; b<9; b++){
waa[b] = new JButton();
id2 += Integer.toString(++cc2);
waa[b].setName(id2);
}
// check if puzzle pieces are matched in the correct place
// compare name of original 'button' array button with the name of 'waa' array buttons
button[a].addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent m){
if(m.getbutton().getName().equals (waa.getName())){
}
else{
JOptionPane.showMessageDialog(null,"Wrong! Try Again.");
}
}
}
In your mouseReleased event m.getButton() is returning the mouse button that was clicked. You'll want to do something more like this that will get you closer:
if (m.getComponent().getName().equals(waa.getName())) {
m.getComponent() returns the Component object (your JButton) that the event was fired from. From there you can do the comparison with the getName approach you are using.
There's an additional issue in that your waa variable is an array. I'm not sure how you want to compare them, whether running through the arrays and making sure the index and names match, but that's an additional issue you need to look into.
JButton uses an ActionListener to trigger notifications back to your program to indicate when it's been triggered. This allows the button to respond to different types of event, including the mouse, keyboard and program triggers.
As apart of the action API, you can supply an action command for each button. See JButton#setActionCommand
Basically you would integrate it in a simular way to your mouse listener...
public void actio Performed(ActionEvent evt) {
if (command.equals(evt.getActionCommand()) {...}
}
Depending on your requirements, it might even be easier to use the Action API
The problem you are actually having is waa is an array, therefore, it doesn't have a getName method. I'm also unclear as to why you have two arrays of buttons?

Categories

Resources