Java Swing: display Text selectable - java

I wont to display some text with Java Swing. It should also be possible to select it with the mouse in order to copy it. If I use a JLable it is not possible to select the text. If I use a JTextField or JTextArea it is possible to select and copy the text, but then the user can modify the text. Sure I can disable them so that it is not longer possible to change the text, but then again it is also not possible to select and copy the text ether.
Is there some way to achieve what I am searching for?

Use setEditable(false) on a JTextField. Oddly, then, the mouse pointer is an arrow, but you can still select the text.
This worked for me:
import javax.swing.*;
public class TestTextField extends JFrame {
private JTextField txt;
public TestTextField() {
txt = new JTextField("test");
this.add(txt);
txt.setEditable(false);
this.setSize(200, 100);
}
public static void main(String[] asArgs) {
new TestTextField().show();
}
}

Related

JTextArea shows up but for further action on it I receive empty

I have a class "MainFrame1" that extends a JFrame and also another class that is a file chooser. Whenever I press one of the JMenuItems in MainFrame1 class, I want the file chooser to open up and load up the text of the chosen file on a JTextArea that was created in MainFrame1 class. This works perfectly fine as I created a separate class implementing an ActionListener. Now my problem is that when I press another JMenuItem I want to do something else to the text in the JTextArea. I have implemented another ActionListener for that in a different class but the problem is that the JTextArea seems to be empty when I do that although I can see the text in there. Thanks in advance.
This is how I have created the JTextArea in the MainFrame1:
showAction = new JTextArea(10,10);
showAction.setEditable(false);
showAction.setFont(new Font("Arial", Font.BOLD, 12));
add(showAction, BorderLayout.NORTH);
And this is my second ActionListener class (also, whenever the text of a file is printed in the JTextArea, the text "loaded up." will also be printed) and I always get the else branch.
public class TransformController implements ActionListener{
MainFrame1 mf;
public TransformController(MainFrame1 mf) {
this.mf = mf;
}
#Override
public void actionPerformed(ActionEvent e) {
String text = mf.showAction.getDocument().toString();
if(text.contains("loaded up.")) {
char[] charText = text.toCharArray();
Parser parser1 = new Parser(charText);
parser1.packageVisitor();
}
else {
System.out.println("Load up a Java file first!");
}
}
}
This seems to be mostly a debugging question: First, find out what's in showAction.getDocument() to see if your menu item just isn't loading it right. Then check (with an IDE or via toString()) that mf.showAction really is the same object in the two cases.
Structurally, there's nothing in Java that prevents you from having a reference to the same JTextArea in two parts of the code, and reading the text out of it for different purposes.

How to return to the class from a jframe in netbeans

I'm new to netbeans. Below is my scenario :
I have created a normal java file in which I'm calling a jframe. jframe have a textbox and submit button.
What I want is that after calling the jframe from the java file, jframe opens up. Then after typing the text in the textbox, when we click on the submit button I should return back to that java file (to the line after I called the jframe) with the text typed. So, that I can use that text in my java file further.
But what is happening now is that when I call the jframe with the below command, jframe opens up and after that rest of the code in the java file gets executed. The java is not waiting for the jframe to return the data.
new Frame1(new javax.swing.JFrame(), false).setVisible(true);
And below is the code in jframe. But don't know how to return it and use it in java file
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String s1 = jTextField1.getText();
argA[0] = s1;
}
So, please let me know how can I do it ?
Thanks to all in Advance
Make two methods,
first one be a main method which create the frame.
second one do the things when Jframe done its work.
and the case
String s1 = jTextField1.getText();
argA[0] = s1;
just write
argA[0] = jTextField1.getText();
make argA as a instance variable then you can call it without to return things.
OR
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
to
private String jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
return YourStringHere;
}
By the way, by use netbeans, coding via GUI design mode is more easier to learn.

how to use text fields in java

