up

Tricky solutions for some Java Swing issue

Almost all beginner Java Swing programmers meet these issues. I have written some code example for representing the solution. This issue collection is useful for some situation, but please comment it.

Maximize a Java Frame

How to maximize the JFrame (main window) from code:

import java.swing.JFrame;

public class MyFrame extend JFrame {
   public MyFrame() {
     // the application window is run as maximized
     this.maximize();

     // some code ...
   }

   /**
    * Maximize the Frame.
    */
   public void maximize() {
     this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
   }
}

JTextArea Auto scroll down

Add a JTextArea to a JPanel:

public class MyFrame extend JFrame {
  private JTextArea area;
  //...

  public MyFrame() {
    //...
    JScrollPane pane = new JScrollPane();
    this.area = new JTextArea();
       
    this.area.setLineWrap(true);
    this.area.setWrapStyleWord(true);
    this.area.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    this.area.setText("Hello");
       
    pane.setPreferredSize(new Dimension(200,200));
    pane.getViewport().add(area);
    panel.add(pane);

    add(panel);
    //...
  }

  //...
}

Next, append some message to the JTextArea. For example these are a log messages, what show real-time events. This case the textarea need to scrolling down to show the last message in every time.
Append some message example:

//...
public void setMessage(String msg) {
  this.area.append(msg + "\n");
  this.area.setCaretPosition(area.getDocument().getLength());
}
//...
Blog categories:  Programming

Comments

Add new comment