Drawing in JLabel - java

i have a problem with drawing in my JFrame app. I have these two functions:
Im quite new to such graphics in Java, i was wondering if someone would be kind and help me. I need to add the line on the JLabel called areaImage. I tried using some done code i found here but none worked for me. Is my code usable with some bugs? Or is it completely bad?
Please dont just post a link with some code, Im not skilled enough to understand it and then change it so it fits my app...
This one just makes the window, adds the components:
public void game (int difficulty)
{
getContentPane().removeAll();
areaImage = new JLabel ();
areaImage.setBounds (50,100,650,500);
areaImage.setForeground(Color.WHITE);
areaImage.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
add(areaImage);
paint (100,120,500,500, null);
info = new JLabel (" Write your answer into the text field");
info.setBounds(730,180,250,50);
info.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
info.setFont(new Font ("Arial", Font.PLAIN, 15));
areaImage.setForeground(Color.red);
add(info);
inputField = new JTextField("");
inputField.setBounds(810, 240, 80, 50);
add(inputField);
checkAnswer = new JButton ("Check");
checkAnswer.setBounds(750, 330, 200, 50);
checkAnswer.setContentAreaFilled(false);
checkAnswer.setOpaque(false);
checkAnswer.addActionListener(this);
checkAnswer.setFont (new Font("Arial",Font.PLAIN, 30));
add(checkAnswer);
next = new JButton ("Next");
next.setBounds(750,440,200,50);
next.setContentAreaFilled(false);
next.setOpaque(false);
next.addActionListener(this);
next.setFont (new Font("Arial",Font.PLAIN, 30));
add(next);
end= new JButton ("Exit");
end.setBounds (750,550,200,50);
end.setFont(new Font("Arial", Font.PLAIN, 30));
end.addActionListener(this);
end.setOpaque(false);
end.setContentAreaFilled(false);
add(end);
revalidate();
repaint();
}
This one is the drawing function:
private void paint (int x, int xx, int y, int yy, Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g.drawLine(x,y,xx,yy);
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
}

Please dont just post a link with some code, Im not skilled enough to understand it
Well that is how you learn. You can't expect us to debug your code and rewrite it every time you have a little problem. If you are not willing to learn by playing with working examples, then I'm not sure how we can help you.
I need to add the line on the JLabel
Then you need to override the painting code for the JLabel. You should never invoke a painting method directly because the painting will be lost the next time Swing determines the component needs to be repainted.
So start by learning how to do painting properly. There is a working example in the Swing tutorial on Custom Painting. The first example just draws a string on a panel but it will be easy enough for you do just draw a line on the label. It is a single statement you add to the paintComponent() method.
The real question is why are you trying to draw this line on a label? I'm sure there is a better solution if we understand the real requirement. You should not be hardcoding the location/size of the line since you don't know how big the label will be.

Related

How to display an image in an JFrame? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner and am trying to program a small game. Unfortunately, I am currently failing to insert an image file on the JFrame.
I got this version from the internet, but unfortunately nothing is displayed when I run it.
import java.awt.*;
import javax.swing.*;
public class Draw extends JLabel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D Graphic1 = (Graphics2D) g;
Graphic1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(new Color(0, 191, 255)); // farbe hintergrund einstellen
g.fillRect(0, 0, Var.Framebreite, Var.Framehöhe);
g.setColor(Color.yellow);
Font currentFont = g.getFont(); // schriftgröße von Leben bestimmen
Font newFont = currentFont.deriveFont(currentFont.getSize() * 8F);
g.setFont(newFont);
double b = Math.round(0.125 * Var.Framebreite);
int h = (int) b;
g.drawString("" + Var.LebenSpieler1, Var.Framebreite / 2 - h - 100, 90); // Leben anzeige spieler
// !muss "" + variable geschriebeen
// werden
g.drawString("" + Var.LebenSpieler2, Var.Framebreite / 2 + h, 90); // Lebven anzeigen gegnerspieler
ImageIcon icon = new ImageIcon("C:\\Users\\justi\\OneDrive\\Desktop\\OnlineSchule\\Englisch\\Test.PNG");
JLabel l1 = new JLabel(icon);
JPanel feld = new JPanel();
feld.add(l1);
feld.setBounds(30, 30, 110, 110);
repaint();
}
}
Do not create components in a painting method. A painting method is used to do painting with a Graphics object.
Do not invoke repaint() in a painting method. This will cause a loop. If you need animation use a Swing Timer.
Do not do I/O in a painting method. The method will be called frequently and you want the painting to be efficient.
Read the section from the Swing tutorial on Custom Painting for examples of how to do painting. Download the working code and modify it for your requirments.
To paint an image you use the drawImage(...) method of the Graphics object.
You would read the image in your constructor and keep an instance variable to reference the image.

