Hintergrundfarbe von Panels durchsichtig machen

Na so in etwa:

   private Image image;

   PicturePanel(Image image) {
      this.image = image;
   }

   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      if(image != null) {
         g.drawImage(image, 0, 0, this);
      }
   }
}```

Dieses Panel wäre dein Panel, welches das Hintergrundbild trägt. Und das baust in deine GUI ein.

Achso, so eine Klasse habe ich schon:


import java.awt.*;
import java.io.*;
import javax.swing.*;

class GUI_MyJPanel extends JPanel {

	private Image image;

	public GUI_MyJPanel(Image file) {
		image = file;
		repaint();
	}

	public GUI_MyJPanel(String file) {
		this(Toolkit.getDefaultToolkit().getImage(file));
	}

	public GUI_MyJPanel(File file) {
		this(file.toString());
	}

	public void paintComponent(Graphics g) {
		g.drawImage(image, 0, 0, null);
	}
}```

Meine Frage lautet, wo ich die **repaint()**-Methode in der Klasse **OpaqueProblem** einbauen muss.

Ich habe es schon in **setCenterPanel()** probiert, allerdings ohne Erfolg:
```		public void setCenterPanel(JPanel panel) {
			JPanel panel2 = new JPanel();
			panel2.setLayout(new GridBagLayout());
			panel2.add(panel);
			gesamtPanel.remove(centerPanel);
			centerPanel = panel2;
			centerPanel.repaint();
			gesamtPanel.add(BorderLayout.CENTER, centerPanel);
			gesamtPanel.validate();
}```

Warum willst du repaint() überhaupt aufrufen?
Normalerweise brauchst du keinen expliziten Aufruf. Das macht die VM bereits. Nötig wird diese Maßnahme nur durch den Programmierer, wenn zur Laufzeit das Bild gewechselt/geändert werden soll.
Du hast wohl noch ein anderes Problem.

Scheint so zu sein. Das Hintergrundbild wird nämlich erst angezeigt, wenn ich die Größe vom Fenster (mit dem Cursor) änder (dann wird ja doch auch die paintComponent()-Methode aufgerufen, oder verstehe ich da was falsch?).

http://media-mobi.com/de/?play-v2aml9jk1eyk7q1twyxrbgdartwu1irl

Die paintComponent()-Methode ist eine “automatische” Methode, die von der VM augerufen wird, wenn es etwas zu zeichnen gibt. Der Programmierer kann natürlich die VM anweisen ein Neuzeichnen durchzuführen.
Aber in deinem Fall sollte das schon erledigt sein, wenn du das Fenster angezeigt bekommst.
Möglicherweise hast du einen setVisible()-Befehl noch vor den Hinzufügen deines PicturePanels gesetzt.

Hab ich ja schon probiert, ohne Erfolg…

Ist es aber leider nicht…

Nein, der kommt als letztes.

Nochmal mein Code:


