So the intial setup for this issue is that there's a JDialog, and inside that I've placed a JPanel that would house the rest of the components (since painting the JDialog itself is apparently a bad idea). This JPanel has an overriden paintComponent(Graphics g) method that only paints the background and adds a faint border for aesthetic purposes.
Now inside that is a series of JPanels that categorize the contained form components, and each JPanel has an overridden paintComponent(Graphics g) as well, painting a semi-transparent background.
Inside each of those JPanels is where I start to have some issues, presumably with transparency. I have JTextFields, JCheckBoxes, JLabels, JSliders, etc inside these panels, and when you interact with one (hover, click, etc), the background goes from transparent to opaque, with an occassional ghosted image from another field (which appears slightly random sometimes). I'm using a custom LAF called Web, but I tested with other built-in LAFs and the same thing happens.
Is this a glitch with Java or did I mess something up? If so, how can I patch this up? I can paste code fragments later if necessary, but I've used several custom classes and nine-patch style image stitching which may make the code fragments hard to follow. Thanks in advance!
If you are painting components with a transparent background it is very important that the component is marked as transparent (setOpaue(false)) so that the repaint manager knows that it must paint the components below it.
It is also very important that when you are performing custom painting that you call super.paintComponent first.
This is especially important in the case of transparent components, as this prepares the Graphics context for painting.
Graphics is a shared resource. All the components painted in your window will share the same Graphics object, meaning that if you don't allow paintComponent to first prepare it, then you will see what was previously painted on it.
Related
I have been under the impression that a Canvas or a JPanel were necessary to put graphics on a JFrame, however I saw a video earlier in which the person was using paint(graphics g)while extending JFrame and hadn't made a panel or a canvas. If this is a case, why do people bother with making a Canvas or a JPanel?
JFrame extends from Frame, which extends from Window, which extends from Container, extends from Component which defines paint.
If this is a case, why do people bother with making a Canvas or a JPanel?
To answer that question, you need to have a better understanding of JFrame (and window based classes).
Complicated
JFrame is actually a composite component, that is, it's made of a number of other components which provide the core functionality of the window
What this means is, if you override paint and perform custom painting on the frame, it's very possible that you will paint over the child components or the child components will paint over it, and because of the way the paint subsystem works, will do so any time without the frame's paint method been called.
Decorations
Frame's include the window decorations within their available area. This means that the "viewable" area is actually smaller then the defined area of the frame.
This is also why it's recommend to use pack instead of setSize
This means that if you override paint you could actually paint under the window decorations (yes, this happens all the time, and we're tired of answering it)
Screen shot from How can I set in the midst?
The contentPane of JFrame takes care of this, as it's laid out within the viewable area.
Double buffering
Top level containers, like JFrame aren't double buffered, so, even if you overcome all of the above, you will get updates which flicker. Sure you could "devise" you're own double buffering algorithm, but in Swing (ie JPanel), it's free, so why bother
Locked in
As a general recommendation, we generally discourage extending from JFrame (or other top level containers) as it locks you into a single use case and prevents the possibility of re-use.
On the other hand, if you use a JPanel, you can add it to what ever container you want, when ever you want
I am making a game in Java. Basically, I have two different "planes" of updating that I need to take care of the. The base layer is the actual game painting itself. It is simply a JPanel that covers the entire JFrame, and is drawn to using its Graphics object.
I use a fixed timestep to take care of these first graphical updates. I have overwritten the paintComponent() method to do absolutely nothing, as I have written a custom render(float interpolation) method that takes care of that, as to prevent unwanted updates.
However, this panel can take no input beyond primitive mouse clicks and keyboard input. I need the ability to create various menus, text boxes, etc, that are also on the screen. Like various abilities, or even the "Menu" button that usually appears in the upper left corner of most games.
To take care of that input, such as creating buttons, I have a second JPanel that has setOpaque(false) applied to it. Then I create various Swing components that I might need, such as a JButton.
To contain the two JPanels, I use a JLayeredPane, and set their layers appropriately, as seen below. This way the input layer should always be on top of the actual game layer.
The code below shows how I create and add the Swing components to each other. addLoginDialog() is a method that adds a Swing component for the login. It has been tested and works properly, and isn't the problem.
private void initComponents()
{
//This code is inside of the JFrame
wholePane = new JLayeredPane();
add(wholePane);
guiPanel = new GUIPanel();
guiPanel.setOpaque(false);
gamePanel = new RPGPanel();
gamePanel.setOpaque(false);
wholePane.add(gamePanel, JLayeredPane.DEFAULT_LAYER);
wholePane.add(guiPanel, JLayeredPane.POPUP_LAYER);
guiPanel.addLoginDialog();
}
So when I run the code, I get horrible flickering. This is the code that is run from my fixed timestep ~60 times per second.
public void handleRepaint()
{
//I don't use repaint() for the game drawing so I can be sure that fps is controlled.
Graphics g = gamePanel.getGraphics();
gamePanel.render(g);
g.dispose();
wholePane.repaint();
}
The problem is, I think, that the two different systems of updating the screen are clashing. The standard paintComponent() system is great for more static screens, but when I need to update consistently and keep track of the fps, I can't have updates going off randomly.
However, for the input layer, I only want to update as Swing normally does. When the mouse moves over a button, when I component is moved or is resized, etc.
Also, note the way the screen flickers: The Background image goes blank and then comes back again repeatedly. The input panel is always there, but is actually painted behind the game drawing, which shouldn't happen, because it is put in the default layer. The reason I know it isn't completely disappearing is because the game painting is partially transparent, so I can see underneath it, and the buttons I added are still there.
My main question is, how can I stop the flickering? Why is the game drawing being drawn on top of the input components when the game drawing is being done on the Panel that is in a lower layer in the JLayeredPane? And I supposed most importantly, what is causing the flickering? Thank you for any help.
Why is the game drawing being drawn on top of the input components
when the game drawing is being done on the Panel that is in a lower
layer in the JLayeredPane?
Mostly because you've circumvented how Swing works.
Let's start with the fact that the Graphics context is a shared resource (typically there is a single Graphics context per native peer), that is, every component gets the same context, this means, when you use your own painting routine, you are basically painting over every thing else.
The RepaintManager is responsible for making decisions about what and when something should be painted. So what you now have is two artist fighting over the same canvas, wanting to paint on it simultaneously, which is just making a mess.
Add into the fray that Swing's painting process is not thread safe and you end up with a complete mess.
If you absolutely must have control, then you need to remove Swing's painting engine from the equation.
Start by taking a look at Passive vs. Active Rendering
ps- There is also hard ware acceleration benefits to using a BufferStrategy
When I use JCheckboxes or JScrollPane (applied to the main component that holds all others in order to generate a scrollable window) together with components that use
component.setBackground(new Color(R, G, B, A));
to define their background color, I am getting some obnoxious repaint() issues. Hovering over JCheckboxes activates MouseListener and the background of the JCheckbox will suddenly display a random other part of the window. This remains even when taking the mouse off the JCheckbox.
The issue disappears when using
JCheckbox.setRollOverEnabled(false);
BUT will still occur when selecting the checkbox!
The scrollpane will also not properly repaint. ONLY the parts that are outside of the visible frame will be painted several times in a row in direction of scrolling when they come back into the frame. It looks similar to that error on Windows OS when a program crashes and you can "draw" with the window on the screen because it "generates" a new window every time you move it (http://i.stack.imgur.com/L5G5Q.png).
The most interesting part is that the issue completely disappears when I use
Color.grey (or any other pre-generated color)
It also disappears when not selecting a custom background color at all.
So is there an issue with revalidate() and repaint() hidden anywhere in this? Is the use of RGBA a problem, specifically the A (= opacity) part since Color.AnyColor works?
Is the use of RGBA a problem, specifically the A (= opacity) part
Yes, Swing does not support transparent backgrounds.
Swing expects a component to be either:
opaque - which implies the component will repaint the entire background with an opaque color first before doing custom painting, or
fully transparent - in which case Swing will first paint the background of the first opaque parent component before doing custom painting.
The setOpaque(...) method is used to control the opaque property of a component.
In either case this makes sure any painting artifacts are removed and custom painting can be done properly.
If you want to use tranparency, then you need to do custom painting yourself to make sure the background is cleared.
The custom painting for the panel would be:
JPanel panel = new JPanel()
{
protected void paintComponent(Graphics g)
{
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
panel.setOpaque(false); // background of parent will be painted first
Similar code would be required for every component that uses transparency.
Or, you can check out Background With Transparency for custom class that can be used on any component that will do the above work for you.
I need to layer JPanels but I don't know how. I have 3 panels, the first is for the background, the second is for a Character/Sprite to move around and layers the first panel(background, and the third is a bar off to the side (Used for buttons and has nothing to do with they layers). How do I layer panel 1 and panel 2?
edit: The background is made up of a grid of 25x25 labels with an icon in each.
Some options:
Use a JLayeredPane which can layer components using a z-order Integer constant. Remember that when doing this, you are also essentially using a null layout, and so you will be fully responsible for setting the size and position of all components added to the JLayeredPane.
If all the background is doing is painting an image, you could use a single JPanel, and then simply paint the image as a BufferedImage that is displayed in the JPanel's paintComponent method. The sprite would also be painted but its location would vary.
See How to Use Layered Panes.
Don't forget to use:
panel.setOpaque(false);
Or you don't need to layer panels. You can just paint a background image on the panel. See Background Panel for an example of this.
We just recently worked on a top-down video game for my CSC class. All we did was draw the background and then all the sprites after it in the paint() method on the JPanel. We also used a Timer and an ActionListener to constantly update the JPanel.
I've just started coding video games and I've heard that doing all your drawing on a JPanel and attaching that panel onto a JFrame is better than simply drawing onto the JFrame. I was just wondering why is this better?
It is better for various reasons, including:
In most Swing components, custom painting is achieved by overriding the paintComponent(Graphics) method. Top-level Swing containers (e.g. JFrame, JApplet, JWindow) have only paint(Graphics). As a result of the common method for painting, people who answer often forget about this difference between common and top-level components, and therefore suggest silly advice. ;)
A JComponent can be added to a JFrame, or a JApplet, or a JDialog, or a constraint of a layout in a JPanel, or a JInternalFrame, or a.. Just when you think your GUI is complete, the client says "Hey, wouldn't it be great to throw in a tool-bar & offer it as an applet as well?" The JComponent approach adapts easily to that.
As explained (complete with code!) by Richante, it is easier to calculate the co-ordinates required for painting the custom component, and if it has a preferred size, to size the JFrame to be 'exactly the right size' to contain the GUI (using pack()). That is especially the case when other components are added as well.
Now, two minor disagreements with the advice offered.
If the entire component is custom painted, it might be better to simply put a BufferedImage inside an ImageIcon/JLabel combo. Here is an example of painting to an image. When it comes time to update it:
Call getGraphics() for a Graphics or createGraphics() for a Graphics2D
Draw the custom painting to that graphics instance
Dispose of the graphics instance
Call repaint() on the label.
It is an easy way to do Double Buffering.
Let me elaborate a bit. In video games, to avoid the flicker caused by redrawing and display smoother graphics, people usually use double buffering. They create an offscreen surface, draw everything on that and then display the entire off-screen surface on the screen in one go.
In Java2D and Swing, the easiest way to do this, is to simply do your game sprite drawing on a JPanel, and then add the JPanel to a JFrame.
Secondly, by drawing things on a JPanel, you allow more GUI widgets and other graphical objects to be displayed on the JFrame without having to paint them manually in the game loop. For example buttons, menus, other panels, even other rendering JPanels.
Thirdly, it allows you to use automatically translated co-ordinates for your game. You can draw everything from the top-left to the bottom-right without having to worry about the window manager specific things like window border-widths, task panes, titles etc.!
Moreover, this is not just a convention only used by Game Programmers in Java. Creating a separate Game Board, Render Panel or Graphics Widget is quite popular when programming games using a library with an internal mainloop such as a GUI Toolkit. You can use a User Form in Windows Forms and a Drawing Board in GTK+.
The JFrame includes things like the menu, title bar and border. Therefore, when you refer to coordinates you have to account for these. You might also decide to add a menu bar, or some other components, to the frame. If your painting is all in a JPanel, then this won't change how you need to refer to coordinates.
For example, try:
public class Test extends JFrame {
public Test() {
super();
setVisible(true);
setBounds(100, 100, 200, 100);
}
#Override
public void paint(Graphics g) {
g.fillRect(0, 0, 50, 50);
}
public static void main(String[] args) {
new Test();
}
}
and you will see that the black square is not square! Because (0, 0) is the top left corner of the entire frame, not the corner of the visible area.