Swing JPanel wird überschrieben

not_me

Mitglied
Hallo, ich habe ein Programm, das Daten von einem Server herunter läd und verarbeitet. Diese beiden Vorgänge erzeugen Logeinträge, die verschiedenfarbig in einem Fenster angezeigt werden. Da der gesammte Prozess biszu 10min dauern kann, wird eine Progressbar angezeigt, damit der User weiß, dass das Programm noch läuft. Es gibt jeweils eine Klasse für den Download, das LogWindow und die Progressbar. Jede Klasse wird vom Main Programm als eingenständiger Thread gestartet. Das klappt auch alles sehr gut, jedoch wird am Ende der Inhalt des LogWindows fast immer gelöscht bzw. übermahlt. Ich komme einfach nicht dahinter, wiso das so ist. Ich hoffe jemand kann mir helfen. Zu Testzwecken habe ich das Programm stark verkürzt und den Download-Teil durch einen einfachen Counter ersetzt. Hier der Code:
Java:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;

import java.math.BigInteger;
import info.clearthought.layout.TableLayout;


// Calculate the power of 0 too 1000 and show the result of every step in a log window.
// While the calculation is running, a progress bar is shown in an additional window.
public class LogWindowTest
{ 	
	private static myProgressBar tProgress;					// A progress bar
	private static counter tCounter;						// A counter, to waste some time
	private static LogWindow lw;							// Shows the log in a window
	
	// For alternately changing the color of a log entry
	private static boolean lastEntryWasBlack = false;	
	
	
	public static void main( String args[] ) throws Exception
	{
		newRun();  				// Do a run on program start  
	}
	
	// Create and start the threads 
	public static void newRun()
	{
		// Create new progress bar
		tProgress = new myProgressBar(); 
		
		// Create new counter thread
		tCounter =   new counter();		
		tCounter.setMax(1000);
		
		// Create and start  new log window
		lw = new LogWindow();
		lw.setData();	    
		lw.start();
		lw.showWindow();
		
		// Start the progress bar and the counter thread
		tProgress.start();
		tCounter.start(); 		
		
		System.out.println("New run started...");
	}
	  
	// Stop the counter thread
	public static void stopCounter()
	{
		tCounter.brake();
	}
	
	public static void stopProgressBar()
	{
		tProgress.close();
	}
	  
	// Refresh the log window
	public static void refreshWin()
	{
		lw.refreshWindow();
	}
	
	
	// Reduce BigInteger b to a maximum of 10 digits
	// & add it to the log
	public static void addToLog(BigInteger b, int x)
	{
		String bAsString=""; 
		
		// Reduce BigInteger b to a maximum of 10 digits
		if (b.bitLength() > 10 )
		{			
			byte[] bArray = b.toByteArray();
			int max = bArray.length;
			
			if (max > 10){
				max = 10;
			}
			
			for (int i=0; i<max; i++)
			{
				bAsString = bAsString + bArray[i];
			}
			bAsString = bAsString + "...";			
		}
		else{
			bAsString = b.toString();
		}
		
		// Create output text
		String text = ( x + "^" + x + " = " + bAsString );
		
		// Add text to log, alternately in black or blue
		if (lastEntryWasBlack){
			lw.newLogListEntry(text, Color.BLUE);
			lastEntryWasBlack = false;
		}
		else{
			lw.newLogListEntry(text, Color.BLACK);
			lastEntryWasBlack = true;
		}
		
	}	  
}

// Creates a window (JFrame) and add a progress bar to it.
class myProgressBar extends Thread implements ActionListener 
{	
	private JProgressBar progressBar;
	private JLabel label = new JLabel ("Download process:");
	private JButton btnCancel = new JButton("Cancel");
	private JFrame frame = new JFrame();
	
