so I'm trying to insert an image underneath a JTextArea, but I havent had much luck, could anyone please help? Basically what I'm asking is if anybody could help make another class or subclass that does this. Heres my code:
import java.awt.*;
import javax.swing.*;
public class t{
private JFrame f; //Main frame
private JTextArea t; // Text area private JScrollPane sbrText; // Scroll pane for text area
private JButton btnQuit; // Quit Program
public t(){ //Constructor
// Create Frame
f = new JFrame("Test");
f.getContentPane().setLayout(new FlowLayout());
String essay = "Test";
// Create Scrolling Text Area in Swing
t = new JTextArea(essay, 25, 35);
t.setEditable(false);
Font f = new Font("Verdana", Font.BOLD, 12 );
t.setFont( f );
t.setLineWrap(true);
sbrText = new JScrollPane(t);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// Create Quit Button
btnQuit = new JButton("Quit");
btnQuit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
} } );
}
public void launchFrame(){ // Create Layout
// Add text area and button to frame
f.getContentPane().add(sbrText);
f.getContentPane().add(btnQuit);
// Close when the close button is clicked
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display Frame
f.pack(); // Adjusts frame to size of components
f.setSize(450,480);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String args[]){
t gui = new t();
gui.launchFrame();
}
}
The basic issue is that JTextArea will paint it's background and it's text within the paintComponent.
The simplest solution is to make the JTextArea transparent and take over the control of painting the background.
This example basically fills the background with the background color, paints the image and then calls super.paintComponent to allow the text to be rendered.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TransparentTextArea {
public static void main(String[] args) {
new TransparentTextArea();
}
public TransparentTextArea() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(new CustomTextArea()));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CustomTextArea extends JTextArea {
private BufferedImage image;
public CustomTextArea() {
super(20, 20);
try {
image = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Miho_Small_02.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public boolean isOpaque() {
return false;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
if (image != null) {
int x = getWidth() - image.getWidth();
int y = getHeight() - image.getHeight();
g2d.drawImage(image, x, y, this);
}
super.paintComponent(g2d);
g2d.dispose();
}
}
}
Check out the Background Panel. When you add a scrollpane to the panel it will make the scrollpane, viewport and text area all non-opaque so you can see the image.
Related
Hello I am new to Java GUI I made a second.java which is as below:
package theproject;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class second extends JPanel implements ActionListener {
private Timer animator;
private ImageIcon imageArray[];
private int delay=50, totalFrames=8, currentFreames=1;
public second()
{
imageArray= new ImageIcon[totalFrames];
System.out.println(imageArray.length);
for(int i=0; i<imageArray.length;i++)
{
imageArray[i]=new ImageIcon(i+1+".png");
System.out.println(i+1);
}
animator= new Timer(delay, this);
animator.start();
}
public void paintComponent(Graphics g )
{
super.paintComponent(g);
if(currentFreames<8)
{
imageArray[currentFreames].paintIcon(this, g, 0, 0);
currentFreames++;
System.out.println(currentFreames);
}
else{
currentFreames=0;
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
}
And a Gui calling the constructor second and output is not showing . Can you please guide me what should I do and the gui is given below:
package theproject;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
public class Sav {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sav window = new Sav();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Sav() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 0, 261, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
second s= new second();
frame.add(s);
}
});
btnNewButton.setBounds(273, -1, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
The gui has to basically call the constructor and which will showcase the animation on the screen If someone what i am doing wrong or if something that has to be done please let me know .
First, don't update the state within the paintComponent method, paint can occur for a number of reasons at any time, mostly without your interaction. Painting should simple paint the current state. In your ActionListener, you should advance the frame and make decisions about what should occur (like resetting the frame value)
Second, you never actually add second to anything, so it will never be displayed.
Third, you don't override getPreferredSize in second, so the layout managers will have no idea what size the component should be and will simply be assigned 0x0, making it as good as invisible as makes no difference
Fourth, you're using null layouts. This is going to make you life impossibly hard. Swing has been designed and optimised around the use of layout managers, they do important work in deciding how best to deal with differences in font metrics across different rendering systems/pipelines, I highly recommend that you take the time to learn how to use them
Fifthly, paintComponent has no business been public, no one should ever call it directly
Example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class Sav {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sav window = new Sav();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Sav() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(20);
frame.getContentPane().add(textField, gbc);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
second s = new second();
frame.add(s, gbc);
frame.getContentPane().revalidate();
frame.pack();
frame.setLocationRelativeTo(null);
}
});
frame.getContentPane().add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class second extends JPanel implements ActionListener {
private Timer animator;
private ImageIcon imageArray[];
private int delay = 50, totalFrames = 8, currentFreames = 1;
public second() {
imageArray = new ImageIcon[totalFrames];
for (int i = 0; i < imageArray.length; i++) {
imageArray[i] = new ImageIcon(getImage(i));
}
animator = new Timer(delay, this);
animator.start();
}
protected Image getImage(int index) {
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
FontMetrics fm = g2d.getFontMetrics();
g2d.dispose();
String text = Integer.toString(index);
int height = fm.getHeight();
int width = fm.stringWidth(text);
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setColor(getForeground());
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();
return img;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(imageArray[0].getIconWidth(), imageArray[1].getIconHeight());
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
imageArray[currentFreames].paintIcon(this, g, 0, 0);
}
#Override
public void actionPerformed(ActionEvent arg0) {
currentFreames++;
if (currentFreames >= imageArray.length) {
currentFreames = 0;
}
repaint();
}
}
}
Your code is also not working. It increment the values of image set but do not displays the images
Works just fine for me...
imageArray[i]=new ImageIcon(i+1+".png"); will not generate any errors if the image can't be loaded for some reason (and it will load the images in the background thread, which is just another issue).
Instead, I would recommend using ImageIO.read instead, which will throw a IOException if the image can't be read for some reason, which is infinitely more useful. See Reading/Loading an Image for more details
I have a JPanel with a JLabel which owns an Icon picture.
how do I set a transparent red color at the top of the whole JPanel (including JLabel Icon)?
I have the transparent backgriound color on for the panel but I want the whole panel including the picture and everything get this transparent color. something like a transparent colorful glass at the top of the JPanel
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TransparentJLabel {
private static final String IMAGE_PATH = "http://duke.kenai.com/Oracle/OracleStratSmall.png";
private static void createAndShowUI() {
JPanel panel = new JPanel();
panel.setBackground(Color.pink);
URL imageUrl;
try {
imageUrl = new URL(IMAGE_PATH);
BufferedImage image = ImageIO.read(imageUrl);
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
panel.add(label);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("TransparentJLabel");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
If you just need a layered panel over the whole contentPane, a simple glassPane will do fine (override it's paintComponent(...) method). For example:
JPanel glassPane = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
glassPane.setOpaque(false);
frame.setGlassPane(glassPane);
frame.getGlassPane().setVisible(true);
However, if you want a layered panel over only one JPanel, I would use JLayer combined with LayerUI, as MadProgrammer already mentioned. You will need a custom LayerUI in which you override the paint(Graphics g, JComponent c) method. I know that sounds dangerous, but I honestly don't know of another way of doing it...
I've provided an example below, this is the output:
As you can see, panel1 (or more accurately, the JLayer) is slighty transparent (RGBA = "0, 100, 0, 100") and panel2 is normal.
Code:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class Example {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
public Example() {
JFrame frame = new JFrame("Example");
JPanel panel1 = new JPanel();
panel1.add(new JButton("Panel 1"));
MyLayerUI layerUI = new MyLayerUI();
JLayer<JPanel> panel1Layer = new JLayer<JPanel>(panel1, layerUI);
panel1.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (layerUI.hasOverlay()) {
layerUI.setOverlay(false);
} else {
layerUI.setOverlay(true);
}
panel1Layer.repaint();
}
});
JPanel panel2 = new JPanel();
panel2.add(new JButton("Panel 2"));
JPanel contentPane = new JPanel(new GridLayout(2, 1));
contentPane.add(panel1Layer);
contentPane.add(panel2);
frame.setContentPane(contentPane);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyLayerUI extends LayerUI<JPanel> {
private boolean overlay = true;
#Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (hasOverlay()) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
g2.dispose();
}
}
public boolean hasOverlay() {
return overlay;
}
public void setOverlay(boolean overlay) {
this.overlay = overlay;
}
}
My Problem is that there's a little bar at the top of my screen which i want to remove (I want the picture to be fullscreen). I'm not sure though from which source this bar is caused.
picture
Here's my code till now:
lpane = new JLayeredPane();
lpane.setBackground(Color.BLACK);
panelBlue = new JPanel();
panelGreen = new JPanel();
frame.add(lpane);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
lpane.setBounds(0, 0, 1920, 1080);
BufferedImage background = null;
BufferedImage title = null;
try{
background = javax.imageio.ImageIO.read(getClass().getResource("resources/background.jpg"));
}catch(IOException ex){
sendErrorMessage("Picture couldn't be loaded"); //custom Errormessage Method
}
JLabel picLabel = new JLabel(new ImageIcon(background));
ImageIcon buttonbackground = new ImageIcon(flames);
panelBlue.add(picLabel);
panelBlue.setBounds(0, 0, 1920, 1080);
panelBlue.setOpaque(true);
frame.pack();
frame.setVisible(true);
I'm not sure if the cause is the JLabel or if it has something to do with the undecorated frame.
What's the cause and how can i remove the bar?
Thx in advance
Don't use setBounds. This is just plain wrong. The proper way is to use an appropriate LayoutManager. Additionaly, if you use pack(), using setBounds before is useless.
To put you frame in fullscreen, you can use any of the following:
frame.setExtendedState(frame.getExtendedState() & JFrame.MAXIMIZED_BOTH);
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame);
See this example that illustrates this:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;
public class TestFullScreen {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestFullScreen().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
public static class ImagePanel extends JPanel {
private ImageIcon imageIcon;
public ImagePanel(ImageIcon imageIcon) {
super();
this.imageIcon = imageIcon;
};
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imageIcon.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight());
}
}
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePanel(new ImageIcon(new URL("http://blog.timesunion.com/opinion/files/2011/10/brickwall.jpg"))));
frame.setUndecorated(true);
frame.pack();
frame.setExtendedState(frame.getExtendedState() & JFrame.MAXIMIZED_BOTH);
// GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame);
frame.setVisible(true);
}
}
I am (still) a beginner in Java, and I created a little software which contains a main frame.
I need to cover all the Desktop behind my software such as a windows 98 installing screen : (I need the black and blue screen behing, covering all the task bar etc).
In order to do this, I used GraphicsDevice which goes full screen. It is exactly what I needed :
public class Fond_noir extends JFrame {
private boolean isFullScreen = false;
private GraphicsDevice device;
public Fond_noir(int etat) {
GraphicsEnvironment env = GraphicsEnvironment
.getLocalGraphicsEnvironment();
this.device = env.getDefaultScreenDevice();
initFullScreen(etat);
}
private void initFullScreen(int etat) {
isFullScreen = device.isFullScreenSupported();
if (etat==0)
{
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
}
if (etat==1)
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
setUndecorated(isFullScreen);
setResizable(!isFullScreen);
if (isFullScreen) {
// Full-screen mode
device.setFullScreenWindow(this);
validate();
} else {
// Windowed mode
this.setExtendedState(MAXIMIZED_BOTH);
this.setVisible(true);
}
}
}
Then, I call this method in a main somewhere else, (there's no problem with this) :
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Fond_noir(0);
Choix_Langue inst = new Choix_Langue(); // main frame
inst.setLocationRelativeTo(null);
inst.setVisible(true);
} } ); }
But the problem is, that my main frame can't show-up, and it's hidden behind my fullscreen.. I'd like the opposite !
Or when I click on my main frame in my task bar (aften using the window key of my keyboard ofc..) I can only see my main frame, and the fullscreen is not showing-up with the frame
=> Is there a way to show both my frame and my GraphicsDevice ? Using "priorities" between them..?
Thanks for reading !
Use this:
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setAlwaysOnTop(true)
Undecorated will remove the titlebars. Also instead of trying to show both the frames seperately. Add the small one to the bigger one.
bigFrame.add(smallFrame);
bigFrame.setVisible(true);
Example to show that it works:
I'm not sure you need to go full screen exclusive mode, for example, you can size a border-less frame to fit the default screen size and make it always on top to help it cover all other windows in the system and then simply use a JDialog as the primary interface to work with the user, for example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class FullScreenBackground {
public static void main(String[] args) {
new FullScreenBackground();
}
public FullScreenBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
JFrame frame = new JFrame("Testing");
frame.setAlwaysOnTop(true);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BackgroundPane());
frame.setLocation(0, 0);
frame.setSize(dim);
frame.setVisible(true);
JDialog dialog = new JDialog(frame);
dialog.setContentPane(new InstallPane());
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
});
}
public class InstallPane extends JPanel {
public InstallPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JLabel("<html><h1>Welcome to my fancy pancy background screen<h1></html>"), gbc);
}
}
public class BackgroundPane extends JPanel {
private BufferedImage bg;
public BackgroundPane() {
}
#Override
public void invalidate() {
super.invalidate();
bg = null;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg == null) {
bg = new BufferedImage(1, getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bg.createGraphics();
LinearGradientPaint lgp = new LinearGradientPaint(
new Point(0, 0),
new Point(0, getHeight()),
new float[]{0f, 1f},
new Color[]{Color.BLACK, Color.BLUE}
);
g2d.setPaint(lgp);
g2d.fillRect(0, 0, 1, getHeight());
}
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
}
}
Updated
If changing all the "frames" is not hard, you could consider making the following changes to the above example...
JFrame frame = new JFrame("Testing");
frame.setAlwaysOnTop(true);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BackgroundPane());
frame.setLocation(0, 0);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setSize(dim);
// This will stop the background window from become focused,
// potentially hiding the other windows
frame.setFocusableWindowState(false);
frame.setFocusable(false);
frame.setVisible(true);
JFrame dialog = new JFrame();
// Will need to add this to each frame...
dialog.setAlwaysOnTop(true);
dialog.setContentPane(new InstallPane());
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
The other problem you might face is the fact that alwaysOnTop is platform dependent, meaning that it might behaviour differently on different platforms.
Changing extends JFrame to extends JDialog really would be a simpler and more stable change...
I found a solution with all your anwers.
Instead of using another frame I used a JWindow for the background :
public class Fond_noir extends JWindow{
Panel panel = new Panel();
public Fond_noir(int etat) {
if (etat==0)
{
setSize(2300,4000);
setLocationRelativeTo(null);
setVisible(true);
}
if (etat==1)
{
dispose();
}
panel.setBackground(Color.black);
add(panel);
}
class Panel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
}
}
}
Then while trying to change the "extends JFrame" of my main frame to "extends JDialog", it made me delete this horrible line in the code : this.setState(Frame.ICONIFIED); !!!!
It explains why I had to look for my icon all the time.. So I kept my JFrame..
So now it opens a background window AND the frame at the same time :)
Thank you everyone ! Next time I won't use that much frames.
I'm trying to print a string that the user can enter to a textbox, to a JFrame.
My problem is that the paintComponent method is never being called. Why?
PNGCreatorWindow Class:
public class PNGCreatorWindow {
private JFrame frame;
private JTextField txtText;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PNGCreatorWindow window = new PNGCreatorWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PNGCreatorWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 678, 502);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtText = new JTextField();
txtText.setBounds(121, 13, 216, 22);
frame.getContentPane().add(txtText);
txtText.setColumns(10);
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnGenerate.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
GeneratePNGImage();
}
});
btnGenerate.setBounds(436, 6, 183, 36);
frame.getContentPane().add(btnGenerate);
JPanel panel = new JPanel();
panel.setBounds(107, 151, 338, 160);
frame.getContentPane().add(panel);
}
protected void GeneratePNGImage() {
PNGImage img = new PNGImage(txtText.getText());
frame.getContentPane().add(img);
frame.getContentPane().validate();
frame.getContentPane().setVisible(true);
frame.repaint();
}
}
PNGImage Class:
public class PNGImage extends JComponent {
private String text;
public PNGImage(String text){
this.text = text;
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.red);
g2.drawString(this.text, 100,100);
g2.fillRect(50, 50, 1000, 1000);
}
}
I made a few changes to your code to get it to draw the text on the JPanel.
I put the JTextField and the JButton inside of a control panel (JPanel) and set a layout manager (FlowLayout) for the control panel. You should always use a layout manager for laying out Swing components.
I defined the image panel (PNGImage) as part of the laying out of the Swing components. First, you lay all of the Swing components out. Then, you change their state.
I removed the mouse adapter and just used an action listener on the JButton. The action listener works with the mouse.
In the PNGImage class, I added a setter, so I could pass the text to the class later, after the user typed the text in the JTextField.
I added a call to setPreferredSize so that I could set the size of the drawing canvas. I removed all other sizing, and used the pack method of JFrame to make the JFrame the appropriate size to hold the Swing components.
I added a null test to paintComponent, so that the text would only be drawn when there was some text to draw.
Here's the code. I put all the code in one module to make it easier to paste.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class PNGCreatorWindow {
private JFrame frame;
private JTextField txtText;
private PNGImage imagePanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new PNGCreatorWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PNGCreatorWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
txtText = new JTextField(10);
controlPanel.add(txtText);
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
generatePNGImage();
}
});
controlPanel.add(btnGenerate);
imagePanel = new PNGImage();
frame.getContentPane().add(controlPanel, BorderLayout.NORTH);
frame.getContentPane().add(imagePanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
protected void generatePNGImage() {
imagePanel.setText(txtText.getText());
imagePanel.repaint();
}
public class PNGImage extends JPanel {
private static final long serialVersionUID = 602718701626241645L;
private String text;
public PNGImage() {
setPreferredSize(new Dimension(400, 300));
}
public void setText(String text) {
this.text = text;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.text != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.drawString(this.text, 100, 100);
}
}
}
}
Edited to add an action listener that saves the contents of a JPanel as a .png file:
package com.ggl.crossword.controller;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.ggl.crossword.view.CrosswordFrame;
public class CreateImageActionListener implements ActionListener {
private CrosswordFrame frame;
private JPanel panel;
public CreateImageActionListener(CrosswordFrame frame,
JPanel panel) {
this.frame = frame;
this.panel = panel;
}
#Override
public void actionPerformed(ActionEvent event) {
writeImage();
}
public void writeImage() {
FileFilter filter =
new FileNameExtensionFilter("PNG file", "png");
JFileChooser fc = new JFileChooser();
fc.setFileFilter(filter);
int returnValue = fc.showSaveDialog(frame.getFrame());
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (!file.getAbsolutePath().endsWith(".png")) {
file = new File(file.getAbsolutePath() + ".png");
}
RenderedImage image = createImage(panel);
try {
ImageIO.write(image, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private BufferedImage createImage(JPanel panel) {
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
panel.paint(g);
g.dispose();
return bi;
}
}