Java Swing Graphics2d rotation jumping

I'm writing a simple game for studying purposes. Everything goes fine except one little thing...
I cant figure out how to rotate square without this ugly jumping
here a simplified version of my program illustrating an issue, here i use one timer, but in original program i have 2 timers one for handle game state and second for repaint:
public class soQuestion extends JLabel {
double r;
#Override
public void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.clearRect(0,0, getWidth(), getHeight());
g.translate(getWidth()/2, getHeight()/2);
g.rotate(r);
g.translate(-20, -20);
g.fillRect(0, 0, 40, 40);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
soQuestion question = new soQuestion();
frame.add(question);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new javax.swing.Timer(10, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
r += 0.005;
question.repaint();
}
}).start();
}
}
jumping is more visible if rotation delta values is small, for fast rotated objects is less visible..
all rendering hints i used has no effect
PS: Sorry for my english
PPS: i can provide more details if needed, how it looks in full version:
Thanks for all participants!
It is fully my mistake and inattention. I was copied this code section from some source :
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
And before ask a question here i couldn't saw that i used hint related to text rendering.
Special thanks to mr #Pshemo for suggesting of using this rendering hint:
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
I was know about it before asking, but i'm a human and could not figure out where a mistake for an a hour and asked.
PS: sorry for my english
I'm a new contributor, so if its not the best help, sry but i am trying :)
have you tried a solution where you are using Math.toRadiants() in your g.rotate() function? in this video: Java: Rotating and scaling images
the image rotates without jumping, it's at 6:42 in the video.
So in your solution, it would look like that: g.rotate(Math.toRadiants(r += 0.005));

Using drawLine Function in Other Function

I'm creating a game where I need to draw some lines and dots. I have a general function called paintDot (check code below) and I want to call it in a different function. I don't know how to call it, any help?
public void paintDot (Graphics g, int x, int y)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(x,y,15,15);
}
This is the other function/method where I need to call the drawing function:
ATM the coordinates are just hardcoded so I know it's working correctly.
As you can see, I'm calling the paintDot method with bad arguements. Don't know what argument should be placed at Graphics g
private void gameWindow (int dif)
{
this.removeAll();
areaImage = new JPanel ();
//distance between points = 75
//point grid = 7*6
areaImage.setBounds(50,50,675,600);
areaImage.setBackground(Color.WHITE);
areaImage.setBorder(BorderFactory.createLineBorder(Color.black));
add(areaImage);
answer = new JTextField();
answer.setBounds(835,200,150,50);
answer.setBorder(BorderFactory.createLineBorder(Color.black));
answer.setHorizontalAlignment(JTextField.CENTER);
answer.setFont(new Font("Verdana", Font.BOLD, 20));
add(answer);
info= new JLabel ("Write your answer here:");
info.setBounds(830,155,250,50);
info.setFont(new Font("Verdana", Font.BOLD, 12));
add(info);
checkAnswer = new JButton ("Check Answer");
checkAnswer.setBounds(835,310,150,50);
checkAnswer.addActionListener(this);
add(checkAnswer);
next = new JButton ("Next");
next.setBounds(835,410,150,50);
next.addActionListener(this);
add(next);
end = new JButton ("End Game");
end.setBounds(835,510,150,50);
end.addActionListener(this);
add(end);
revalidate();
repaint();
int x = 75,y=75;
for(int num=0;num<6;num++)
{
for(int xx=0; x<7;xx++)
{
paintDot (areaImage,x,y); // here is the problem
x=x*2;
}
y=y*2;
}
}
I have a general function called paintDot (check code below) and I want to call it in a different function
You can't.
Painting can only be done in the paintComponent() method.
You should NEVER be invoking paintComponent() directly.
All painting code MUST be in the paintComponent() method.
If you want to paint 7 dots. Then that painting code MUST be in the paintComponent() method which means the looping code would be in the paintComponent() method and then you invoke the paintDot(...) method from withing the loop. The painting of the dots must be done EVERY time Swing determines the component needs to be repainted.
You have asked several questions on this topic and the answer is always the same. Read the tutorial link you have been given and follow the examples. The tutorial draws a square, but the concept would be similar for drawing 7 dots.
So once again, read the tutorial, download the code and play with the working example. Start by changing the tutorial code to draw 7 dots. Once you understand how that works, then you add the logic to your real code.
The tutorial link is give to you for a reason. If there is something you don't understand in the tutorial, then ask a question, but don't post code that looks nothing like the example from the tutorial and wonder why it doesn't work!
You have this for:
for(int xx=0; x<7;xx++)
where you have an index called xx and you try to do a cycle. The problem is that you test for x < 7 instead of xx < 7 and since x is greater than 7, you will never get into the for.
You could extend JPanel and overwrite the drawing functions, such as the paintComponent(Graphics g) (Thanks camickr) or paintAll(Graphics g) (I believe) method.
You might also want to add a JLabel with a BufferedImage using createGraphics()
Please note if you are trying to make a full-fledged game, you would need a game loop and other stuff, which is NOT fun without a library.
This is not an attempt in shameless self-promotion, it's a suggestion.
IF you need a game loop, canvases, multiple screens and stuff,
a library could be the way to go.
I made the library j2D to make 2D games.

