This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to add hyperlink in JLabel
In my program, I am searching through an index using Lucene and I am retrieving files. I have created XML files for the retrieved docs from the Lucene's search. Now, I want to make these XML files as hyperlinks and display to the user as the search results. That is I want the XML files to be open when the user clicks on this hyperlink. Any help appreciated!?
for(int i=0;i<file_count;i++)
{
file=str+index[i]+".xml";
JLabel label = new JLabel(file,JLabel.CENTER );
label.setOpaque(true);
label.setBackground(Color.RED);
panel.add(label) ;
label.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() > 0)
{
Runtime r= Runtime.getRuntime();
try {
System.out.println("testing : Inside mouseclicked");
Process p = r.exec("cmd.exe /c start "+file);
System.out.println("opened the file");
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.out.println();
}
}
}
});
}
Here is the code that I have made. In this, I am suppose to get output on the screen "file_count" no of times. I am getting that but what is happening is all the links are showing the same file when clicked. Help?
If I do understand your question correctly, you want to allow the user to open a file. The Desktop class (available as of JDK1.6) allows this
File fileToOpen = ...;
Desktop desktop = Desktop.getDesktop();
desktop.open( fileToOpen )
Depending on how you want to present this to the user, you can opt for your JLabel code with the listener but it is probably easier to use a JButton with an ActionListener. Both approaches are discussed in detail in the answer Marko Topolnik already suggested in his comment. The only difference is that they wanted to open an URL, while you want to open a file (so that answer uses the browse method instead of the open method of the Desktop class).
Related
I have a tree list which will open a specific html file when I click at a node. I try loading my html into a Jeditorpanel but it can't seem to work.
Here's my code from main file:
private void treeItemMouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) treeItem.getSelectionPath().getLastPathComponent();
String checkLeaf = selectedNode.getUserObject().toString();
if (checkLeaf == "Java Turtorial 1") {
String htmlURL = "/htmlFILE/javaTurtorial1.html";
new displayHTML(htmlURL).setVisible(true);
}
}
Where I wanna display it:
public displayHTML(String htmlURL) {
initComponents();
try {
//Display html file
editorHTML.setPage(htmlURL);
} catch (IOException ex) {
Logger.getLogger(displayHTML.class.getName()).log(Level.SEVERE, null, ex);
}
}
My files:
One simple way to render HTML with JEditorPane is using it's setText method:
JEditorPane editorPane =...
editorPane.setContentType( "text/html" );
editorPane.setText( "<html><body><h1>I'm an html to render</h1></body></html>" );
Note that only certain HTML pages (relatively simple ones) can be rendered with this JEditoPane, if you need something more complicated you'll have to use thirdparty components
Based on OP's comment, I'm adding an update to the answer:
Update
Since the HTMLs that you're trying to load are files inside the JAR, you should read the file into some string variable and use the aforementioned method setText
Note that you shouldn't use java.io.File because it used to identify resources at the filesystem, and you're trying to access something inside the artifact:
Reading the resource like this can be done with the following construction:
InputStream is = getClass().getResourceAsStream("/htmls/myhtml.html");
// and then read with the help of variety of ways, depending on Java Version of your choice and by the availaility by auxiliary thirdparties
// here is the most simple way IMO for Java 9+
String htmlString = new String(input.readAllBytes(), StandardCharsets.UTF_8);
Read Here about many different ways to read InputStream into String
I am trying to write java code to access and use the DullRazor software.
Please refer to this image of the DullRazor application:
I had an idea of creating a Java runtime program that could loop through all images I need to process(the software only allows 1 image at a time) and complete the necessary steps required for the DullRazor software to successfully alter an image for every image I have.
The DullRazor software works as follows:
-Source File: Requires the path to an image(jpg in my case) to be altered i.e c://Isic-Images//image0000.jpg.
-Target File: Requires the location for the new image with a new image name i.e c://finalLocation//newImage.jpg
-Start: Run the program after giving the inputs in the correct format as described above.
My thinking is iterating through all my images, creating new ones and incrementing the name(img00, img001 etc..).
I have never attempted anything like this in Java and I have had some trouble accessing the Input fields of the software as well as the application's start button.
The code below is just very basic for opening the application, but I am unsure how to access the various items in the DullRazor application and being able to input Strings in those aforementioned fields(again, refer to the DullRazor picture).
private String trainingPath = "C:\\Users\\user\\AppData\\Local\\Temp\\ISIC-Images\\Training\\0";
private String finalPath = "C:\\Users\\user\\finalLocation\\";
public static void main(String[] args) {
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("C:\\Users\\user\\Desktop\\dullrazor.exe");
System.out.println("Opening DullRazor");
OutputStream output = process.getOutputStream();
InputStream input = process.getInputStream();
Thread.sleep(2000);
process.destroy();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException s) {
s.printStackTrace();
} finally {
System.out.println("Closing Dullrazor");
}
}
I have just been testing a bit with the code above, but I am unsure on how to proceed.
Tell me if there is anything that needs clarifying.
Any help is greatly appreciated, thanks.
You can use Java's java.awt.Robot class to control mouse and keyboard on the screen.
This is a simple example entering "test1" and "test2" into two input fields:
Robot r = new Robot();
r.mouseMove(22, 125);
r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
r.keyPress('T');
r.keyRelease('T');
r.keyPress('E');
r.keyRelease('E');
r.keyPress('S');
r.keyRelease('S');
r.keyPress('T');
r.keyRelease('T');
r.keyPress('1');
r.keyRelease('1');
r.mouseMove(200, 125);
r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
r.keyPress('T');
r.keyRelease('T');
r.keyPress('E');
r.keyRelease('E');
r.keyPress('S');
r.keyRelease('S');
r.keyPress('T');
r.keyRelease('T');
r.keyPress('2');
r.keyRelease('2');
The above code in action:
If the position of the new application window does not change with each start, and the tool is not about to be deployed to users, this might already suffice. However, if it changes the position with each start, the challenge is to find the window position to add the relative input element positions from there. There are Windows (platform) specific approaches facilitating the Win32 API through JNA, though I'm not familiar with it and whether it is still available in current Microsoft Windows versions.
See these related questions on determining other windows positions:
Windows: how to get a list of all visible windows?
How to get the x and y of a program window in Java?
Using robot works perfectly in order to input into the targeted fields and clicking start/clear button on the application.
In order to find the x & y positions of the application I used runtime exec to open dullrazor and then take a screenshot of the screen with the application up where mouse clicks reveals the x and y position of the current click. Below is the code for finding x & y which I found at this Stackoverflow thread:
Robot robot = new Robot();
final Dimension screenSize = Toolkit.getDefaultToolkit().
getScreenSize();
final BufferedImage screen = robot.createScreenCapture(
new Rectangle(screenSize));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel screenLabel = new JLabel(new ImageIcon(screen));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension(
(int)(screenSize.getWidth()/2),
(int)(screenSize.getHeight()/2)));
final Point pointOfInterest = new Point();
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel pointLabel = new JLabel(
"Click on any point in the screen shot!");
panel.add(pointLabel, BorderLayout.SOUTH);
screenLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
pointOfInterest.setLocation(me.getPoint());
pointLabel.setText(
"Point: " +
pointOfInterest.getX() +
"x" +
pointOfInterest.getY());
}
});
JOptionPane.showMessageDialog(null, panel);
System.out.println("Point of interest: " + pointOfInterest);
}
});
Thank you try-catch-finally for a great answer.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to make a text editor in Java, but I can't seem to get the "open file" feature to work. When I run the code, it only displays the first line of a file. I've tried all of the code snippets from: How to read a large text file line by line using Java?, but it still reads the first line only.
This is what I have tried:
JMenuItem mntmOpen = new JMenuItem("Open");
mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
mntmOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mntmOpen) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
Path HI = file.toPath();
try( Stream<String> lines = Files.lines(HI)
){
for( String line : (Iterable<String>) lines::iterator )
{
editorPane.setText(line);
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
Check out this answer here, you should be able to use the section in the while loop. Pretty straight forward run until null which basically states that the buffer will continue to read until the reader sends back a null pointer in which case there is nothing left in the file. If this doesn't work then we can take a look at it again. Also you got downvoted for asking a question without searching for an answer first. https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html
This question already has answers here:
JTextField in which the predefined text in not editable but other text can be appended to it?
(5 answers)
Closed 7 years ago.
I am trying to create a TextArea using java that contains text that cannot be deleted/updated. That being said, the user can still add to the TextArea and delete their own text.
I've tried to play around with getting the length of the TextArea and listening for the 'backspace' keypress however I can still select all the text in the TextArea and replace it.
Example Code
(TA is the TextArea)
TA.setText(cmdx);
cmdLength = TA.getDocument().getLength();
TA.getKeymap().addActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), new AbstractAction() {
public void actionPerformed(ActionEvent e) {
TA.disable();
try {
backSpace();
} catch (BadLocationException ex) {
Logger.getLogger(CmdFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
AND
public void backSpace() throws BadLocationException {
System.out.println("Backspace is pressed");
int currentLength = TA.getDocument().getLength();
if(currentLength > cmdLength)
{
Document doc = TA.getDocument();
doc.remove(doc.getLength() - 1, 1);
TA.enable();
}
}
I apologize if this question has already been asked.
Thank you in Advance!
Don't let the user directly type in text but catch the respective event and manually set the text to the textField. Then you can implement a check (for example if the text is starting with your sticky text) and if not add it at the beginning again. If it does then simply add the typed key at the end of the text.
Look here for more solutions
I am new to java.
I have a project from college where I have to make entries to txt file through 2 JTextField boxes and 1 JButton (save) which will display the entries in JTextArea. I am able to make entries in txt file successfully. But how to refresh JTextArea at run-time to display the new entries I recently made?
Thanks for helps:
below is my code:
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader("RokFile.txt"));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
jTextArea1.append(line+"\n");
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
Let me know if its correct?
Thanks
JTextArea.append ought to suffice. This method is thread-safe and will update the text area's content automatically.
This answer assumes that you already have the EventListeners configured.
You can use two methods,
If you want to display the content as soon as you write in jTextField(fairly attainable), you can do it this way, in the FocusLost event of jTextField, give something like jTextArea.setText(jTextField.getText())
Note, that this is fairly near to what you want.(also,NOT perfect code)
If you want to display the contents when you click save , the above code, jTextArea.setText(jTextField.getText()) may be given in the event handler of the save button.