How to make a transparent JFrame but keep everything else the same? - java

I want to make the JFrame transparent, but the image on top of it to be non-transparent. This is what I have now:
Does anyone know a way to make only the JFrame transparent?
Here's my code:
import javax.swing.*;
import java.awt.*;
import com.sun.awt.AWTUtilities;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
public class SplashDemo extends JFrame
{
public SplashDemo()
{
setUndecorated(true);
setSize(200, 200);
add(new JLabel(new ImageIcon("puppy2.png")));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setOpacity(0.85f);
}
public static void main(String[] args)
{
new SplashDemo();
}
}

Basically, you need to make a transparent window and a translucent content pane. This will mean anything added to the content pane will continue to be rendered without additional alphering...
public class TranscluentWindow {
public static void main(String[] args) {
new TranscluentWindow();
}
public TranscluentWindow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JWindow frame = new JWindow();
frame.setAlwaysOnTop(true);
frame.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
frame.setBackground(new Color(0,0,0,0));
frame.setContentPane(new TranslucentPane());
frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Puppy.png")))));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TranslucentPane extends JPanel {
public TranslucentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
}

Related

How do I add a line in Java GUI?

I'm trying to add a line into my program, it runs however displays nothing, how do I fix this?
I've watched tutorials and I've come up with the following code, but it doesn't display anything. How do I fix this?
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
}
Here is my full program:
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
public class GuiLine {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiLine window = new GuiLine();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GuiLine() {
initialize();
}
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Your class GuiLine has the method paint(Graphics g), but it will never be called since the class isn't a component (nor is it added to the frame, so it wouldn't be visible).
You can make the class extend JPanel and in your initialize method call frame.add(this);. Then you can continue reading some more tutorials.

Want to create a frame taking mouse input and implements drawLines()

I am trying to create a frame that is taking input from mouse and also make x/o grid on frame using drawLines(). But I am able to do only one of the two.
Here is my code:
public class Test extends JPanel {
public static void main(String[] args) {
Test t = new Test();
t.dispFrame();
}
public static void dispFrame()
{
JFrame frame = new JFrame("My New Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 300));
frame.setResizable(false);
JPanel panel=new JPanel();
panel.addMouseListener(new MouseListener()
{
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(":MOUSE_CLICK_EVENT:");
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("\n:MOUSE_PRESSED_EVENT:");
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(":MOUSE_RELEASED_EVENT:");
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println(":MOUSE_ENTER_EVENT:");
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println(":MOUSE_EXITED_EVENT:");
}
});
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(30,100,270,100);
g.drawLine(30,200,270,200);
g.drawLine(100,35,100,250);
g.drawLine(200,35,200,250);
}
}
If you want to override the paintComponent() method on your panel, you should do something like this,
JPanel panel = new JPanel() {
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(30,100,270,100);
g.drawLine(30,200,270,200);
g.drawLine(100,35,100,250);
g.drawLine(200,35,200,250);
}
};
In your code, your are overriding the paintComponent() in your Test class, which will throw a compile time error if your Test class itself is not a subclass Component.

How to deal with public void paint() method in JFrame