	// The main method, that creates the frame for the progress bar
	public void run()
	{		
		// set title and add action listener for the button
		frame.setTitle("Loading System Dump. Please wait...");
		this.btnCancel.addActionListener(this);
		
		// Set the TableLayout for the frame	    
	    double size[][] =
	    {{ 0.04, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, 0.04,},				 // 5 columns				
	    { 0.04, TableLayout.FILL, 0.04, TableLayout.FILL, 0.04, TableLayout.FILL, 0.04 } };	 // 7 rows
	    frame.setLayout (new TableLayout(size));
	    
	    // set icon and screen size
		frame.setSize(350, 100);
		
		// Create the progress bar
		this.progressBar = new JProgressBar();
		// the progress bar is always running from left to right and back
		this.progressBar.setIndeterminate(true);		
		this.progressBar.setSize(100, 50);
		
		// add all elements to the frame
		frame.add(label, "1, 1, 3, 1");
		frame.add(progressBar, "1, 3, 3, 1" );		
		frame.add(btnCancel, "2, 5, 1, 1");
	     
		// set screen position and show the frame
		frame.setLocation(150, 150);
		frame.setVisible(true);
	}
	
	// Close the update progress bar
	public void close() 
	{	
		System.out.println("... run completed");
		frame.dispose();
	}	
	
	// If button 'cancel' gets pushed: call 'close()'
	public void actionPerformed(ActionEvent arg0) 
	{
		close();
		LogWindowTest.stopCounter();
	}
}
	  
// The counter thread, that waist the time and create the output  
class counter extends Thread   
{
	private myProgressBar p = null;
	private int max = 0;
	private boolean boBrake = false;	
	
	// Set the maximum 
	public void setMax(int newMax){
		max = newMax;		
	}
	
	// Calculation
    public void run()  
    {
    	int i=0;
    	
    	while ( i<max && !boBrake ){	    		
    		BigInteger a = BigInteger.valueOf(i).pow(i);
    		LogWindowTest.addToLog(a, i);							// add to log
    		i++;
    	} 	
    	
    	LogWindowTest.refreshWin();
    }
    
    // Stop the calculation (caused by the cancel button of the progress bar)
    public void brake()
    {
    	boBrake = true;
    }
    
    // Stop/close the progress bar
    public void stopProgBar()
    {
    	LogWindowTest.stopProgressBar();
    }
}

// The window, that show the update progress
class LogWindow extends Thread
{	 
	private JList logList;
	private JMenuItem jmiEnde, jmiNewRun;
	private Listener al;
	private Container lfwContainer;				
	private JPanel panlogListe;	
	private JFrame fLog;									
	private DefaultListModel model;				
	private LogListEntry entry;
	
	// Prepare the needed elements
	public void setData()
	{
		logList = new JList();
		al = new Listener();
		fLog = new JFrame();									
		model = new DefaultListModel();				
	}
	
	// create a new window on start()
	public void run(){	
		createWindow();
	}
	
	// Create a new window
	public void createWindow(){		
		
		// Create a new JList & add 'model'
		logList.setModel(model);								// 'model' contains the log data
		logList.setCellRenderer( new LogListCellRenderer() );
		
		lfwContainer = fLog.getContentPane();	 				// get the container of fLog   
		lfwContainer.add(logList);
	    	    

		// Create new JPanel AND add the List
		panlogListe = new JPanel( new BorderLayout() );
		panlogListe.add(new JScrollPane(logList), BorderLayout.CENTER);
		
		// Creates MenuBar, Menu AND Menu-Items
		JMenuBar jmb = new JMenuBar();
		JMenu jmFile = new JMenu("File");
		jmiEnde = new JMenuItem("Close");
		jmiNewRun = new JMenuItem("New run");
		
		// Add action-listener to Menu-Items
		jmiEnde.addActionListener(al);
		jmiNewRun.addActionListener(al);
		
		// Add every thing to MenuBar
		jmFile.add(jmiNewRun);
		jmFile.addSeparator();
		jmFile.add(jmiEnde);
		jmb.add(jmFile);
		
		// Add every thing to window and set the properties
		fLog.setJMenuBar(jmb);
		fLog.setTitle("Update Status");
		fLog.add(panlogListe);
		fLog.setLocation(520, 120);
		fLog.setSize(500, 600);
	}
	
