I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:
public void drawStartScreen(){
startScreenOn = true;
Graphics2D b = buffer.createGraphics();
b.setColor( Color.WHITE );
b.fillRect(0, 0, 800, 600);
b.drawImage(start,0,0,null);
setLayout( null );
button = new JButton("Start Game");
button.setBounds(10,10,100,100);
button.setVisible( true );
add(button);
}
It draws the image first, and then the Button, but the button still draws behind the image.
You are mixing painting and adding of components and you definitely shouldn't be doing this. Instead add components when you create the screen or when you first need them but make sure you are only doing this once. Then separate modify the components that need painting changes inside the paintComponent() method.
I recommend you'd use a JLayeredPane (I go for custom painting only as a last resort).
If you're still interested in mixing the 'low-level' painting with 'higher-level' JComponent hierarchy, look at a question about a JFrame that has multiple layers.
Override the paint method on the JFrame:
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D b = (Graphics2D)g;
b.setColor( Color.WHITE );
b.fillRect(0, 0, 800, 600);
b.drawImage(start.getImage(),0,0,null);
b.dispose();
}
Notice that this calls paint() on the parent and dispose() on the graphics context when done. I just tried this code and it worked for me.
Related
I'm making a game and I want to add a JTextField to a JPanel that has Paint Component. I repaint the JPanel every 16 milliseconds.
I add() the textfield to the panel but it show up only for a single frame when i click on it.
Then I tried to repaint() the textfield but now it is flashing.
public class Screen extends JPanel {
public Screen() {
JTextField txt = new JTextField();
txt.setBounds(10, 10, 300, 50);
this.add(txt);
}
#Override
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(Color.BLACK);
g2D.fillRect(0, 0, this.getWidth(), this.getHeight());
g2D.setColor(Color.WHITE);
g2D.fillRect(0, 0, this.getWidth(), 20);
txt.repaint();
}
}
I want to show the textfield on the top of the panel
JTextField txt = new JTextField();
When you create a JTextField you should use code like:
JTextField txt = new JTextField(10);
Now the text field can calculate its own preferred size.
//txt.setBounds(10, 10, 300, 50);
Don't use setBounds() to give a component a size. Again each Swing component is responsible for determining its own preferred size. Then the layout manager will set the size/location of the component on the panel.
//public void paint(Graphics g) {
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// add custom painting here
}
Don't override paint(). Custom painting is done by overriding the paintComponent() method. And the first statement in the method should be super.paintComopnent(g)
//g2D.setColor(Color.BLACK);
//g2D.fillRect(0, 0, this.getWidth(), this.getHeight());
Don't paint the background of the panel. That is the job of the panel and that is why you need to super.paintComponent(), to make sure the background is painted.
Then in the constructor of your JPanel class you simply use setBackground( Color.BLACK )
//txt.repaint();
Don't ever invoke repaint() on any component in a painting method.
Read the section from the Swing tutorial on Custom Painting for working examples to get you started. Use the demo code as the starting point for you program. Then you simply add a JTextField to the panel, so it will be a single line of code that is needed to display the text field.
It seems like you want to have a JTextField on a black panel. You don't need to set the colour of the panel every time in paint() method. Instead add this to the constructor:
public Screen() {
setOpaque(true);
setBackground(Color.BLACK);
//...
}
and remove paint() method.
Also, if you want to use absolute positioning with setBounds() method then you should set the layout to null setLayout(null) in constructor. If you use absolute positioning you will also need to specify the size of the panel explicitly. However, I would still suggest you use a layout manager that takes care of panel sizing as well.
See this post for more information about absolute positioning.
I have a JSlider in a JPanel that return me a value of R-G-B .
I create it, in the Costructor of JPanel. I draw in same Panel (using paintComponent) a little circle, and I change his color using the Slider. I want that the color change in contemporany of slider shift.
So, i use the method repaint.. Next to Panel there is another Panel, with two button.. If I use method repaint in first panel , the buttons of second panel duplicated in the topLeft of First Panel. Why? Thank's you.
First Panel:
public class OptionsPanel extends JPanel {
static JSlider RBG = new JSlider(0,255);
OptionsPanel(){
this.setVisible(false);
this.setSize(350,1000);
this.setLayout(null);
this.setBackground(new Color(200,200,0));
Main.f1.add(this);
RBG.setVisible(true);
RBG.setSize(255,50);
RBG.setLocation(30,240);
this.add(RBG);
LotL lotl = new LotL();
Button save = new Button("Save");
save.setVisible(true);
save.setSize(100,40);
save.setLayout(null);
save.setLocation(60,300);
save.addActionListener(lotl);
save.setBackground(Color.yellow);
save.identificatore=3;
this.add(save);
}
boolean draw=false;
#Override
public void paintComponent(Graphics g){
g.drawOval(50,100,70,70);
g.setColor(new Color(RBG.getValue(),180,200));
g.fillOval(50,100,70,70);
repaint();
}
}
Second Panel:
public class FirstPanel extends JPanel{
FirstPanel(){
this.setVisible(true);
this.setSize(1000,1000);
this.setLayout(null);
this.setBackground(new Color(255,200,180));
Main.f1.add(this);
Button start = new Button("Start Game!");
Button options = new Button("Options");
LotL LotL = new LotL();
start.setVisible(true);
start.setSize(200,80);
start.setLayout(null);
start.setLocation(400,450);
start.addActionListener(LotL);
start.setBackground(Color.green);
start.identificatore=1;
this.add(start);
options.setVisible(true);
options.setSize(200,70);
options.setLayout(null);
options.setLocation(400,550);
options.addActionListener(LotL);
options.setBackground(Color.green);
options.identificatore=2;
this.add(options);
}
}
You've broken the paint chain...
#Override
public void paintComponent(Graphics g){
g.drawOval(50,100,70,70);
g.setColor(new Color(RBG.getValue(),180,200));
g.fillOval(50,100,70,70);
repaint();
}
Graphics is a shared resource, which gets passed to ALL the components that are painted during a given paint cycle.
One of the jobs of paintComponent is to prepare the Graphics context for painting, but filling with the components background color.
You MUST call super.paintComponent before performing any custom painting.
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawOval(50,100,70,70);
g.setColor(new Color(RBG.getValue(),180,200));
g.fillOval(50,100,70,70);
}
Also, there is never any need for paintComponent to be public, no one should ever be calling directly and NEVER modify the state of a component from within any paint method which may trigger a repaint, you will get yourself into a infinite loop which will eventually consume your CPU and make you computer unusable.
Take a look at Painting in AWT and Swing and Performing Custom Painting for more details
You should also avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
I try to draw a .PNG Image using graphic2D.drawImage() method.
And I make it right, but I've one JPanel on my Frame, and when I draw my image, it appears in background. I want it to appear on the foreground, and obviously in front of my JPanel.
Use JLayer. (http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html)
Override the paint method on the LayerUI set to the JLayer and draw your .PNG image there. Add your JPanel to the JLayer.
You should add one more JPanel and draw image in its paintComponent method like that.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (yourImage != null)
g.drawImage(yourImage, 0, 0, this);
}
and than you can hide other JPanel and show this JPanel with setVisible() function.
I created a new JApplet form in NetBeans:
public class UI extends javax.swing.JApplet {
//generated code...
}
And a JPanel in design mode named panou:
// Variables declaration - do not modify
private javax.swing.JPanel panou;
How do I get to draw a line on panou? I've been searching for this for 5 hours now so a code snippet and where to place it would be great. Using Graphics2D preferably.
Go to design mode
Right Click on the panel "panou"
Click "Costumize code"
In the dialog select in the first combobox "costum creation"
add after = new javax.swing.JPanel() this, so you see this:
panou = new javax.swing.JPanel(){
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g); // Do the original draw
g.drawLine(10, 10, 60, 60); // Write here your coordinates
}
};
Make sure you import java.awt.Graphics.
The line that you will see is always one pixel thick. You can make it more "line" by doing the following:
Create this method:
public static final void setAntiAliasing(Graphics g, boolean yesno)
{
Object obj = yesno ? RenderingHints.VALUE_ANTIALIAS_ON
: RenderingHints.VALUE_ANTIALIAS_OFF;
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, obj);
}
And add after super.paintComponent(g); (in your costum creation) this:
setAntiAlias(g, true);
Edit:
What you are doing wrong is: you paint the line once (by creating the frame).
When you paint the line the frame is also invisible. The first draw is happening when the frame becomes visible. The frame will be Repainted, so everything from the previous paint will disappear.
Always you resize the frame, everything will be repainted. So you have to make sure each time the panel is painted, the line also is painted.
To do custom painting in a JPanel, one would need to make a subclass of a JPanel, and then overload the paintComponent method:
class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
// Perform custom painting here.
}
}
In the example above, the MyPanel class is a subclass of JPanel, which will perform whatever custom painting is written in the paintComponent method.
For more information on how to do custom painting in Swing components, Lesson: Performing Custom Painting from The Java Tutorials have some examples.
If one wants to do painting with Java2D (i.e. using Graphics2D) then one could do some painting on a BufferedImage first, then draw the contents of the BufferedImage onto the JPanel:
class MyPanel extends JPanel {
BufferedImage image;
public MyPanel() {
Graphics2D g = image.createGraphics();
// Do Java2D painting onto the BufferedImage.
}
public void paintComponent(Graphics g) {
// Draw the contents of the BufferedImage onto the panel.
g.drawImage(image, 0, 0, null);
}
}
Further reading:
Painting in AWT and Swing
Trail: 2D Graphics
I'm having a problem adding a JPanel on top of an Image. This is what I'm trying to do:
Image bgImage = loadImage(filename);
JPanel jp = new JPanel();
jp.setBounds(100,100,100,100);
jp.setOpaque(true);
jp.setBackgroudColor(Color.red);
bgImage.add(jp);
After doing this, I only see the bgImage. I tried everything but I still can't show the panel. Can somebody help me?
You cannot place a component inside an Image. What you want to do is paint the Image onto the background of a swing component (like JPanel). All swing components have a paint() method that calls these three methods (perhaps not quite this order): paintComponent(), paintChildren(), paintBorder(). So, you want to override the paintComponent() method to paint your background image over the panel. When this runs, your custom method will be called, and then the paintChildren() method will be called, which will paint all "child" components over the top of your background image:
class BackgroundImagePanel extends JPanel {
public void setBackgroundImage(Image backgroundImage) {
this.backgroundImage = backgroundImage;
}
#Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.drawImage(backgroundImage, 0, 0, this);
}
private Image backgroundImage;
}
BackgroundImagePanel panel = new BackgroundImagePanel();
panel.setBackgroundImage(image);
panel.add(new JTextField("Enter text here..."));
panel.add(new JButton("Press Me"));
The "BackgroundImagePanel" solution paints the image at its actual size. If this is a requirement, then you can just use a JLabel instead of creating a custom component.
The BackgroundPanel entry shows how you can do this. It also provides a background panel with more custom image painting solutions, that will allow you to scale and tile the image, if this is part of your requirement.