My problem is that when i use
public void paint(Graphics g)
{}
Method to draw a String as
g.drawString("hello java",0,0);
My full code is
import javax.swing.*;
import java.awt.*;
class test
extends JFrame
{
public void testing()
{
setSize(500,500);
show();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{ super.paint(g);
g.drawString("HELLO JAVA");
}
public static void main(String arg[])
{
test t=new test();
t.testing();
} }
In JFrame i am getting a black screen without hello java being drawn
Please help me
Thanks in advance
To display the inherited frame correctly, the paint method in the inherited class should contain the call of super.paint():
class MyFrame extends JFrame {
public void paint(Graphics g) {
super.paint(g);
g.drawString("hello java", 50, 50);
}
}
EDIT (painting in the panel):
import java.awt.*;
import javax.swing.*;
public class CustomPaint {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("CustomPaint");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MyPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
class MyPanel extends JPanel {
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
String msg = "HELLO JAVA";
g2.setPaint(Color.BLUE);
int w = (getWidth() - g.getFontMetrics().stringWidth(msg)) / 2;
g2.drawString(msg, w, getHeight() / 2);
}
}

How to Remove JFrame Border as to Let an Image Touch The Edge

I had a friend make a background for the program I made so that it wouldn't look so plain, and I thought the best way to place the images would be to make a JLabel, fill it with an image, and set it to the size of the screen. This worked fine, except there is a small border around the JFrame and I can't get the JLabel to touch the edges of the frame. Thoughts? I have attached a picture.
public class ProgramDriver extends JFrame {
private JPanel contentPane;
private static CardLayout cardLayout;
private JTextField addGradeN;
private JTextField addGradeD;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProgramDriver frame = new ProgramDriver();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Global Variables
...
manager = new StateManager(gb);
//JFrame Settings
setTitle("Grade Book");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 656, 530);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
cardLayout = new CardLayout(0,0);
contentPane.setLayout(cardLayout);
setResizable(false);
//Home Panel
final JPanel Home = new JPanel();
contentPane.add(Home, "Home");
Home.setLayout(null);
JButton btnSeeGrades = new JButton("See Grades");
...
//Grades Panel
JPanel Grades = new JPanel();
contentPane.add(Grades, "Grades");
Grades.setLayout(null);'
The problem isn't with the JFrame, the problem is with your code. We can spend the rest of our natural life at guessing what's wrong or you can post some example code.
Now it's up to you, we can keep trying to throw wrong guess after wrong guess at you, frustrating us all, or you can help us help you...
Here are two examples I did. The first uses a JLabel as the primary content for a JPanel, where the child components are placed on it. Nice and simple.
The second uses a custom JPanel which paints the image onto the background of the component. I then use this to replace the frames content pane. This is a little more involved, but it has the added benefit of been easily updated (replacing the content pane won't effect the rest of the program)
Example 1: JLabel used as background
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LabelPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class LabelPane extends JPanel {
public LabelPane() {
BufferedImage bg = null;
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(new ImageIcon(bg));
setLayout(new BorderLayout());
add(label);
label.setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
label.add(lblMessage);
}
}
}
Example 2: Image used as background, replacing content pane...
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class BackgroundPane extends JPanel {
private BufferedImage bg = null;
public BackgroundPane() {
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
add(lblMessage);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1153, 823);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
g.drawImage(bg, 0, 0, this);
}
}
}
}
To expand on Eng.Fouad's answer, you'll want to use the drawImage(...) method that takes 6 parameters, image, x and y location, image width and height, and image observer, and draw it like so from within a JPanel:
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
For example, my sscce:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ExpandingImage extends JPanel {
public static final String GUITAR = "http://duke.kenai.com/Oracle/OracleStrat.png";
BufferedImage img;
public ExpandingImage(String imgUrlPath) throws IOException {
URL imgUrl = new URL(imgUrlPath);
img = ImageIO.read(imgUrl);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
private static void createAndShowGui() {
ExpandingImage mainPanel;
try {
mainPanel = new ExpandingImage(GUITAR);
JFrame frame = new JFrame("ExpandingImage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit
I see that you're using an EmptyBorder around the contentPane. Why if you don't want this border to be present?
As an alternative, you can override the method paintComponent(Graphics g) of JPanel (the contentPane) and use drawImage() on the Graphics object g as in this example.
have you tried JFrame function setUndecorated() ?
Make the frame undecorated. frame.setUndecorated(true)
If you want to make it move, you can use the ComponentMover of the Java2S.
Make sure that it is undecorated before it is visible.
Next, use setContentPane(new JLabel(new ImageIcon("myimage.jpg")));
After, that you can add contents as usual.

Why doesn't GlassPane work with JDIC's WebBrowser?

I have the following program to test GlassPane, but it doesn't work with JDIC's WebBrowser. Does anyone know what I did wrong and how to make it work?
import org.jdesktop.jdic.browser.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class Test_Panel extends JPanel
{
static WebBrowser webBrowser=new WebBrowser();
static int W=802,H=702;
Test_Panel()
{
setPreferredSize(new Dimension(W,H));
setLayout(new BorderLayout());
webBrowser.setPreferredSize(new Dimension(W,H));
// add("Center",webBrowser);
try { webBrowser.setURL(new URL("http://www.yahoo.com")); }
catch (MalformedURLException e) { e.printStackTrace(); }
}
static void Create_And_Show_GUI()
{
JFrame frame=new JFrame("Test");
frame.add(new Test_Panel());
frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
new My_GlassPane(frame,W,H);
frame.pack();
frame.setBounds(0,0,W,H);
frame.setVisible(true);
}
public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } }); }
}
class My_GlassPane extends JComponent
{
JFrame f;
int W,H,Edge,Size;
public My_GlassPane(JFrame f,int W,int H)
{
this.f=f;
this.W=W;
this.H=H;
Edge=W/100;
Size=W/5;
f.setGlassPane(this);
f.getGlassPane().setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(W/6,H*18/120,W*2/3,H*2/3);
g.setColor(Color.white);
g.setFont(new Font("Times New Roman",0,Size));
g.drawString("Test",W/3,H*68/120);
}
}
If you uncomment add("Center",webBrowser); you will see what I mean-- the GlassPane won't show up. Why not?
You need to have "jdic.jar" and "IeEmbed.exe" to make it work. The version I have is 0.9.1.0 and you can get them here.
As I've read, WebBrowser is an AWT component while GlassPane is a Swing component. There is a common problem mixing heavyweight and lightweight components. I don't think there is a workaround on what you're trying to do.
More information on this subject can be found in this discussion.

Categories