I just have a very basic question about how to use textfields in Java. It's very simple, but the tutorials and other questions I've been looking for haven't been helpful, and I'm hoping that someone can explain things a little more clearly for me.
Right now I have the following code that I just sort of slapped together for the sake of example:
import javax.swing*;
public class testText {
public static void main(String[] args){
JFrame frame = new JFrame();
JTextField text = new JTextField();
frame.add(text);
frame.setVisible(true);
System.out.println(text.getText());
}
}
All I'm trying to do, is print what the user types into the text field in the console. But nothing happens when I type into the text field.
Now,based on the research I've done, I think the problem is that I'm not using an actionListener. The thing is, I really don't understand how those work, and I'm hoping someone can clarify for me.
I've been using this tutorial to try and figure things out, and particularly the TextDemo example they have near the top. I'm still kind of at a loss though, and I can't seem to find any way to use the actionlistener interface without breaking the program. If someone could either just explain simply and directly how to use the actionlistener to pull a string from a text field and then use it, or else point me to somewhere else where I can FIND a simple straightforward explanation, I would immensely appreciate it. I've been beating my head against this for five hours now with absolutely nothing to show for it, so I apologize for asking such a basic question but I'm at a loss.
An action listener will be called when an enter key is pressed while typing in the field. From the JTextfield Javadoc :
How the text field consumes VK_ENTER events depends on whether the
text field has any action listeners. If so, then VK_ENTER results in
the listeners getting an ActionEvent, and the VK_ENTER event is
consumed.
Here is your example modified to work with an action listener :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class testText {
public static void main(String[] args){
JFrame frame = new JFrame();
final JTextField text = new JTextField();
frame.add(text);
frame.setVisible(true);
text.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(text.getText());
}
});
}
}
And here is an object oriented complete example not relying only on a static main method.

Java - Allow using backspace in an editable JComboBox with Substance L&F

I am using Substance L&F and I have set a JComboBox to editable so that i can select the value that i want from its popup, or type a new value in its Editor.
Typing a new value works fine, but if i want to delete a miss-typed letter from the Combo editor, and i click Backspace to do that it selects the letters in the editor instead of erasing them. Here is a screenshot :
I want the Combo editor to work like a JTextField when typing keyboard letters or Backspace or Delete in it, so is there a way to do that ? Or what is causing this?
See below for the importance of an SSCCE not everything that goes wrong is a bug, most of the times it something wrong in your actual code, which without an SSCCE we are non the wiser.
Seems to work fine for me:
On start up:
After selecting JComboBox and pressing Backspace:
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JComboBox jc = new JComboBox(new String[]{"Hello", "Bye", "World", "Cruel"});
jc.setEditable(true);
frame.add(jc);
frame.pack();
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
new Test();
}
}
UPDATE
As per your comment:
I did not think it would work fine ! ... It is a problem in Substance;
the L&F i am using.
See below for details on the Bug:
Substance: Editable JComboBox does not support backspace key
As stated:
This behavior is by design. This is a "feel" part of Substance that
adds auto-completion on editable comboboxes.
Alternatively see my answer here for more L&Fs and/or a way to make your own
UPDATE 2:
Thanks to #Brad (for deciphering the bug log I linked from Substance :P) to fix this simply do:
UIManager.put( LafWidget.COMBO_BOX_NO_AUTOCOMPLETION, Boolean.TRUE );
UIManager.put(LafWidget.COMBO_BOX_NO_AUTOCOMPLETION, Boolean.TRUE);
This work for me!

Updating text in a JTextField

