Using ProgressBar in Java Lanterna

319 Views Asked by At

I tried to use ProgressBar as below:

    ProgressBar Prog=new ProgressBar(0,100,50);
    Prog.setValue(0)
    //
    BufferedReader bf = new BufferedReader(new FileReader(file1));
    String line = bf.readLine();
        while (line != null) {
                lines.add(line);
                Prog.setValue((int)(100*(double)lines.size()/MaxLen)); //ProgressBar  will ot be updated
      
                line = bf.readLine();

        }
            bf.close();  

I also tried this method:

 ProgressBar.DefaultProgressBarRenderer DP=new ProgressBar.DefaultProgressBarRenderer();
 DP.drawComponent((TextGUIGraphics)gui.getScreen().newTextGraphics(),Prog  );

GUI is MultiWindowTextGUI belong to contex, but it does not work because of Cast Problem:

 com.googlecode.lanterna.screen.AbstractScreen$1 cannot be cast to com.googlecode.lanterna.gui2.TextGUIGraphics

Edit2:in component aproach, it need this:

Prog.setRenderer(new ProgressBar.DefaultProgressBarRenderer());

and a timer:

   Timer timer = new Timer("ProgressBar-timer", true);
         timer.schedule(new TimerTask() {
             @Override
             public void run() {
                //Do some thing
             }
         }, 10, 10);
1

There are 1 best solutions below

4
hc_dev On BEST ANSWER

Assume you wanted to draw a progress-bar on the screen somehow.

Issue

But gui.getScreen().newTextGraphics() is giving TextGraphics and not desired TextGUIGraphics.

Draw on the screen

Given your renderer, you can use it to draw the progressBar on your screen.

Therefore, use the renderer's method drawComponent(TextGUIGraphics graphics, ProgressBar component):

// Given
MultiWindowTextGUI textGui = createGuiOn(screen);
TextGraphics textGraphics = screen.newTextGraphics();

// What you need, but don't get
TextGUIGraphics graphics = null;  // WARNING: There is no method to get the graphics object from!

// Then
renderer.drawComponent( graphics, progressBar );

The drawing is a low-level rendering action. See Tutorial 3.

And there seems neither a constructor, nor a public method, that gives you that TextGUIGraphics, see the search on the GitHub repo.

Instead consider to work with components like ProgressBar.

Work with components

ProgressBar is a component. So you can add it simply to your TextGUI:

final Window window = new BasicWindow("My Root Window");  // create window
window.setComponent(progressBar);  // set component of window

textGUI.addWindowAndWait(window);  // add window to gui

See Tutorial 4 for working with components.