Download Files From a Website with java - java

I am very new to Java and I'm currently trying to create a Java application to download files from a website. To enter the website you need a password and username. I use NativeSwing to enter and get the path of the files, but I do not know how to download them.
public class Test {
public JFrame frame;
private static JWebBrowser browser;
private static JPanel configurationButtonPanel;
public Test() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createContent(), BorderLayout.CENTER);
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComponent createContent() {
JPanel contentPane = new JPanel(new BorderLayout());
JPanel configurationPanel = new JPanel(new BorderLayout());
configurationButtonPanel = new JPanel(new FlowLayout(
FlowLayout.CENTER, 0, 0));
JButton beginButton = new JButton("Download");
beginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ArrayList<String> ligas = new ArrayList<String>();
int a=0;
Document doc = Jsoup.parse(browser.getHTMLContent());
Element ele = doc.getElementById("ctl00_MainContent_PnlResultados");
System.setProperty("java.net.useSystemProxies", "true");
try{
Elements img_2 = ele.getElementsByClass("BtnDescarga");
for (Element el : img_2) {
for( Attribute attribute : el.attributes() )
{
if( attribute.getKey().equalsIgnoreCase("onclick") )
{
ligas.add("https://portalcfdi.facturaelectronica.sat.gob.mx/"+attribute.getValue().substring(19,535));
}
}
}
}
catch(NullPointerException nulo){
}
for( int i = 0 ; i < ligas.size() ; i++ ){
System.out.println( ligas.get( i ) );
}
}
});
browser = new JWebBrowser();
browser.navigate("https://portalcfdi.facturaelectronica.sat.gob.mx/");
configurationButtonPanel.add(beginButton);
configurationButtonPanel.setVisible(true);
configurationPanel.add(configurationButtonPanel, BorderLayout.NORTH);
contentPane.add(configurationPanel, BorderLayout.SOUTH);
contentPane.add(browser, BorderLayout.CENTER);
return contentPane;
}
/**
* #param args
*/
public static void main(String[] args) {
NativeInterface.open();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
NativeInterface.runEventPump();
}
}
When it run this part:
for( int i = 0 ; i < ligas.size() ; i++ ) {
System.out.println( ligas.get( i ) );
}
I get the following URL:
https://portalcfdi.facturaelectronica.sat.gob.mx/RecuperaCfdi.aspx?Datos=huswUYX1eXMlGkDiItMUBgaWREHHqhXOWtYxqyUh0oUZnCKLYE/gx6ENJ+0TwW5auWw8d/AiCJyuFSDNVY+5l0vkiELroo/fEmF+x5w+DQDDTfMX9qIINS1NgP9C1bFhirjcVXpZI1ed4ycpLPczkYMEGEKvqWemni8LWcbqC0BuZskOJnCQCaWRh1Kt7AL5GdBVKqkm3T5mvzhtkmE5dn0vcWbCFFO3d3G8hu7rlcc0XM+7+6iR52SZYYaHa/TOhcl2DjuzztADpa9tPxZ9VO6EzMVkYKTfDOqHwZO8m2U9BZ7UhFjqsyoAwsQneqhIqGwN21yEpGEcptsTb9uZ1t0Fc/1Ggd6SuK9NeGdBpiawn6cv6QM1uc4QQHMNpAgG89Rq5tOd4YAoRQHBe/vO8ppq60JwvJgQ4BN76EtZF0UtEWK+k57P01vatuvTHIdMBncbXyU+TrtE5AlhdGKkY2a8HwSxHw3nfoQ+SLBrjyg=

I use the following code to read images from url, i think you can use the same techniques here
try{
URL url = new URL("YOUR_URL_TO_READ");
InputStream is = url.openStream();
OutputStream os = new FileOutputStream("YOUR_FILE_TO_SAVE");
byte[] b = new byte[4096];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}catch(Exception exp){
exp.printStackTrace();
}