K, so unlike with my last question, I've been proactive about trying to deal with this problem a number of times, and it's still not working.
Basically I'm trying implement a JTextField. I've added the action listener to it and the getters and setters for the text are working, but text that I'm enter isn't showing up in the textfield. I tried setting the text color to black and that didn't help. Honestly, I'm not sure what the issue is.
K here's the code.
import acm.program.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSurfer extends Program implements NameSurferConstants {
//Change back to program after this
/* Method: init() */
/**
* This method has the responsibility for reading in the data base
* and initializing the interactors at the bottom of the window.
*/
public void init() {
// You fill this in, along with any helper methods //
createUI();
addActionListeners();
}
/* Method: actionPerformed(e) */
/**
* This class is responsible for detecting when the buttons are
* clicked, so you will have to define a method to respond to
* button actions.
*/
public void actionPerformed(ActionEvent e) {
// You fill this in //
if(e.getSource() == nameField || e.getSource() == graphName) {
drawNameGraph(nameField.getText());
} else if(e.getSource() == clearGraph) {
clearNameGraph();
}
}
/* Method: createUI() */
/**
* This method sets up and adds the interactors at the bottom of the window*/
private void createUI() {
nameField = new JTextField(25);
nameField.setColumns(25);
nameField.addActionListener(this);
graphName = new JButton("Graph");
clearGraph = new JButton("Clear");
graph=new NameSurferGraph();
add(new JLabel("Name"), SOUTH);
add(nameField, SOUTH);
add(graphName, SOUTH);
add(clearGraph, SOUTH);
add(graph);
//println(db.fileEntries.size());
}
/* Method: drawNameGraph(str) */
/** Draws the graph of the name entered in nameField
* */
private void drawNameGraph(String str) {
//println(str);
NameSurferEntry entered = db.findEntry(str);
if(entered != null) {
//println("Graph: " + entered.toString());
graph.addEntry(entered);
nameField.setText("str");
} else {
graph.badEntry(str);
}
//nameField.setText("");
}
/* Method: clearNameGraph() */
private void clearNameGraph() {
graph.clear();
}
private NameSurferDataBase db = new NameSurferDataBase(NAMES_DATA_FILE);
/**TextField where the names get entered*/
private JTextField nameField;
/**button to graph name popularity*/
private JButton graphName;
/**Clears graph*/
private JButton clearGraph;
private NameSurferGraph graph;
}
Also I'm going to try to explain my question better using images. Sorry if this don't work on your OS. Their .tiffs but I'll try to run them through image conversion later on. For some reason, stackoverflow isn't letting me post the images in question, so I'm going to try to do some links to them instead through some other site. Sorry for the inconvenience.
When I run the code, this is displayed.
See the image for that here.
Basically so far it works as expected.
The problem arises
here.
The getters and setters are working, but I'ld like to have the JTextField updated when the user enters the text, as opposed to not displaying anything that I've got entered in it.
Are you trying to do this?!?
JTextField text = new JTextField();
text.setText("ttttttttttttexxxt");
Quoting from the the Java 6 API on JTextField:
public JTextField()
Constructs a new TextField. A default model is created, the initial string is null, and the number of columns is set to 0.
(Emphasis added.)
If you are using a default constructor, then if you have not called setColumns(int), your JTextField has a column limit of 0 (regardless of the text field's width) and therefore will refuse all input from the user. I am inferring you are having trouble entering text as a user when the program is running, rather than trouble setting the text within the program and causing it to display?
Either use a form of the constructor that has a column limit, or use setColumns to specify a nonzero maximum after construction.
If this doesn't solve the issue, please provide a code sample, especially where you are constructing and initializing your JTextField.
The text is always defaulted to black so there no need to play with anything except setText.
There are a number of things you could be asking here so.
To set the text on load simply use setText at the top of your code.
public TestFrame() {
initComponents();
jTextField1.setText("Hello I am text in a box");
}
You can also have it respond to an event in the following way. Example is a button click.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Text Box changes from default
jTextField1.setText("The button was pushed!!");
}
Notice that it is all the same, I feel like you are making it a little more complicated than it actually is.
Use a normal TextField instead of a JTextfield. According to this post that was the issue. I'm not a specialist, but I have encountered the exact same problem, and it seems to be linked to the usage of the ACM library.

Categories