I have the problem of this textarea not showing up when I run it. Is there any way to make it show up. BTW its getting called through the gameloop on a class that extends canvas.
public void render(Graphics g){
Graphics2D g2d = (Graphics2D) g;
if(!initialized)
init();
try {
test.requestFocus();
test.paintAll(g);
test.setText("hi");
test.setBounds(getBounds());
test.printAll(g);
} catch (Exception e) {
e.printStackTrace();
}
g2d.draw(getBounds());
g.drawRect(0, 0, 100, 100);
}
private void init(){
frame.setVisible(false);
initialized = true;
test = new TextArea();
test.setEditable(true);
test.setBounds(getBounds());
test.setBackground(test.getBackground());
test.setForeground(test.getForeground());
frame.add(test);
frame.repaint();
frame.setVisible(true);
System.out.println(test.isVisible());
}
private Rectangle getBounds(){
return new Rectangle(100, 100, 100, 100);
}
I have tried using JTextArea but it takes up the full screen and won't bind to a rect. Thanks for help in advance!
You don't need to manually paint existing Components you add to your program. Here is a simple example how to display a TextArea over a frame/canvas you paint yourself: Check the comments for further details.
package main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Test extends JFrame {
private static Test frame;
private static double t;
private static int x;
private static int y;
private static TextArea test;
public static void main(String[] args) {
frame = new Test();
frame.setVisible(true);
// set layout to null so that you can freely position your components
// without them "filling up the whole screen"
frame.setLayout(null);
frame.setSize(500, 500);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
// game loop
new Timer(10, (e) -> {
t += 10.0 / 1000;
x = (int) (100 + 50 * Math.sin(t));
y = (int) (100 + 50 * Math.cos(t));
// calling repaint will cause Test.paint() to be called first,
// then Test's children will be painted (= the TextArea)
frame.repaint();
}).start();
// initialize the textarea only once
test = new TextArea();
test.setEditable(true);
test.setBounds(new Rectangle(100, 100, 100, 100));
test.setText("hi");
frame.add(test);
}
#Override
public void paint(Graphics g) {
// put only painting logic in your paint/render.
// don't set the bounds of components here,
// as this will trigger a repaint.
g.setColor(Color.black);
g.fillRect(0, 0, 400, 400);
g.setColor(Color.yellow);
g.fillOval(x, y, 20, 20);
}
}
Related
After learning that dispose() should be called on Graphics/Graphics2D object after use, I went about changing my game to incorporate this.
When I added g2d.dispose() in overridden paintComponent(Graphics g) of JPanel, my components which I added (extensions of JLabel class) where not rendered I was able to still click on them etc but they would not be painted.
I tested with a normal JLabel and JButton with same effect (though JButton is rendered when mouse is over it).
So my question is why does this happen?
Here is an SSCCE to demonstrate:
after uncommenting call to dispose() in paintComponent of MainMenuPanel class:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
try {
initComponents();
} catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void initComponents() throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
MainMenuPanel mmp = new MainMenuPanel();
frame.add(mmp);
frame.pack();
frame.setVisible(true);
}
}
class MainMenuPanel extends JPanel {
//create labels for Main Menu
private PopUpJLabel versusesModeLabel;
private PopUpJLabel singlePlayerModeLabel;
private PopUpJLabel optionsLabel;
private PopUpJLabel helpLabel;
private PopUpJLabel aboutLabel;
//create variable to hold background
private Image background;
private Dimension preferredDimensions;
public static String gameType;
public static final String SINGLE_PLAYER = "Single Player", VERSUS_MODE = "VS Mode";
/**
* Default constructor to initialize double buffered JPanel with
* GridBagLayout
*/
public MainMenuPanel() {
super(new GridBagLayout(), true);
try {
initComponents();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Could not load main menu background!", "Main Menu Error: 0x004", JOptionPane.ERROR_MESSAGE);
System.exit(4);
}
}
/*
* Create JPanel and its components
*/
private void initComponents() throws Exception {
//set prefered size of JPanel
preferredDimensions = new Dimension(800, 600);
background = scaleImage(800, 600, ImageIO.read(new URL("http://photos.appleinsider.com/12.08.30-Java.jpg")));
//create label instances
singlePlayerModeLabel = new PopUpJLabel("Single Player Mode");
singlePlayerModeLabel.setEnabled(false);
versusesModeLabel = new PopUpJLabel("Versus Mode");
optionsLabel = new PopUpJLabel("Options");
helpLabel = new PopUpJLabel("Help");
aboutLabel = new PopUpJLabel("About");
//create new constraints for gridbag
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.HORIZONTAL;
gc.ipady = 50;//vertical spacing
//add newGameLabel to panel with constraints
gc.gridx = 0;
gc.gridy = 0;
add(singlePlayerModeLabel, gc);
gc.gridy = 1;
add(versusesModeLabel, gc);
//add optionsLabel to panel with constraints (x is the same)
gc.gridy = 2;
add(optionsLabel, gc);
//add helpLabel to panel with constraints (x is the same)
gc.gridy = 3;
add(helpLabel, gc);
//add aboutLabel to panel with constraints (x is the same)
gc.gridy = 4;
add(aboutLabel, gc);
}
public static BufferedImage scaleImage(int w, int h, BufferedImage img) throws Exception {
BufferedImage bi;
//bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
bi = new BufferedImage(w, h, img.getType());
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(img, 0, 0, w, h, null);
g2d.dispose();
return bi;
}
/*
* Will return the preffered size of JPanel
*/
#Override
public Dimension getPreferredSize() {
return preferredDimensions;
}
/*
* Will draw the background to JPanel with anti-aliasing on and quality rendering
*/
#Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
//convert graphics object to graphics2d object
Graphics2D g2d = (Graphics2D) grphcs;
//set anti-aliasing on and rendering etc
//GamePanel.applyRenderHints(g2d);
//draw the image as the background
g2d.drawImage(background, 0, 0, null);
//g2d.dispose();//if I uncomment this no LAbels will be shown
}
}
class PopUpJLabel extends JLabel {
public final static Font defaultFont = new Font("Arial", Font.PLAIN, 50);
public final static Font hoverFont = new Font("Arial", Font.BOLD, 70);
PopUpJLabel(String text) {
super(text);
setHorizontalAlignment(JLabel.CENTER);
setForeground(Color.ORANGE);
setFont(defaultFont);
//allow component to be focusable
setFocusable(true);
//add focus adapter to change fints when focus is gained or lost (used for transversing labels with keys)
addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent fe) {
super.focusGained(fe);
if (isEnabled()) {
setFont(getHoverFont());
}
}
#Override
public void focusLost(FocusEvent fe) {
super.focusLost(fe);
setFont(getDefaultFont());
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent me) {
super.mouseEntered(me);
if (isEnabled()) {
setFont(getHoverFont());
}
//call for focus mouse is over this component
requestFocusInWindow();
}
});
}
Font getDefaultFont() {
return defaultFont;
}
Font getHoverFont() {
return hoverFont;
}
}
The thing is that the Graphics context you are using in paintComponent is created and provided by the caller (the framework), which is also responsible for disposing of it.
You only need to dispose of Graphics when you actually create it yourself (for example by calling Component.getGraphics()). In your case, you're not creating it, you're just casting it, so do not call dispose in this case.
Because .dispose() releases your resources. Yes, everything.
I just started using Intelli J Idea and one of my first projects is to plot some geometric forms to a JPanel of a GUI defined in a form. In the end I want to plot some graphs. I found a tutorial where a class extending the JPanel was defined and the paintCompontent() method was overloaded.
public class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int y2 = (int)(40 * Math.random());
Line2D line = new Line2D.Double(10, 10, 60, y2);
Rectangle2D rectangle = new Rectangle2D.Double(200, 120, 70, 30);
Ellipse2D oval = new Ellipse2D.Double(400, 200, 40, 60);
g2.draw(line);
g2.setPaint(Color.RED);
g2.fill(rectangle);
g2.setPaint(Color.ORANGE);
g2.fill(oval);
}
}
This would run fine if I use it together with this code:
public class MainClass {
public static void main(String[] args) {
MyPanel s = new MyPanel();
JFrame f = new JFrame();
f.add(s);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 400);
}
}
Then I tried combining this with a form I created using Intelli J Idea. And this is where I have problems. I would like to have a form with a button and a JPanel. When I press the button some geometric figures are being drawn on the JPanel defined in the form. I think my best try is like this:
public class MainWindow {
private JPanel panelMain;
private JButton buttonCalculate;
private JPanel panelPlot;
public MainWindow() {
buttonCalculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panelPlot = new MyPanel();
panelPlot.setBackground(Color.CYAN);
panelPlot.setSize(200, 200);
panelPlot.setVisible(true);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("MyFirstGraphTool");
f.setContentPane(new MainWindow().panelMain);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 400);
f.setVisible(true);
}
}
But simply saving my derived JPlane object to the bound property does not change anything.
And also the setBackgroundColor() method does not change anything.
Do you know any tutorials or more detailed explanation of how this can be done?
EDIT: Please find below an image of the component tree.
Component tree from Intelli J Idea
Thanks and kind regards,
David
You've made lots of mistakes in your code. I try to explain you, what's wrong.
public class MainWindow {
private JPanel panelMain; // panelMain is not initialized, so when you try to add it to any window/panel, you'll get a NullPointerException
private JButton buttonCalculate; // same as before. Also this button is not added to any container (window/panel)
private JPanel panelPlot; // panel is not added to any container
public MainWindow() {
buttonCalculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panelPlot = new MyPanel();
panelPlot.setBackground(Color.CYAN);
panelPlot.setSize(200, 200); // this code will not be honored because the layout manager will recalculate panel bounds.
// use setPreferredSize instead.
panelPlot.setVisible(true);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("MyFirstGraphTool");
f.setContentPane(new MainWindow().panelMain);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 400);
f.setVisible(true);
}
}
Here is the correct version of your class
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* <code>MainWindow</code>.
*/
public class MainWindow {
private JPanel panelMain = new JPanel();
private JButton buttonCalculate = new JButton("Calculate");
private JPanel panelPlot; // panel is not added to any container
public MainWindow() {
buttonCalculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panelPlot = new MyPanel();
panelPlot.setOpaque(true);
panelPlot.setBackground(Color.CYAN);
panelPlot.setPreferredSize(new Dimension(200, 200));
panelMain.add(panelPlot);
panelMain.revalidate(); // cause layout manager to recalculate component bounds
}
});
panelMain.add(buttonCalculate);
}
public static void main(String[] args) {
JFrame f = new JFrame("MyFirstGraphTool");
f.setContentPane(new MainWindow().panelMain);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 400);
f.setVisible(true);
}
static class MyPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int y2 = (int) (40 * Math.random());
Line2D line = new Line2D.Double(10, 10, 60, y2);
Rectangle2D rectangle = new Rectangle2D.Double(200, 120, 70, 30);
Ellipse2D oval = new Ellipse2D.Double(400, 200, 40, 60);
g2.draw(line);
g2.setPaint(Color.RED);
g2.fill(rectangle);
g2.setPaint(Color.ORANGE);
g2.fill(oval);
}
}
}
Please also read about layout managers in Swing
I want to create a fully transparent background for a Frame (or JFrame) and have it show a transparent animation. I managed to get it working in Windows 7 x64 but the same code does not run on my Linux (Lubuntu x64 15.04).
The code below shows what I'm trying to achieve--just copy & paste it. I just want the little rectangle to move across the screen without leaving a trail.
static int a = 0;
public static void main(String[] args) {
JFrame f = new JFrame();
f.setUndecorated(true);
f.setBackground(new Color(0, 0, 0, 0));
f.setVisible(true);
f.setSize(512, 512);
f.add(new JPanel() {
#Override
public void paintComponent(Graphics gr) {
Graphics2D g = (Graphics2D)gr;
g.setBackground(new Color(0, 0, 0, 0));
g.clearRect(0, 0, 512, 512);
g.drawRect(a, a++, 2, 2);
}
});
while(true) {
try {
Thread.sleep(30);
} catch(InterruptedException e) {
e.printStackTrace();
}
f.repaint();
}
}
What I want to achieve (as shown in Windows) and what I get with Lubuntu 15.04:
I just want to see the little square move just like what's shown on Windows 7--I don't want to see a trail.
Please don't give me the link of Oracle's transparency and window documentation--I've gone over it all thrice.
What I've tried:
Graphics2D's 'copyArea()' of a transparent space. (This used to work AFAIK but no longer does)
GlassPane
AlphaComposite
setPaint()
Please please just test out your thoughts/code first. A lot of the "this should work" stuff I have already tried and does not seem to... All help is greatly appreciated.
For reference, here's a minimal complete example, suitable for cross-platform testing. Note that
On some platforms, e.g. Ubuntu, a completely transparent background is not seen as opaque; a small, non-zero alpha value is a typical work-around.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
Use java.swing.Timer, which runs on the event dispatch thread, to pace the animation.
Don't use setPreferredSize() when you really mean to override getPreferredSize().
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
* #see https://stackoverflow.com/a/31328464/230513
*/
public class TransparentAnimation {
private static final Color tranparentBlack = new Color(0, 0, 0, 1);
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.setBackground(tranparentBlack);
f.add(new JPanel() {
int x, y;
Timer t = new Timer(10, (ActionEvent e) -> {
x = (x + 1) % getWidth();
y = (y + 1) % getHeight();
repaint();
});
{
setBackground(tranparentBlack);
t.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g.fillOval(x, y, 16, 16);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
});
f.add(new JLabel(System.getProperty("os.name") + "; v"
+ System.getProperty("os.version")), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new TransparentAnimation()::display);
}
}
Basically this issue is OS-related. What works for Windows will not work for Linux and vice versa.
For some reason, Linux only allows animated per-pixel-transparency when setting up a BufferStrategy. However, this solution fails on Windows. As a result I have come up with the following code which picks the correct algorithm based on the OS:
static int a = 0;
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel p = new JPanel() {
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setBackground(new Color(255, 255, 255, 0));
g2d.clearRect(0, 0, f.getWidth(), f.getHeight());
g2d.drawRect(a, a++, 2, 2);
}
};
f.add(p);
f.setUndecorated(true);
f.setBackground(new Color(255, 255, 255, 0));
f.setSize(512, 512);
f.setVisible(true);
f.createBufferStrategy(2);
BufferStrategy bs = f.getBufferStrategy();
while (true) {
try {
Thread.sleep(33);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (System.getProperty("os.name").contains("indows ")) {
p.repaint();
} else {
Graphics g = null;
do {
try {
g = bs.getDrawGraphics();
p.update(g);
} finally {
g.dispose();
}
bs.show();
} while (bs.contentsLost());
Toolkit.getDefaultToolkit().sync();
}
}
}
This code works for my Windows 7 x64 and my Lubuntu 15.04 x64. Please try out this code out yourself and see if it works for you. I myself don't own a Mac so if someone would please test it for me I would be very grateful. If it does not work for anyone, please let me know.
This is what you're supposed to see:
If we extend JFrame, set undecorated to true, and override paint with, we can make a transparent JFrame.
try this,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestTransparentFrame {
private class PaintPanel extends JPanel {
private List<Point> points = new ArrayList<Point>();
public PaintPanel() {
setOpaque(false);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
points.clear();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);
setBorder(BorderFactory.createLineBorder(Color.GREEN));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (points.size() > 1) {
g.setColor(Color.RED);
Point p1 = points.get(0);
for (int i = 1; i < points.size(); i++) {
Point p2 = points.get(i);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(700, 500);
}
}
protected void createAndShowGUI() throws MalformedURLException, IOException {
JFrame frame = new JFrame("Test transparent painting");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 50));
frame.add(new PaintPanel());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestTransparentFrame().createAndShowGUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
So I'm trying to change the background on a full screen game I'm making from a tutorial, I'm trying to change the background to green, but it stays black, what's wrong with the code?
Screen.java
package debels;
import java.awt.*;
import javax.swing.JFrame;
public class Screen {
private GraphicsDevice vc;
public Screen(){
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame window){
window.setUndecorated(true);
window.setResizable(false);
vc.setFullScreenWindow(window);
if (dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
}catch (Exception e){}
}
}
public Window getFullScreen(){
return vc.getFullScreenWindow();
}
public void restoreScreen(){
Window w = vc.getFullScreenWindow();
if (w != null){
w.dispose();
}
vc.setFullScreenWindow(null);
}
}
Main.java
package debels;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame{
private static final long serialVersionUID = -7498470134154894036L;
public static void main(String[] args){
DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
Main m = new Main();
m.run(dm);
}
public void run(DisplayMode dm){
setBackground(Color.GREEN);
setForeground(Color.BLUE);
setFont(new Font("Arial", Font.PLAIN, 24));
Screen s = new Screen();
try{
s.setFullScreen(dm, this);
try{
Thread.sleep(5000);
}catch(Exception e){}
}finally{
s.restoreScreen();
}
}
public void paint(Graphics g){
g.drawString("Hello", 200, 200);
}
}
Your first problem is going to be your paint method...
public void paint(Graphics g){
g.drawString("Hello", 200, 200);
}
Part of the responsibility of the paint method is to paint...the background. But since you're not calling super.paint this can't happen.
You should avoid overriding paint on top level containers, like JFrame and instead use a custom component, like JPanel for example, and override their paintComponent method (not forgetting to call super.paintComponent).
Another area of potential issue is the use of Thread.sleep, this could be causing the Event Dispatching Thread to be halted, preventing from processing new paint requests. A better solution might be to use a javax.swing.Timer, which will pause in the background and provide notification (via a ActionListener) within the context of the EDT...
For example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestFullScreen {
public static void main(String[] args) {
new TestFullScreen();
}
public TestFullScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
final Screen s = new Screen();
DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
s.setFullScreen(dm, frame);
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
s.restoreScreen();
}
});
timer.start();
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.GREEN);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.PLAIN, 24));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
FontMetrics fm = g2d.getFontMetrics();
String text = "It's not easy to be green";
int x = (width - fm.stringWidth(text)) / 2;
int y = ((height - fm.getHeight()) / 2) + fm.getAscent();
System.out.println(width + "x" + height);
System.out.println(x + "x" + y);
g2d.drawString(text, x, y);
g2d.dispose();
}
}
public class Screen {
private GraphicsDevice vc;
public Screen() {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame window) {
window.setUndecorated(true);
window.setResizable(false);
vc.setFullScreenWindow(window);
if (dm != null && vc.isDisplayChangeSupported()) {
try {
vc.setDisplayMode(dm);
} catch (Exception e) {
}
}
}
public Window getFullScreen() {
return vc.getFullScreenWindow();
}
public void restoreScreen() {
Window w = vc.getFullScreenWindow();
if (w != null) {
w.dispose();
}
vc.setFullScreenWindow(null);
}
}
}
This is what I did to overcome the challenge. I removed the setBackground, setForeground, and setFont from the run method in the Main class and added them to the setFullScreen method in the Screen class:
window.getContentPane().setBackground(Color.PINK);
window.setForeground(Color.BLUE);
window.setFont(new Font ("Arial", Font.PLAIN, 24));
Thereafter, I added "super.paint(g);" as the first line of the paint method in the Main class
You just need to make 3 little changes and it will work. Follow these steps:
Step-1:Add getContentPane() to setBackgroud() which is present in the run() method
getContentPane().setBackground(Color.GREEN);
Step-2: Cut & paste below lines from run() method to paint() method.
getContentPane().setBackground(Color.GREEN);
setForeground(Color.BLUE);
setFont(new Font("Arial", Font.PLAIN, 24));
step-3: Add super.paint(g) in the starting of paint() method. the whole paint() method will look like this;
public void paint(Graphics g){
super.paint(g);
getContentPane().setBackground(Color.GREEN);
setForeground(Color.BLUE);
setFont(new Font("Arial", Font.PLAIN, 24));
g.drawString("Hello", 200, 200);
}
if it still doesn't work let me know in the comment! #YNWA
I'm trying to built a simple app which has a translucent frame and it draws lines where the user wants.I have also added listeners to catch the mouse events and these are displayed accordingly .Everything is working fine but the problems are:
1)the window is not transparent
2)it is completely black and the lines are appearing white.
Can anyone
Here is the code:
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MouseListen2 extends JFrame implements MouseListener {
String str = "Nothing";
int x[][] = new int[100][2];
int count = 0;
int flag = 1;
boolean draw = false;
MouseListen2() {
super("Line Draw App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
this.addMouseListener(this);
setBackground(new Color(0, 0, 0, 0));
JPanel jp = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Paint gp = new GradientPaint(300, 700, new Color(20, 20, 210, 0), 100, 00, new Color(10, 20, 40, 255));
g2.setPaint(gp);
g2.fillRect(0, 0, getWidth(), getHeight());
}
};
setContentPane(jp);
setVisible(true);
//c.setOpaque(true);
}
public void paint(Graphics g) {
//Graphics g=this.getGraphics();
//super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.clearRect(0, 0, getWidth(), getHeight());
g2.drawString(str, 50, 50);
//initially count=0 hence i<-1 so loop will not automatically run in the beginning
for (int i = 0; i < count - 1; i = i + 2) {
g2.drawLine(x[i][0], x[i][1], x[i + 1][0], x[i + 1][1]);
}
//repaint(); using this here creates an infinite loop as after mouse event paint is called and at the end
//this method is again called using the repaint() and so on the loop continues.
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MouseListen2();
}
});
}
#Override
public void mouseClicked(MouseEvent e) {
str = "clicked";
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
str = "pressed";
repaint();
x[count][0] = e.getX();
x[count][1] = e.getY();
count++;
}
#Override
public void mouseReleased(MouseEvent e) {
str = "released";
draw = true;
x[count][0] = e.getX();
x[count][1] = e.getY();
count++;
//draw();
repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
str = "entered";
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
str = "exited";
repaint();
}
}
have to add MouseListener to the JPanel, because you added MouseListener to the JFrame (this.addMouseListener(this);)
this code line setContentPane(jp); put JPanel to the BorderLayout.CENTER possition to the JFrame, in this case (isn't there any another JComponent added to the JFrame) fills whole / all available space into JFrame
then for mouse event is accesible only JPanel, mouse can't access to the JFrame's RootPane or ContentPane
remove / comment public void paint(Graphics g) and rellated code block move to the paintComponent for the JPanel
See How to Create Translucent and Shaped Windows.