JPanel how to add a ToolTipText

I have a little problem, I need to add a ToolTipText to JPanel. How should I do this?
I want to have a tooltip when I have mouse over the circle.
This is part of my code.
JPanel component1 = new JPanel();
JPanel component11 = new JPanel();
okno.add(component1,"align left,cell 0 0, h 75!, grow,wrap");
component1.setLayout(new MigLayout("","[][grow][grow]", "[grow]"));
component1.add((okno.add(creLab("Kraj", i, czcionka, etykietki))),"left align, cell 0 0");
component1.add(t1,"cell 1 0,grow");
//component1.add(new circle1(),"right align, cell 2 0,h 50!, w 53!, gapleft 50, wrap");
component1.add(component11," right align, cell 2 0, h 30!, gapleft 300, wrap");
component11.setLayout(new MigLayout("","[]","[]"));
component11.add(new circle1(),"cell 0 0,h 50!, w 50!, dock north");
component11.setToolTipText("<html>W polu obok wpisz kraj pochodzenia towaru</html>");
I add also code of circle1:
class circle1 extends Applet{
public void paint(Graphics g){
setForeground(Color.yellow);
g.drawOval(0, 0, 50, 50);
g.fillOval(0, 0, 50, 50);
g.setColor(Color.black);
g.drawString("Jak", 14, 14);
g.drawString("wpisac", 3, 28);
g.setColor(Color.red);
g.drawString("kraj?", 14, 42);
//g.drawString(arg0, arg1, arg2)
}
}
Take a look at JComponent#getToolTipText(MouseEvent)
This will allow you to determine what text to return based on the location of the mouse.
It's difficult to determine for your code snippet, exactly where the circle is been drawen, but I would avoid drawing directly to the surface of the applet, but instead use a custom component (like a JPanel) instead (overriding its paintComponent method). This I would then either add to the applet or to the control panel.
This way your going to avoid issues with the mouse events been consumed
I would also take a look at Ellipse2D, which can be used to determine if the ellipse contains a given point
The first thing is to identify when the mouse is inside the circle. To do that you could verify the mouse position on a mouseMotionlister according to the circle area
http://www.java2s.com/Code/JavaAPI/javax.swing/JPaneladdMouseMotionListenerMouseMotionListenerlis.htm
Once you identify this situation you could proceed to change the tooltip
See Playing With Shapes. You can create a JLabel with a ShapeIcon. Then you just use the setToolTipText() method of the JLabel. You can then add the label to the panel like any other component.
Now that you can use a component to represent a Shape there is no need to do custom painting. Just create a panel add add components to the panel. You can also create JLabels for all your text strings.
Don't do custom painting, unless you have a good reason to do so.

Center a button or image

I'm using Eclipse to create an app for Android. I know you set attributes such as centering a button or image in the XML file but How would you do this in Java?
Its hard to say without knowing what you have. However, if you look through the docs, every xml attribute has a related method in Java. For example, Look at the View Docs and you can see a list of attributes with its corresponding Java method and a description of what it actually does. You should be able to use this to get you started then you can ask a question with code you have tried, precise problem you are having, and any error messages you might be getting. Good luck!
Use code to center your stuff, not attributes in an XML file.
Center a button:
Use a FlowLayout. This will keep the button centered horizontally in the container, but not vertically.
JButton button = new JButton("Click Me!");
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.add(button);
If you want it centered in both directions, you could use BoxLayout.
JButton button = new JButton("Click Me!");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(Box.createVerticalGlue());
panel.add(button);
panel.add(Box.createVerticalGlue());
Center image:
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int xCenter = (this.getWidth() - image.getWidth()) / 2;
int yCenter = (this.getHeight() - image.getHeight()) / 2;
g2d.drawImage(image, xCenter, yCenter, null);
}
Have you tried :
Button button = new Button(getApplicationContext());
button.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
button.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);

Categories