	// Show the window (visibility is set to true)
	public void showWindow()
	{		
		fLog.setVisible(true);
	}
		
	// Close the window
	public void closeWindow()
	{		
		fLog.dispose();
	}
	
	// Refresh the window
	public void refreshWindow()
	{		
		fLog.repaint();
		fLog.validate();
	}
	
	// Creates a new log entry, that will have the content 'text' 
	// and will be shown in color 'col' 
	public void newLogListEntry(String text, Color col)
	{		
		entry = new LogListEntry(text, col);
		model.addElement(entry);
	}
	
	// ActionListener for Menu-Items 'New run' & 'End' 
	private class Listener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if (e.getSource() == jmiNewRun)	
			{
				fLog.dispose();					// Close the log window
				createWindow();					// Create a new one
				LogWindowTest.newRun();			// Start a new run
			}
			
			if (e.getSource() == jmiEnde)	// Exit the program
			{
				fLog.dispose();
			}
			
		}
	}
		
	// Definition of object: 'LogListEntry'
	// to create use: LogListEntry(String content, Color fontcolor)
	public class LogListEntry {
	
		  private String content;
		  private Color fontcolor;	
		  
		  public LogListEntry(String content, Color fontcolor){
		     this.content = content;
		     this.fontcolor = fontcolor;
		  }
		  
		  public String getContent() 
		  {
		    return content;
		  }
		  public void setContent(String content)
		  { 
		    this.content = content;
		  }
		  public Color getFontcolor() 
		  {
		    return fontcolor;
		  }
		  public void setFontcolor(Color fontcolor) 
		  {
		    this.fontcolor = fontcolor;
		  }
	}
	
	// Change some features of ListCellRenderer for a better color-handling in the log-output
	public class LogListCellRenderer extends JLabel implements ListCellRenderer {
		  
		private static final long serialVersionUID = 1977L;

		@Override
		  public Component getListCellRendererComponent(JList list, Object value,
		      int index, boolean isSelected, boolean cellHasFocus) {

		    // Cast a LogListValue as LogFileWindow.LogListEntry 
			LogListEntry entry = (LogListEntry) value;

		    // set text to entry-content
		    this.setText(entry.getContent());
		    
		    // Activate 'this.setBackground'
		    this.setOpaque(true);
		    
		    // If List-Item is Selected:
		    if(isSelected){
		    	// Font-Color
		    	this.setForeground(Color.MAGENTA);
		    	// Background-Color
		    	this.setBackground(Color.LIGHT_GRAY);
		    }
		    // If List-Item is NOT Selected:
		    else{
		      // Font-Color
		      this.setForeground(entry.getFontcolor());
		      // Background-Color
		      this.setBackground(UIManager.getColor("logList.background"));
		    }		    
		    // Return this Label
		    return this;
		  }
	}
}
 
S

SlaterB

Gast
die meisten GUI-Elemente dürfen nicht wild von anderen Threads verändert werden,
wenn das mit Zeichen-Vorgängen kollidiert kann allles mögliche schiefgehen,
hier eine sichere Variante für deinen counter:

Java:
		while (i < max && !boBrake) {
			final BigInteger a = BigInteger.valueOf(i).pow(i);
			final int fi = i;
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					LogWindowTest.addToLog(a, fi); // add to log
				}
			});
			i++;
		}

wenn die Schleife schnell ist, so wie hier, dann kann auch der gesamte Block komplett in ein invokeLater() gesetzt werden,
wenn aber das ganze 10 min dauert und nur alle paar sec in praktisch nicht messbarer Zeit ein Eintrag erzeugt wird, dann nur diesen einzelnen Aufruf mit invokeLater(),
denn solange ein invokeLater() von der GUI ausgeführt wird, ist die GUI blockiert, keine Reaktion, kein Neuzeichnen
 