import java.io.File;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class OpaqueProblem {
	private ArrayList<GUI_tabs> tabListe = new ArrayList<GUI_tabs>();
	private static final int fensterHoeheStandard = 700;
	private static final int fensterBreiteStandard = 800;
	private JFrame fenster = new JFrame();

	private GUI_MyJPanel ueberschriftPanel;

	private GUI_JTabbedPaneWithCloseIcons tabs = new GUI_JTabbedPaneWithCloseIcons();

	public OpaqueProblem() {
		fenster.setSize(fensterBreiteStandard, fensterHoeheStandard);
		fenster.setLocationRelativeTo(null);

		if (ueberschriftPanel != null) {
			fenster.add(BorderLayout.NORTH, ueberschriftPanel);
		}
		fenster.add(BorderLayout.CENTER, tabs);
	}

	public void addTab(int arrayNr, String titel, JPanel panel,
			boolean closeIcon) {
		tabListe.add(arrayNr, new GUI_tabs(titel, panel, closeIcon));
	}

	public GUI_tabs getTab(int arrayNr) {
		return tabListe.get(arrayNr);
	}

	public void setSichtbar(boolean sichtbar) {
		fenster.setVisible(sichtbar);
	}

	public void schliessenBeimSchliessen() {
		fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	class GUI_tabs {

		private GUI_MyJPanel gesamtPanel;
		private JPanel northPanel = new JPanel();
		private JPanel eastPanel = new JPanel();
		private JPanel centerPanel = new JPanel();

		private GUI_tabs() {
			File bgGesamtpanel = new File(getClass().getResource(
					"bg_gesamtpanel.jpg").getFile());
			bgGesamtpanel = new File(String.valueOf(bgGesamtpanel).replace(
					"%20", " "));
			gesamtPanel = new GUI_MyJPanel(bgGesamtpanel);
			gesamtPanel.repaint();

			centerPanel.setOpaque(false);
			System.out.println(centerPanel.isOpaque());
		}

		public GUI_tabs(String titel, JPanel panel, boolean closeIcon) {
			this();

			setCenterPanel(panel);
			if (closeIcon) {

				tabs.addTab(titel, gesamtPanel);
			} else {
				tabs.addTabWithoutCloseIcon(titel, gesamtPanel);
			}
		}

		public void setNorthPanel(JPanel panel) {
			JPanel panel2 = new JPanel();
			panel2.setLayout(new GridBagLayout());
			panel2.add(panel);
			gesamtPanel.remove(northPanel);
			northPanel = panel2;
			gesamtPanel.add(BorderLayout.NORTH, northPanel);
			gesamtPanel.validate();
		}

		public void setEastPanel(JPanel panel) {
			JPanel panel2 = new JPanel();
			panel2.setLayout(new GridBagLayout());
			panel2.add(panel);
			gesamtPanel.remove(eastPanel);
			eastPanel = panel2;
			gesamtPanel.add(BorderLayout.EAST, eastPanel);
			gesamtPanel.validate();
		}

		public void setCenterPanel(JPanel panel) {
			JPanel panel2 = new JPanel();
			panel2.setLayout(new GridBagLayout());
			panel2.add(panel);
			gesamtPanel.remove(centerPanel);
			centerPanel = panel2;
			gesamtPanel.add(BorderLayout.CENTER, centerPanel);
			gesamtPanel.validate();
		}

	}

	public static void main(String[] args) {
		OpaqueProblem fenster = new OpaqueProblem();
		fenster.schliessenBeimSchliessen();

		JPanel panel = new JPanel();
		JLabel label = new JLabel("Tab1");
		panel.add(label);
		fenster.addTab(0, "Tab1", panel, false);

		panel.add(new JButton("Tab1"));
		fenster.getTab(0).setCenterPanel(panel);
		fenster.getTab(0).centerPanel.setOpaque(false);

		System.out.println(fenster.getTab(0).centerPanel.isOpaque());

		fenster.setSichtbar(true);
	}

}```

```package testPackage;

import java.awt.*;
import java.io.*;
import javax.swing.*;

class GUI_MyJPanel extends JPanel {

	private Image image;

	public GUI_MyJPanel(Image file) {
		image = file;
		repaint();
	}

	public GUI_MyJPanel(String file) {
		this(Toolkit.getDefaultToolkit().getImage(file));
	}

	public GUI_MyJPanel(File file) {
		this(file.toString());
	}

	public void paintComponent(Graphics g) {
		g.drawImage(image, 0, 0, null);
	}
}```

```package testPackage;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * A JTabbedPane which has a close ('X') icon on each tab.
 * 
 * To add a tab, use the method addTab(String, Component)
 * 
 * To have an extra icon on each tab (e.g. like in JBuilder, showing the file
 * type) use the method addTab(String, Component, Icon). Only clicking the 'X'
 * closes the tab.
 */
public class GUI_JTabbedPaneWithCloseIcons extends JTabbedPane implements
		MouseListener {
	public GUI_JTabbedPaneWithCloseIcons() {
		super();
		addMouseListener(this);
	}

	public void addTab(String title, Component component) {
		this.addTab(title, component, null);
	}

	public void addTab(String title, Component component, Icon extraIcon) {
		super.addTab(title, new CloseTabIcon(extraIcon), component);
	}

	public void addTabWithoutCloseIcon(String title, Component component) {
		super.addTab(title, component);
	}

	public void mouseClicked(MouseEvent e) {
		try {
			int tabNumber = getUI().tabForCoordinate(this, e.getX(), e.getY());
			if (tabNumber < 0)
				return;
			Rectangle rect = ((CloseTabIcon) getIconAt(tabNumber)).getBounds();
			if (rect.contains(e.getX(), e.getY())) {
				// the tab is being closed
				this.removeTabAt(tabNumber);
			}
		} catch (NullPointerException ex) {
			System.out
					.println("Gewöhnliche Nullpointer-Exception, tritt auf bei Tab ohne Close-Icon");
		}
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}
}

/**
 * The class which generates the 'X' icon for the tabs. The constructor accepts
 * an icon which is extra to the 'X' icon, so you can have tabs like in
 * JBuilder. This value is null if no extra icon is required.
 */
class CloseTabIcon implements Icon {
	private int x_pos;
	private int y_pos;
	private int width;
	private int height;
	private Icon fileIcon = null;

	public CloseTabIcon(Icon fileIcon) {
		this.fileIcon = fileIcon;
		width = 16;
		height = 16;
	}

	public void paintIcon(Component c, Graphics g, int x, int y) {
		this.x_pos = x;
		this.y_pos = y;

		Color col = g.getColor();

		g.setColor(Color.black);
		int y_p = y + 2;

		g.drawLine(x + 1, y_p, x + 12, y_p);
		g.drawLine(x + 1, y_p + 13, x + 12, y_p + 13);
		g.drawLine(x, y_p + 1, x, y_p + 12);
		g.drawLine(x + 13, y_p + 1, x + 13, y_p + 12);
		g.drawLine(x + 3, y_p + 3, x + 10, y_p + 10);
		g.drawLine(x + 3, y_p + 4, x + 9, y_p + 10);
		g.drawLine(x + 4, y_p + 3, x + 10, y_p + 9);
		g.drawLine(x + 10, y_p + 3, x + 3, y_p + 10);
		g.drawLine(x + 10, y_p + 4, x + 4, y_p + 10);
		g.drawLine(x + 9, y_p + 3, x + 3, y_p + 9);
		if (fileIcon != null) {
			fileIcon.paintIcon(c, g, x + width, y_p);
		}
		g.setColor(col);
	}

	public int getIconWidth() {
		return width + (fileIcon != null ? fileIcon.getIconWidth() : 0);
	}

	public int getIconHeight() {
		return height;
	}

	public Rectangle getBounds() {
		return new Rectangle(x_pos, y_pos, width, height);
	}
}```

Alle Klassen zum Runterladen: [http://www.uploadarea.de/files/3ylmvydis8mcgpewnlnl5kjbb.zip](http://www.uploadarea.de/files/3ylmvydis8mcgpewnlnl5kjbb.zip)

Du hast dir da einen regelrechten Panel-Wald geschaffen.
Am besten ist es du schreibst dir ein KSKB (Kurzes selbstständiges kompilierbares Beispiel), in welchem du sich auf das Wesentliche konzentrierst und unnötigen Ballast erst mal außen vor lässt. Dann lässt sich der Fehler schneller eingrenzen und beheben.

Hiho,

wenn es wie unten aussehen soll, dann fehlt folgende Zeile:

panel.add(new JButton("Tab1"));
//-----------------------
panel.setOpaque(false);
//-----------------------
fenster.getTab(0).setCenterPanel(panel);

bye Saxony

Hiho,

wenn es wie unten aussehen soll, dann fehlt doch folgende Zeile:

panel.add(new JButton("Tab1"));
//-----------------------
panel.setOpaque(false);
//-----------------------
fenster.getTab(0).setCenterPanel(panel);

bye Saxony

Hier ein KSKB (immer noch mit dem gleichen Bug):


import java.io.*;
import javax.swing.*;
import java.awt.*;

class OpaqueProblemKSKB {
	public static void main(String[] args) {
		new OpaqueProblemKSKB().los();
	}

	public void los() {
		JFrame fenster = new JFrame("OpaqueProblemKSKB");
		fenster.setSize(500, 500);
		fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		File background = new File(getClass().getResource("bg_gesamtpanel.jpg")
				.getFile());
		background = new File(String.valueOf(background).replace("%20", " "));
		MyJPanel panel = new MyJPanel(background);
		panel.add(new JButton("Button"));
		
		fenster.add(panel);
		fenster.setVisible(true);
		panel.repaint();
	}
}

class MyJPanel extends JPanel {

	private Image image;

	public MyJPanel(Image file) {
		image = file;
		repaint();
	}

	public MyJPanel(String file) {
		this(Toolkit.getDefaultToolkit().getImage(file));
	}

	public MyJPanel(File file) {
		this(file.toString());
	}

	public void paintComponent(Graphics g) {
		g.drawImage(image, 0, 0, null);
	}
}```

Dann einfach noch irgendeine Datei mit dem Namen **bg_gesamtpanel.jpg** in den Ordner mitreinpacken ([http://www.abload.de/img/bg_gesamtpanel77f.jpg](http://www.abload.de/img/bg_gesamtpanel77f.jpg)).

Jetzt läuft’s.

Habe den einen Konstruktor durch folgendes ersetzt:

		this(new ImageIcon(file).getImage()); 
	}```