The best answer right now is the Apache Http Client. Java has HttpURLConnection built-in, but it is difficult to use, and has some other usage issues that can burn you (e.g. keep-alive and errors). If you absolutely cannot include a third party, use HttpURLConnection, otherwise go with the Apache Library.
There is a new Java standard Http library coming in JDK 9 here, but that's not here yet.

You might have to try code on similar lines..it might work... Two issues maybe there...first is you need to find the proxy name and port set on your machine...if there is a proxy.. Next, possible the site needs authentication,so you would need to set the right username and password.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("Your Proxy", ProxyPort));
String username = "YourUserName";
String password = "Password";
String userPassword = username + ":" + password;
byte[] encodedAuthorization = BASE64EncoderStream.encode(userPassword.getBytes());
HttpURLConnection connection =(HttpURLConnection)new URL("Your URL set here").openConnection(proxy);
connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization.toString());
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/zip");
//connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream("d:\\PathToFile" + "Chec.zip");

Related

Action Listener doesn't change set variable to other value

I am writing GUI for a chat, and I have problem I can't seem to find a solution.
When button Send is clicked variable OKpressed should change to true and in function getUserInput it should recognize it changed but it doesn't..
It's acting like it still says false..
I tried printing out in Send that works, so problem is only that functiong getUserInput doesn't recognize variable as changed
Any help is appreciated..Here's the code
I can't attach all other classes so you can start it, but everything is working except the problem mentioned above
public class Chat extends Process {
public static class myFrame extends JFrame{
/** Creates a new instance of myFrame */
private JTextArea ChatBox=new JTextArea(10,45);
private JScrollPane myChatHistory=new JScrollPane(ChatBox,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JTextArea UserText = new JTextArea(5,40);
private JScrollPane myUserHistory=new JScrollPane(UserText,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
private JButton Send = new JButton("Send");
private JTextField User=new JTextField(20);
private String ServerName;
private String UserName;
boolean OKPressed = false;
String poruka;
public myFrame() {
setResizable(false);
setTitle("Client");
setSize(560,400);
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Chat History"));
cp.add(myChatHistory);
cp.add(new JLabel("Chat Box : "));
cp.add(myUserHistory);
cp.add(Send);
cp.add(User);
Send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
poruka=(String)UserText.getText();
OKPressed = true;
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
static myFrame t=new myFrame();
public Chat(Linker initComm) {
super(initComm);
}
public synchronized void handleMsg(Msg m, int src, String tag){
if (tag.equals("chat")) {
System.out.println("Message from " + src +":");
System.out.println(m.getMessage());
t.ChatBox.append(src + ":" + m.getMessage() + "\n");
}
}
public String getUserInput() throws Exception {
while (t.OKPressed == false){}
String chatMsg=t.poruka;
return chatMsg;
}
public IntLinkedList getDest(BufferedReader din) throws Exception {
System.out.println("Type in destination pids with -1 at end:");
System.out.println("Only one pid for synch order:");
IntLinkedList destIds = new IntLinkedList(); //dest for msg
StringTokenizer st = new StringTokenizer(din.readLine());
// StringTokenizer st = new StringTokenizer(t.poruka);
while (st.hasMoreTokens()) {
int pid = Integer.parseInt(st.nextToken());
if (pid == -1) break;
else destIds.add(pid);
}
return destIds;
}
public static void main(String[] args) throws Exception {
String baseName = "Chat";
int myId = Integer.parseInt(args[0]);
int numProc = Integer.parseInt(args[1]);
Linker comm = null;
comm = new CausalLinker(baseName, myId, numProc);
Chat c = new Chat(comm);
for (int i = 0; i < numProc; i++)
if (i != myId) (new ListenerThread(i, c)).start();
BufferedReader din = new BufferedReader(
new InputStreamReader(System.in));
while (true){
System.out.println(c.getUserInput());
String chatMsg = c.getUserInput();
if (chatMsg.equals("quit")) break;
t.ChatBox.append(myId + ": " + chatMsg +"\n");
IntLinkedList destIds = c.getDest(din);
comm.multicast(destIds, "chat", chatMsg);
}
}
}
As you wrote, I cannot run you code, so it is kind of guess, however I think the problem is in empty infinite loop:
while (t.OKPressed == false){}
if you add anything inside, even:
while(t.OKPressed == false){
System.out.println();
}
It should work. It is connected with problem better described for example here: Threads: Busy Waiting - Empty While-Loop, and in post which duplicate it is.

Authenticator getPasswordAuthentication not called [closed]

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 8 years ago.
Improve this question
I am new to Network Programming.
Here is my Code:
public class ComputerNetworks extends Authenticator {
private JDialog passwordDialog;
private JLabel mainLabel= new JLabel("Please enter username and password: ");
private JLabel userLabel = new JLabel("Username: ");
private JLabel passwordLabel = new JLabel("Password: ");
private JTextField usernameField = new JTextField(20);
private JPasswordField passwordField = new JPasswordField(20);
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public ComputerNetworks( ) {
this("", new JFrame());
}
public ComputerNetworks(String username) {
this(username, new JFrame());
}
public ComputerNetworks(JFrame parent) {
this("", parent);
}
public ComputerNetworks(String username, JFrame parent) {
this.passwordDialog = new JDialog(parent, true);
Container pane = passwordDialog.getContentPane( );
pane.setLayout(new GridLayout(4, 1));
pane.add(mainLabel);
JPanel p2 = new JPanel( );
p2.add(userLabel);
p2.add(usernameField);
usernameField.setText(username);
pane.add(p2);
JPanel p3 = new JPanel( );
p3.add(passwordLabel);
p3.add(passwordField);
pane.add(p3);
JPanel p4 = new JPanel( );
p4.add(okButton);
p4.add(cancelButton);
pane.add(p4);
ActionListener al = new OKResponse( );
okButton.addActionListener(al);
usernameField.addActionListener(al);
passwordField.addActionListener(al);
cancelButton.addActionListener(new CancelResponse( ));
passwordDialog.pack( );
passwordDialog.setVisible(true);
}
private void show( ) {
String prompt = this.getRequestingPrompt( );
if (prompt == null) {
String site = this.getRequestingSite().getHostName( );
String protocol = this.getRequestingProtocol( );
int port = this.getRequestingPort();
if (site != null & protocol != null) {
prompt = protocol + "://" + site;
if (port > 0)
prompt += ":" + port;
} else {
prompt = "";
}
}
mainLabel.setText("Please enter username and password for "
+ prompt + ": ");
passwordDialog.pack();
passwordDialog.setVisible(true);
}
PasswordAuthentication response = null;
class OKResponse implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("OK clicked");
passwordDialog.setVisible(false);
// The password is returned as an array of
// chars for security reasons.
char[] password = passwordField.getPassword( );
String username = usernameField.getText( );
// Erase the password in case this is used again.
passwordField.setText("");
response = new PasswordAuthentication(username, password);
}
}
class CancelResponse implements ActionListener {
public void actionPerformed(ActionEvent e) {
passwordDialog.hide( );
// Erase the password in case this is used again.
passwordField.setText("");
response = null;
}
}
public PasswordAuthentication getPasswordAuthentication( ) {
this.show();
return this.response;
}
public static void main(String[] args) throws Exception {
Authenticator.setDefault(new ComputerNetworks());
URL u = new URL("http://www.google.co.in");
InputStream in = u.openStream();
}
}
I am running this code from IDE. The problem is getPasswordAuthentication() method of Authenticator is not getting called though I have opened a stream with a URL.
Please help.
Thanks in advance
From the JavaDoc:
getPasswordAuthentication()
protected PasswordAuthentication getPasswordAuthentication()
Called when password authorization is needed. Subclasses should override the default implementation, which returns null.
Returns:
The PasswordAuthentication collected from the user, or null if none is provided.
google.co.in, to the best of my knowledge, does not require password authorization. Therefore, the Authenticator is not used. Try entering a URL that does require authentication, and see if that helps.

Java JFrame update in loop

Before coming here, I have searched all over the web and read dozens of topic talking about this but I can't fix my problem.
I want to show the progress of an upload. In the following code, everything works, except that my JFrame does not update. I am using a technique I found on another topic, but it doesn't seem to work. I think it will be more simple if you take a look at my code (I erased the instructions that aren't related to the problem).
/*
* Correct imports have been done
*/
class GUI extends JFrame {
public JPanel pan;
public GUI(JPanel panel) {
super("Uploading...");
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(600, 500));
setMinimumSize(new Dimension(600, 500));
setMaximumSize(new Dimension(600, 500));
setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);
setLocationRelativeTo(null);
pan = panel;
pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS));
setContentPane(pan);
setVisible(true);
}
}
public class GUIUpload {
private static GUI ui;
public static void main(String args[]) {
JPanel main = new JPanel();
ui = new GUI(main); // create and display GUI
uploadLoop(args, main); // start the upload loop
/*
* After upload is finished
*/
JButton jb = new JButton("Ok");
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ui.setVisible(false);
}
});
ui.getContentPane().add(jb);
ui.getContentPane().repaint();
}
private static void uploadLoop(String[] paths, JPanel monitor) {
/*
* Upload starts here
*/
long transfered;
long size;
InputStream inputStream;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("xxxxxx", 21);
boolean success = ftpClient.login("xxxxxx", "xxxxxx");
/*
* Sending
*/
for (int i = 0; i < 4; i++){
if (paths[i] != null){
File localFile = new File(paths[i]);
String remoteFile = "/public_html/papers/" + i + ".pdf";
JLabel label = new JLabel("Uploading...");
ui.getContentPane().add(label);
ui.repaint();
inputStream = new FileInputStream(localFile);
// Monitoring misc
size = localFile.length();
transfered = 0;
int percentage = 0;
// Progress bar
JProgressBar pgb = new JProgressBar();
pgb.setValue(0);
ui.getContentPane().add(pgb);
ui.repaint();
// Upload routine
OutputStream outputStream = ftpClient.storeFileStream(remoteFile);;
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
transfered += read;
percentage = (int)(transfered * 100.0 / size + 0.5);
System.out.println(percentage);
pgb.setValue(percentage);
ui.repaint();
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
/*
* End of upload
*/
}
}
} // end try
catch (Exception e){
// Do nothing}
} // end catch
} // end upload method
}
The percentage works fine. The file transfer works fine. The GUI frame only updates after when I repaint it in the main method of the GUIUpload class. When it repaints, I can see that all the labels and progressbars have been correctly added and updated (the progress bars are showing the maximum value.
So.. it's been quite a while that I'm searching how to do this, and I've tried using threads, I've tried a lot of things, but none worked (or I did something wrong when trying them).
Thanks a lot to anyone who will be able to help me out.
Best regards.
Swing is single-threaded. When you perform resource heavy tasks such as file download, you prevent Swing from repainting.
It's unsurprising that raw Threads didn't work as Swing has it's own concurrency features that provide a means of dealing with time-consuming background tasks. Threads were not designed to interact with swing components.
Use a SwingWorker.

cant create a JTextField

import org.jsoup.Jsoup;
#SuppressWarnings({ "unused", "serial" })
public class SimpleWebCrawler extends JFrame {
JTextField yourInputField = new JTextField(20);
static JTextArea _resultArea = new JTextArea(200, 200);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
private final static String newline = "\n";
String word2;
public SimpleWebCrawler() throws MalformedURLException {
yourInputField.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
word2 = yourInputField.getText();
}
});
_resultArea.setEditable(false);
try {
URL my_url = new URL("http://" + word2 + "/");
BufferedReader br = new BufferedReader(new InputStreamReader(
my_url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
_resultArea.append(strTemp + newline);
}
} catch (Exception ex) {
ex.printStackTrace();
}
_resultArea.append("\n");
_resultArea.append("\n");
_resultArea.append("\n");
String url = "http://" + word2 + "/";
print("Fetching %s...", url);
try{
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
System.out.println("\n");
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\user\\fypworkspace\\FYP\\Link\\abc.txt"));
_resultArea.append("\n");
for (Element link : links) {
print(" %s ", link.attr("abs:href"), trim(link.text(), 35));
bw.write(link.attr("abs:href"));
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
} catch (IOException e1) {
}
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
content.add(yourInputField,BorderLayout.SOUTH);
this.setContentPane(content);
this.setTitle("Crawled Links");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
JPanel content2 = new JPanel();
this.setContentPane(content2);
this.setTitle("Input the URL");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
private static void print(String msg, Object... args) {
_resultArea.append(String.format(msg, args) +newline);
}
private static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width - 1) + ".";
else
return s;
}
//.. Get the content pane, set layout, add to center
public static void main(String[] args) throws IOException {
JFrame win = new SimpleWebCrawler();
win.setVisible(true);
}
}
I am trying to create a JTextField to accept the user input. The input will go to this line of code to process the code.
URL my_url = new URL("http://" + word2 + "/");
String url = "http://" + word2 + "/";
However, the code is run without asking the user for input. The JTextField does not appear and i straight get an error on because i din enter the input.
I am trying to get the JTextField to accept input from the user. However, it does not appear and the code straight proceed with the processing end up with empty my_url and rmpty url variable.
How do i create a JTextField according to my code that i post ? It seems that the Jtextfield i created clashed with my codes.
Java swing does not follow the imperative approach but is event driven. Your constructor method is executed in total and does not wait for your input.
You must not include the business logic (i.e. all this read/write stuff) into this method but into a separate one and invoke it from the action listener your registered with your input field. (see e.g. http://download.oracle.com/javase/tutorial/uiswing/events/index.html)
Note A: If your logic is quite heavy you should spawn a background thread and not do it directly in your action listener (see Swingworker).
Note B: There is lot's of strange code within your class.
this.setContentPane(content);
this.setTitle("Crawled Links");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
JPanel content2 = new JPanel();
this.setContentPane(content2);
this.setTitle("Input the URL");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
As mentioned before this will be run immediately and thus your panel content is never shown at all because it will be overwritten by content2.

Redirecting System.out to JTextPane

I have a class (shown below) that extends JPanel and contains a JTextPane. I want to redirect System.out and System.err to my JTextPane. My class does not seem to work. When I run it, it does redirect the system prints, but they do not print to my JTextPane. Please help!
Note: The calls are only redirected when the application launches. But any time after launch, the System.out calls are not redirected to the JTextPane. (ie, if I place a System.out.prinln(); in the class, it will be called, but if it is placed in a actionListener for later use, it does not redirect).
public class OSXConsole extends JPanel {
public static final long serialVersionUID = 21362469L;
private JTextPane textPane;
private PipedOutputStream pipeOut;
private PipedInputStream pipeIn;
public OSXConsole() {
super(new BorderLayout());
textPane = new JTextPane();
this.add(textPane, BorderLayout.CENTER);
redirectSystemStreams();
textPane.setBackground(Color.GRAY);
textPane.setBorder(new EmptyBorder(5, 5, 5, 5));
}
private void updateTextPane(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Document doc = textPane.getDocument();
try {
doc.insertString(doc.getLength(), text, null);
} catch (BadLocationException e) {
throw new RuntimeException(e);
}
textPane.setCaretPosition(doc.getLength() - 1);
}
});
}
private void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(final int b) throws IOException {
updateTextPane(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextPane(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
}
Piped streams always confuse me, which is why my Message Console solution doesn't use them. Anyway here is my attempt at a console using piped streams. A couple of differences:
a) it uses a JTextArea because a JTextArea is more efficient than a JTextPane for just displaying text. Of course if you intend to add attributes to the text then you need a text pane.
b) this solution uses Threads. I'm sure I read somewhere that this was necessary to prevent blocking of the output. Anyway it works in my simple test case.
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class Console implements Runnable
{
JTextArea displayPane;
BufferedReader reader;
private Console(JTextArea displayPane, PipedOutputStream pos)
{
this.displayPane = displayPane;
try
{
PipedInputStream pis = new PipedInputStream( pos );
reader = new BufferedReader( new InputStreamReader(pis) );
}
catch(IOException e) {}
}
public void run()
{
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
// displayPane.replaceSelection( line + "\n" );
displayPane.append( line + "\n" );
displayPane.setCaretPosition( displayPane.getDocument().getLength() );
}
System.err.println("im here");
}
catch (IOException ioe)
{
JOptionPane.showMessageDialog(null,
"Error redirecting output : "+ioe.getMessage());
}
}
public static void redirectOutput(JTextArea displayPane)
{
Console.redirectOut(displayPane);
Console.redirectErr(displayPane);
}
public static void redirectOut(JTextArea displayPane)
{
PipedOutputStream pos = new PipedOutputStream();
System.setOut( new PrintStream(pos, true) );
Console console = new Console(displayPane, pos);
new Thread(console).start();
}
public static void redirectErr(JTextArea displayPane)
{
PipedOutputStream pos = new PipedOutputStream();
System.setErr( new PrintStream(pos, true) );
Console console = new Console(displayPane, pos);
new Thread(console).start();
}
public static void main(String[] args)
{
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane( textArea );
JFrame frame = new JFrame("Redirect Output");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( scrollPane );
frame.setSize(200, 100);
frame.setVisible(true);
Console.redirectOutput( textArea );
final int i = 0;
Timer timer = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println( new java.util.Date().toString() );
System.err.println( System.currentTimeMillis() );
}
});
timer.start();
}
}
Message Console class does this for you.
Edit:
Here is a simple test class:
import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class MessageConsoleTest
{
public static int counter;
public static void main(String[] args)
throws Exception
{
JTextComponent textComponent = new JTextPane();
JScrollPane scrollPane = new JScrollPane( textComponent );
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Message Console");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( scrollPane );
frame.setSize(400, 120);
frame.setVisible(true);
MessageConsole console = new MessageConsole(textComponent);
console.redirectOut();
console.redirectErr(Color.RED, null);
Timer timer = new Timer(1000, new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
System.out.println( new java.util.Date().toString() );
}
});
timer.start();
Thread.sleep(750);
Timer timer2 = new Timer(1000, new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
System.err.println( "Error Message: " + ++counter);
}
});
timer2.start();
}
}
In the following link you can find the MessageConsole class that someone mentioned. I implemented a software and used this solution and it works perfect for me.
I used the Netbeans design tool, so the code regarding the visual appearance of the JTextPane is a bit cumbersome, so I'm not going to place it here.
JTextPane jTextPane = new JTextPane();
MessageConsole console = new MessageConsole(jTextPane);
/*
This parameters are optional, but if you are looking for a solution with JTextPane it is because you need them, at least color.
*/
console.redirectErr(Color.RED, null);
console.redirectOut();
//some event
private void jButton1ActionPerformed(ActionEvent evt) {
/*
In this event I execute a function of my business.
I put it in a thread so that it does not block the graphical interface.
There are many calls to System.out.println() and System.err.println()
*/
BusinessClass bc = new BusinessClass();
Runnable runnable = () -> {
bc.someBusinessFn();
};
thread = new Thread(runnable);
thread.start();
}
//My main method
public static void main(String args[]) {
/* Create and display the GUI */
EventQueue.invokeLater(() -> {
new MyJFrame().setVisible(true);
});
}
Edit
Sorry, I did not realize that in the response similar to this, they had put the link to the MessageConsole class. I didn't see it and I also wanted to show my solution.

Categories