Zuletzt bearbeitet von einem Moderator:

not_me

Mitglied
Also im Testprogramm läufts super, danke. Mal nachher in das Hauptprogramm über tragen. *edit* Da läufts auch super, vielen Dank.
 
Zuletzt bearbeitet:
Ähnliche Java Themen
  Titel Forum Antworten Datum
O Swing "Eigenes" JPanel wird dem JScrollPane nicht hinzugefügt AWT, Swing, JavaFX & SWT 5
J JPanel wird nicht angezeigt AWT, Swing, JavaFX & SWT 2
DaCrazyJavaExpert Swing JPanel "ContentPane" wird nicht gesetzt/angezeigt AWT, Swing, JavaFX & SWT 16
DaCrazyJavaExpert Swing Größe des JPanel ändern/wird nicht geändert. AWT, Swing, JavaFX & SWT 3
DaCrazyJavaExpert Swing JPanel wird in JScollPane nicht angezeigt AWT, Swing, JavaFX & SWT 2
G Nur ein JPanel wird angezeigt AWT, Swing, JavaFX & SWT 9
L ImageIcon auf JPanel wird nicht angezeigt(keiner Fehlermeldung) AWT, Swing, JavaFX & SWT 11
T JTextField Array im JPanel wird nicht komplett angezeigt AWT, Swing, JavaFX & SWT 7
thobren Swing Im JPanel wird nur TextArea gelöscht AWT, Swing, JavaFX & SWT 13
C Image laden und Speichern - Image wird auf JPanel nicht angezeigt AWT, Swing, JavaFX & SWT 4
R JPanel paintComponents() wird nicht aufgerufen AWT, Swing, JavaFX & SWT 5
A JPanel wird nach Buttonklick nicht angezeigt AWT, Swing, JavaFX & SWT 2
J 2D-Grafik JPanel wird nicht angezeigt AWT, Swing, JavaFX & SWT 0
S Geladenes Bild wird nicht in JPanel angezeigt AWT, Swing, JavaFX & SWT 7
J 2D-Grafik JPanel wird erst 1-2sek nach start des JFrames angezeigt AWT, Swing, JavaFX & SWT 3
K JPanel wird nicht gezeichnet AWT, Swing, JavaFX & SWT 4
S Swing JLabel wird in JPanel nicht sichtbar AWT, Swing, JavaFX & SWT 2
R Instanz einer Subklsse von JPanel wird nicht angezeigt. AWT, Swing, JavaFX & SWT 15
H Swing JPanel Inhalt wird bei verwenden von JPopup gelöscht AWT, Swing, JavaFX & SWT 5
R JPanel wird erst neu gezeichnet nach erneuter auswahl AWT, Swing, JavaFX & SWT 8
H Swing paint() von JPanel wird nicht aufgerufen AWT, Swing, JavaFX & SWT 10
W JMenu wird vom JPanel ständig überzeichnet... Abhilfe? AWT, Swing, JavaFX & SWT 3
Z JPanel wird erst durch aufziehen des Fensters sichtbar AWT, Swing, JavaFX & SWT 3
Ä Graphics-Komponente auf JPanel wird nicht angezeigt AWT, Swing, JavaFX & SWT 4
V Bild wird nicht auf JPanel gezeichnet; Java Problem AWT, Swing, JavaFX & SWT 10
T grafik in jpanel wird nicht neugezeichnet AWT, Swing, JavaFX & SWT 7
E Problem mit JPanel - Wann wird size berechnet? AWT, Swing, JavaFX & SWT 5
P Zwei JPanel übereianderlegen AWT, Swing, JavaFX & SWT 14
XWing Basic JPanel mit 2 Buttons beutzen. AWT, Swing, JavaFX & SWT 10
G JPanel per Drag and Drop JButtons und Bilder ablegen AWT, Swing, JavaFX & SWT 1
G JPanel mit JButtons und Bilder AWT, Swing, JavaFX & SWT 5
N AWT JPanel zu Jframe hinzufügen AWT, Swing, JavaFX & SWT 2
M clear JPanel before repainting AWT, Swing, JavaFX & SWT 1
B ImageIcon auf JPanel austauschen AWT, Swing, JavaFX & SWT 3
T Swing Reload JPanel + darin liegende ProgressBar AWT, Swing, JavaFX & SWT 9
P Swing Mehrere JLabels mit ImageIcon in JPanel lesen AWT, Swing, JavaFX & SWT 1
E JScrollPane mit JPanel verbinden AWT, Swing, JavaFX & SWT 1
F JPanel Celleditor AWT, Swing, JavaFX & SWT 8
B JPanel-Inhalte inkl. JTextarea zoomen? AWT, Swing, JavaFX & SWT 3
B Mit ContentPane werden Komponenten angezeigt, mit SplitPane, JPanel nicht? AWT, Swing, JavaFX & SWT 6
CptK Funktionsgraphen effizient zeichnen und nur Teile von JPanel erneuern AWT, Swing, JavaFX & SWT 2
P Button simpler random auf einem JPanel verteilen? AWT, Swing, JavaFX & SWT 3
Ich lerne Java. Swing Von JPanel A auf JPanel B zugreifen. AWT, Swing, JavaFX & SWT 4
A JPanel austauschen und Focus geben AWT, Swing, JavaFX & SWT 3
E Auf JPanel malen und davor JComponenten anzeigen AWT, Swing, JavaFX & SWT 12
L JComponent aus JPanel anhand Mausposition ermitteln AWT, Swing, JavaFX & SWT 10
B Verschiebbares JPanel "ruckelt" im Randbereich AWT, Swing, JavaFX & SWT 2
S Swing JPanel nimmt keinen KeyListener an AWT, Swing, JavaFX & SWT 7
K JLabel mit Bilder im nicht initialisierten JPanel hinzufügen AWT, Swing, JavaFX & SWT 5
Hatsi09 Swing JPanel Bild einfügen AWT, Swing, JavaFX & SWT 14
L JPanel zeigt keinen Inhalt AWT, Swing, JavaFX & SWT 1
dereki2000 JPanel mit Rückgbe wie bei JOptionPane AWT, Swing, JavaFX & SWT 3
E Hintergrundfarbe setzen in JPanel funktioneirt nicht AWT, Swing, JavaFX & SWT 4
P JPanel KeyListener hinzufügen AWT, Swing, JavaFX & SWT 8
S Nach scrollen verschwindet das zuvor im JPanel gezeichnete AWT, Swing, JavaFX & SWT 2
P Bewegung eines Balkens in eineum JPanel welches als Spielfeld fungiert AWT, Swing, JavaFX & SWT 2
L Swing JPanel Größe anpassen AWT, Swing, JavaFX & SWT 6
D Platzierung von JTextfield in JPanel AWT, Swing, JavaFX & SWT 3
D Swing Anwendung ohne JPanel erstellen AWT, Swing, JavaFX & SWT 1
M Swing JPanel in JScrollPane AWT, Swing, JavaFX & SWT 3
M Zwei JPanel übereinander nur vorderes "repainten" AWT, Swing, JavaFX & SWT 3
J 2D-Grafik Background einer Jpanel Klasse ändern AWT, Swing, JavaFX & SWT 1
J Ziehen eines Buttons im JPanel AWT, Swing, JavaFX & SWT 2
J Button lässt sich nicht auf dem JPanel verschieben AWT, Swing, JavaFX & SWT 5
D zwei JLabel stapeln in einem JPanel AWT, Swing, JavaFX & SWT 5
it_is_all JPanel verschwindet nach Button-Klick AWT, Swing, JavaFX & SWT 2
B Bar Plot in Swing JPanel AWT, Swing, JavaFX & SWT 0
F Screenshot eines JPanel AWT, Swing, JavaFX & SWT 3
S JPanel rotieren, Bild ist abgeschnitten, Clipping? AWT, Swing, JavaFX & SWT 0
M Swing JPanel flüssig verschieben AWT, Swing, JavaFX & SWT 5
kilopack15 JPanel im laufenden Zustand einfärben AWT, Swing, JavaFX & SWT 2
kilopack15 JPanel Farbverwaltung AWT, Swing, JavaFX & SWT 1
A JScrollPane soll JPanel mit JButtons enthalten und eine Scollbar anzeigen AWT, Swing, JavaFX & SWT 1
A Swing JLabels in einer ForEach Schleife an den JPanel anheften (UNO Netzwerkspiel) AWT, Swing, JavaFX & SWT 1
L JPanel zeichnet im Konstrukter erzeugten Hintergrund nicht AWT, Swing, JavaFX & SWT 10
Java_RY wie kann ich auf JButtons in einem JPanel zugreifen AWT, Swing, JavaFX & SWT 3
F Zeichnung einem JPanel im Layoutmanager zuweisen AWT, Swing, JavaFX & SWT 3
Meeresgott Swing Umgang mit JPanel AWT, Swing, JavaFX & SWT 4
R 2D-Grafik PNG Bild per Graphics auf JPanel AWT, Swing, JavaFX & SWT 9
K JPanel Bilder bei Windows nicht darstellbar AWT, Swing, JavaFX & SWT 6
W Swing JPanel nur einmal nach mehreren Änderungen neu zeichnen AWT, Swing, JavaFX & SWT 1
J Swing Zeichenfläche im JPanel des Haupfenster anzeigen lassen AWT, Swing, JavaFX & SWT 4
A Swing JPanel zeigt Buttons nicht an AWT, Swing, JavaFX & SWT 4
R JPanel überzeichnet alles? AWT, Swing, JavaFX & SWT 1
D Von JPanel auf anderes JPanel zugreifen AWT, Swing, JavaFX & SWT 9
L Swing Teile eines JPanel in eigene Klasse auslagern AWT, Swing, JavaFX & SWT 3
I JPanel - Verwaltung/ Anordnung AWT, Swing, JavaFX & SWT 4
T JComponents zur Laufzeit auf JPanel darstellen AWT, Swing, JavaFX & SWT 10
F Java Swing Rechteck in JPanel zeichnen AWT, Swing, JavaFX & SWT 7
J Linien auf JPanel zeichnen AWT, Swing, JavaFX & SWT 3
M Swing JPanel innerhalb eines Frames verschieben AWT, Swing, JavaFX & SWT 3
K Swing JPanel ueber komplette Form legen AWT, Swing, JavaFX & SWT 1
W Swing Größenänderung vom JPanel im JScrollPane und anschließendes positionieren AWT, Swing, JavaFX & SWT 2
R Komponenten von JPanel bleiben unsichtbar AWT, Swing, JavaFX & SWT 2
O JTabeddpane aber jedes JPanel als eigene Klasse anlegen AWT, Swing, JavaFX & SWT 7
llabusch Linien in JPanel zeichnen AWT, Swing, JavaFX & SWT 6
I (JPanel) paintComponent mit Zeitverschiebung (Sleep/Wait) AWT, Swing, JavaFX & SWT 1
H Netbeans Designer: Probleme mit JPanel und JFrame AWT, Swing, JavaFX & SWT 2
S jpanel anchor bottom AWT, Swing, JavaFX & SWT 1
A JPanel größe verändern AWT, Swing, JavaFX & SWT 4

Ähnliche Java Themen

Neue Themen


Oben