I've been trying to make a JTextArea display a certain String when F2 is pressed in a certain TextField, with no success as yet. Any help much appreciated.
My code may reveal how little programming experience I have:
final String ACTION_KEY = "this text";
public void actionPerformed(ActionEvent actionEvent) {
JTextField source = (JTextField) actionEvent.getSource();
System.out.println("Activated: " + source.getText());
textAreaInstructions.setText("this text");
}
};
KeyStroke F2 = KeyStroke.getKeyStroke("F2");
InputMap inputMap = timeStep.getInputMap();
inputMap.put(F2, ACTION_KEY);
ActionMap actionMap = timeStep.getActionMap();
actionMap.put(ACTION_KEY, actionListener);
EDIT: I'm now trying this code instead:
InputMap inputMap = timeStep.getInputMap();
Object actionSubmit = inputMap.get(KeyStroke.getKeyStroke("ENTER"));
Object actionSubmitSp = inputMap.get(KeyStroke.getKeyStroke("SPACE"));
System.out.println("actionSubmit for space = " + actionSubmitSp);
ActionMap actionMap = timeStep.getActionMap();
Action action = actionMap.get(actionSubmit);
System.out.println("actionSubmit = " + actionSubmit);
timeStep.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),
actionSubmit);
EDIT:
This prints
actionSubmit for space = null
actionSubmit = notify-field-accept
Is this any use?
The problem was nothing to do with the code posted. It was that I'd saved a backup of the file in the same package as the original and forgot to change the code, so the backup was being implemented rather than the updated original. That cost me a lot of time. lol.
EDIT: so anyway, now that I know which file I'm running, I found that the following code (which I got here: http://blog.marcnuri.com/blog/.../2007/06/06/Detecting-Tab-Key-Pressed-Event-in-JTextField-s-Event-VK-TAB-KeyPressed) does what I wanted (for tab instead of F2, but would obviously work for F2 too, in which case the first line wouldn't be needed):
timeStep.setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);
timeStep.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_TAB){
instruction = "tab pressed";
textAreaInstructions.setText(instruction);
lblTabEvent.setText(instruction);
// If you want to change the focus to the next component
timerInterval.grabFocus();
}
else {
textAreaInstructions.setText("got here, "+ e.getKeyCode());
}
}
});
Related
I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.
public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;
// this is called in my initComponent method to create both
textAreaDisplay = new JTextArea();
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + " ");
}
spDisplay = new JScrollPane(textAreaDisplay);
textAreaDisplay.setLineWrap(true);
textAreaDisplay.setWrapStyleWord(true);
spDisplay.setPreferredSize(new Dimension(500, 500));
// this is called in my createEvents method. After creating lakes in the database
// it will display the else statement but it is empty
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{
}
}
});
Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.
Some obvious issues:
textAreaDisplay = new JTextArea();
A JTextArea should be created with code like:
textAreaDisplay = new JTextArea(5, 20);
By specifying the row/column the text area will be able to calculate its own preferred size. Scrollbars should appear when the preferred size of the text area is greater than the size of the scroll pane.
spDisplay.setPreferredSize(new Dimension(500, 500));
Don't use setPreferredSize(). The scroll area will calculate its preferred size based on the preferred size of the text area.
textAreaDisplay.append(obj.toString() + " ");
I would think you want each Lake to show on a different line, so I would append "\n" instead of the space.
I was setting textAreaDisplay before anything was entered into the ArrayList and it would not run again after anything was entered. I moved the for loop down and into the actionPerformed event and works well now.
btnDisplayLake.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
for (Object obj : lake)
{
textAreaDisplay.append(obj.toString() + "\n");
}
if (lake.size() == 0)
{
JOptionPane.showMessageDialog(null, "No Lakes in database!");
}
else
JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
}
catch (Exception e1)
{
I'm making a simple "paint" application in JAVA. I would have wanted that when the person clicks the canvas, and make a drag and drop, a listener get the drop cursor location, but I don't find how make a drop listener. How can I find the location of the cursor when the user stop his click?
I have the following code for the drag :
Canvas paintC = new Canvas(shell, SWT.NONE);
paintC.addDragDetectListener(new DragDetectListener() {
public void dragDetected(DragDetectEvent arg0) {
Point controlRelativePos = new Point(arg0.x, arg0.y);
displayRelativePos1 = paintC.toDisplay(controlRelativePos);
GC gc = new GC(paintC);
gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_YELLOW));
gc.fillRectangle(arg0.x, arg0.y, 90, 60);
}
});
Should I a drag function in order to get the latest position?
Edit: I've tried this, but it didn't work :
dropTarget.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
displayRelativePos2 = dropTarget.getDisplay().getCursorLocation();
hauteur = displayRelativePos2.y - displayRelativePos1.y;
largeur = displayRelativePos2.x - displayRelativePos1.x;
GC gc = new GC(paintC);
gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
gc.fillRectangle(displayRelativePos1.x, displayRelativePos1.y, largeur, hauteur);
nbFormesAff = nbFormes +1;
forme = "Rectangle" + nbFormesAff;
pos = displayRelativePos1.x + ", " + displayRelativePos1.y +"\nhauteur:" + hauteur +" largeur:"+ largeur;
}
DropTargetEvent has x and y fields which contain the Display relative location of the cursor.
Point displayRelativeDrop = new Point(event.x, event.y);
Your fillRectangle must use points which are relative to the Control (paintC) not the display. Use Control.toControl(point) to convert from display relative to control relative.
You should also not try to draw the control in the drop method. Just call redraw on the control and do the drawing in a paint listener.
String [] texts= new String[26];
for(int a=0; a<26; a++){
String te=money[a].getText();
texts[a] = te;
box[a].setText(te);
}
In this code I want to set Text boxs and box is a JLabel. I created moneys which are also JLabel and has texts. I want that if I click on a box I wan to remove that box and money which has the same text with that box. For this I wrote this code:
for(clickLoop=0; clickLoop<26; clickLoop++){
box[clickLoop].addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
clickCount++;
if(clickCount == 0){
box[26].setVisible(false);
JLabel labelReference=(JLabel)e.getSource();
ortaPanel.remove(welcome);
ortaPanel.revalidate();
ortaPanel.repaint();
ortaPanel.add(labelReference).setBounds(390,480,im.getIconWidth(),im.getIconHeight());
System.out.println("a");
ortaPanel.add(six).setBounds(305, 465, s.getIconWidth(), s.getIconHeight());
labelReference.removeMouseListener(this);
}else if(clickCount == 6){
e.getComponent().setVisible(false);
JLabel labelReference=(JLabel)e.getSource();
ortaPanel.remove(six);
ortaPanel.revalidate();
ortaPanel.repaint();
//ortaPanel.add(labelReference).setBounds(390,480,im.getIconWidth(),im.getIconHeight());
ortaPanel.add(five).setBounds(305, 465, s.getIconWidth(), s.getIconHeight());
labelReference.removeMouseListener(this);
}else {
e.getComponent().setVisible(false);
String esles=((JLabel) e.getComponent()).getText();
for(int i=0; i<money.length; i++){
if(esles.equals(money[i].getText()) ){
sagPanel.remove(money[i]);
}
}
}
System.out.println(clickCount);
}
});
}
}
Some labels are working truely but most of them didnt work. I dont know why? There is one more question I want to ask: As you can see the code above I created text of box[i] same as text of money[i]. Instead of doing like that I want to make it randomly. I tried but did not achive. Do you know how can I do that? Thanx in advance.
I am having an issue with using a scrollpane in libgdx. It is going to be used for a chatwindow class. When you press enter the message will be added to the window and you will scroll to the latest posted message..However it doesn't. It misses one message and scrolls to the one before the latest message. Below I've posted the chatwindow class and the method that adds input to it. The textAreaholder is a table that holds everything. The chatField is where you input what you want to post to the chat. The chatarea is the textfield that then becomes added to the table. But as stated..it doesn't scroll properly, the error properly lies somewhere in the keyTyped method.
public ChatWindow(final Pipe<String> chatPipe) {
this.chatPipe = chatPipe;
messageFieldCounter = 0;
white = new BitmapFont(Gdx.files.internal("fonts/ChatWindowText.fnt"), false);
fontSize = white.getLineHeight();
white.scale(TEXT_SCALE);
final TextFilter filter = new TextFilter();
/* Making a textfield style */
textFieldStyle = new TextFieldStyle();
textFieldStyle.fontColor = Color.WHITE;
textFieldStyle.font = white;
textFieldStyle.focusedFontColor = Color.CYAN;
/*Area where all chat appears*/
textAreaHolder = new Table();
textAreaHolder.debug();
/*Applies the scrollpane to the chat area*/
scrollPane = new ScrollPane(textAreaHolder);
scrollPane.setForceScroll(false, true);
scrollPane.setFlickScroll(true);
scrollPane.setOverscroll(false, false);
/*Input chat*/
chatField = new TextField("", textFieldStyle);
chatField.setTextFieldFilter(filter);
/*Tries to make the textField react on enter?*/
chatField.setTextFieldListener(new TextFieldListener() {
#Override
public void keyTyped(final TextField textField, final char key) {
if (key == '\n' || key == '\r') {
if (messageFieldCounter <= 50) {
textAreaHolder.row();
StringBuilder message = new StringBuilder(); //Creates the message
message.append(chatField.getText()); //Appends the chatfield entry
TextArea chatArea = new TextArea(message.toString(), textFieldStyle); //Creates a chatArea with the message
chatArea.setHeight(fontSize + 1);
chatArea.setDisabled(true);
chatArea.setTextFieldFilter(filter);
textAreaHolder.add(chatArea).height(CHAT_INPUT_HEIGHT).width(CHAT_WIDTH);
scrollPane.scrollToCenter(0, 0, 0, 0);
//Scrolls to latest input
chatField.setText("");
//InputDecider.inputDecision(message.toString(), chatPipe); //TODO: Change the filter
//chatPipe.put(message.toString()); //TODO: testing
}
}
}
});
Problems could occur, because you're using scrollPane.scrollToCenter(float x, float y, float width, float height) with zero parameters:
scrollPane.scrollToCenter(0, 0, 0, 0);
scrollToCenter method requires that parameters to be correctly supplied. So, try to supply message bounds.
The second reason could be because you call scrollToCenter before table do layout itself. So, try overwrite table's layout method and call scrollToCenter after:
#Override
public void layout()
{
super.layout();
if (new_messages_added)
{
scrollPane.scrollToCenter(...)
}
}
Currently it looks so
What to do so that it looks so?
Below is my code:
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
JTextField component = new JTextField(" ");
component.setMaximumSize(component.getPreferredSize());
textPane.setSelectionStart(textPane.getDocument().getLength());
textPane.setSelectionEnd(textPane.getDocument().getLength());
textPane.insertComponent(component);
try {
textPane.getDocument().insertString(textPane.getDocument().getLength(), "text",
new SimpleAttributeSet());
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
f.add(new JScrollPane(textPane));
f.setSize(200, 100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
The single question which is near to this topic I found: JTextPane insert component, faulty vertical alignment
But there is no answer how to change the alignment. But it must be possible according to the discussion there.
You can use this http://java-sl.com/tip_center_vertically.html
It should work with JComponents as well.
You can also override LabelView's getPreferredSpan() adding some space to the bottom.
Alternatively you can try to override RowView inner class in ParagraphView
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/text/ParagraphView.java#ParagraphView.Row
That points to inner class Row extends BoxView
You should replace it with own one. Try to override
public float getAlignment(int axis)
to return CENTER (0.5). If this does not help override layoutMinorAxis(0 to return proper offsets (shifted).
Define a style for your document with a JLabel and set the vertical aligment on it:
Style s = doc.addStyle("icUf", regular);
ImageIcon icUf = createImageIcon("uf.png", "Unidad Funcional");
if (icUf != null) {
JLabel jl = new JLabel(icUf);
jl.setVerticalAlignment(JLabel.CENTER);
StyleConstants.setComponent(s, jl);
}
Insert the label:
doc.insertString(doc.getLength(), " ", doc.getStyle("icUf"));
and the text:
doc.insertString(doc.getLength(), " text ", doc.getStyle("bold"));
Based on the answer above (which didn't work for me, but helped me find this), I used:
Style s = doc.addStyle("icUf", regular);
ImageIcon icUf = createImageIcon("uf.png", "Unidad Funcional");
if (icUf != null) {
// create label with icon AND text
JLabel jl = new JLabel("some text",icUf, SwingConstants.LEFT);
StyleConstants.setComponent(s, jl);
}
doc.insertString(doc.getLength(), " ", doc.getStyle("icUf"))
This properly aligned the text 'some text' and the icon.