Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm very new to programming. I just started today and am following a book called learning java by Patrick Neimeyer and Daniel Leuck.
It started by asking me to create the Hello World ! programme, and did this by placing it in a JFrame which was all done in one class, it is now asking me two create another class in which will use a JComponent. I've tried creating another class and have just ended up going around in circles with errors.
This is my previous attempt. Can someone explain please what I'm meant to do?! I know it is fairly basic, but I am struggling.
It's telling me that the new code for the class is:
import java.awt.*;
class HelloComponent extends JComponent {
public void paintComponent( Graphics g ) {
g.drawString( "Hello, Java!", 125, 95 );
}
}
Where do I add this?
This is a rather perplexing way to start programming in Java. Even so, in this instance why would you not use a JLabel rather than creating your own JComponent?
In any case, as some of the comments already said, you need to add your JComponent to a JFrame.
An example below:
Example JFrame class
This class extends JFrame rather than creating and using a JFrame object. It also includes the main method as well, just to avoid another class. The main method runs the GUI on the event dispatch thread. This part is important, but not so much for a beginner.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ExampleFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ExampleFrame frame = new ExampleFrame();
frame.createAndShow();
}
});
}
public void createAndShow() {
getContentPane().add(new HelloComponent());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Example");
pack();
setVisible(true);
}
}
HelloComponent
As before with your version, but sets the preferred size so that when the JFrame is 'packed' it sizes to the component. Additionally, I've used the Graphic font height metric to position the y-coordinate, since the drawString method places the y coordinate at the bottom left.
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
public class HelloComponent extends JComponent {
private final int COMPONENT_WIDTH = 100;
private final int COMPONENT_HEIGHT = 30;
public HelloComponent() {
setPreferredSize(new Dimension(COMPONENT_WIDTH, COMPONENT_HEIGHT));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello World", 0, g.getFontMetrics().getHeight());
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a probably annoying request. Could someone demonstrate how to use one of these static Java swing utility methods? I am looking for a simple, extremely simple, example.
public static void paintComponent(java.awt.Graphics, java.awt.Component, java.
awt.Container, int, int, int, int);
public static void paintComponent(java.awt.Graphics, java.awt.Component, java.
awt.Container, java.awt.Rectangle);
These static Java swing methods are found in the javax.swing.SwingUtilities package.
Thank-you for reading this and any help given.
you can find some usages of most public api methods from grepcode. and here is yours.
EDIT
a running example may be like this
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater( () -> {
JFrame frame = new JFrame();
JPanel panel = new JPanel() {
JLabel label = new JLabel("<html>SwingUtilities.paintComponent method usage example");
{
label.setBorder(new LineBorder(Color.red));
}
protected void paintComponent(Graphics g) {
// render label which is not part of component hierarchy
// and paint it on this panel at location (10,10) with dimension (200,50)
SwingUtilities.paintComponent(g, label, this, 10, 10, 200, 50);
}
};
frame.setContentPane(panel);
frame.setSize(300, 200);
frame.setVisible(true);
});
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I have stucked to 4 lines of code.
They supposed to let me create my own widget.
But it seems that the main method is missing.
I have tried to write a main class on my-own and create an object in paintComponent() method with no luck.
I know that i am not supposed to call the method myself, but when i run the program i get the error Main method not found in class....
Can someone please explain me how this works or give me a link to read?
Here is the simple code that I tried:
import javax.swing.*;
import java.awt.*;
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
Try this simple code, it should be helpful to you:
import javax.swing.*;
import java.awt.*;
public class MyDrawPanel extends JPanel {
private static final int WIDE = 300;
private static final int HIGH = 200;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
public MyDrawPanel() {
setBackground(Color.white);
// Set a initial size for the program window
this.setPreferredSize(new Dimension(WIDE, HIGH));
}
private void display() {
// Some statements to let the JFrame appear in a good way
JFrame f = new JFrame("MyDrawPanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
// Main method is called when the program is runned
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MyDrawPanel().display();
}
});
}
}
Output:
If you are new to java, I would suggest to just give 4-5 days on Tutorials | Javatpoint.
Java rule is that the java file name should match the class name containing main method.
So a simple code of main method:
class Simple {
public static void main(String args[]) {
System.out.println("Hello Java");
}
}
In this case this code should be in Simple.java file.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm new in Java and currently my level is around printing text. Even though, I wanted to start with graphical content but sadly I didn't be able to do it.
I began with JFrame and everything went well but when I had to print images I had problem. Thanks to YouTube I could copy this piece of code where shows clearly (not enough for me, though) how to print an image in a JFrame.
import java.awt.Graphics;
import javax.swing.*;
public class Main extends JPanel{
public static void main(String[] args){
JFrame j = new JFrame("Image");
j.setSize(1080,720);
j.setVisible(true);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.add(new Main());
}
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("C:\\Users\\Hello\\Pictures\\picture.jpg");
i.paintIcon(this, g, 0, 0);
}
}
I honestly don't understand that. I looked for explanations on internet but no answer has really helped me out. What I don't comprehend is basically j.add(new Main()) (are we linking the same class?) and paintComponent(Graphics g)...
I don't think I've seen so many errors in a supposed teaching example.
Here's the rewritten code. You have to put the image in the same directory as the Java code to read the image.
package com.ggl.testing;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawImage implements Runnable {
#Override
public void run() {
JFrame j = new JFrame("Image");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.add(new ImagePanel(getImage()));
j.pack();
j.setLocationByPlatform(true);
j.setVisible(true);
}
private Image getImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new DrawImage());
}
public class ImagePanel extends JPanel {
private static final long serialVersionUID = -2668799915861031723L;
private Image image;
public ImagePanel(Image image) {
this.image = image;
this.setPreferredSize(new Dimension(image.getWidth(null), image
.getHeight(null)));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
}
Here are the important concepts to take from this code.
Always start a Java Swing application with a call to the SwingUtilities invokeLater method. This puts the creation and updates of the Swing components on the Event Dispatch thread (EDT).
As others have mentioned, read the images before you try and display them. This code will abend if the image is missing. This code will also work when you package your Java class in a JAR file, along with the image.
You don't set any sizes. You let the JFrame and JPanels calculate their own sizes using Swing layouts. In this particular example, the JPanel takes on the size of the image you read, and the JFrame is just large enough to hold the image JPanel.
You use Swing components. You only extend a Swing component when you want to override a method in the class. In this example, we used a JFrame and extended a JPanel.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
say at first rectangle and then a line for example
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Canvas;
import javax.swing.JComponent;
import javax.swing.JFrame;
//class MyCanvas extends JComponent {
class MyCanvas extends Canvas {
public void paint(Graphics g) {
g.fillRect(20, 20, 500, 500);
}
}
class Linie extends MyCanvas {
public void paint(Graphics g) {
g.setColor(new Color(0, 255, 0));
g.drawLine(30, 40, 300, 100);
}
}
public class LinieUndRec {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(100, 100, 800, 800);
window.getContentPane().add(new MyCanvas());
window.getContentPane().add(new Linie());
window.setVisible(true);
}
}
this code draws only a line
how to draw a rectangle and a line
In your implementation of the Linie class, you're providing code for the paint method. This replaces the code of the paint method on the MyCanvas class, because Linie extends MyCanvas.
So, when you call paint() on an instance of Linie only the code in the Linie.paint() method is run, not both. If you want it to run both, add do this:
class Linie extends MyCanvas {
public void paint(Graphics g) {
super.paint(g); // This will draw the rectangle from the parent class,
// then render the line below
g.setColor(new Color(0,255,0));
g.drawLine(30,40, 300, 100);
}
}
As a side note, even though the code above should work, type inheritance isn't meant to solve this kind of problem. I'm just trying to provide an answer to the code as provided.
If you really want to draw a rectangle followed by a line, then call .paint() on an object that represents a rectangle, then call .paint() on an object that represents a line, one after the other. What you have here is...well, really bad code (that's okay if you're new to Java - we were all new once). You're using inheritance to accomplish what would be done by just calling two .paint() commands after each other.
Also as #Durandal points out, you can use a single canvas to do all drawings. You don't need one canvas per drawing operation. Think of a Canvas as a surface you can draw on, like a piece of paper or, well, like a painter's canvas. And think of the drawing operations as instructions of what to do in order to construct a painting. Generally speaking, you must draw things in the background first, followed by things in the foreground. The result is that drawing that happens first is covered up by drawing that happens later.
i make simple game , and it consist of 2 files , first file is "Alibaba.java" which is extended from JFrame , i used it to display general contents of the game !,
and the second file is "intro.java" which is extended from JPanel , i used it to show intro of the game which include (title & background & person) ,
my problem occured when i tried to add a simple button in the intro ! , i did a function to create the button , but the problem is when i run the game , the button which i added it don't appear !! , but when i tried add it from the first file which extended from JFrame , its appeared ! ,
so what is the problem in my code ? is JPanel don't accept JButtons ! or i must create the buttons from the JFrame file ?!
so i need to know how to add Jbutton inside Jpanel instead of add Jbutton in JFrame Direct !!,
this is my samples of my codes which contain the problem :
1st file (Alibaba.java)
package alibaba;
import java.awt.Color;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Alibaba extends JFrame {
public Alibaba(){
super("Alibaba");
Intro intro = new Intro();
this.add(intro);
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = environment.getDefaultScreenDevice();
device.setFullScreenWindow(this);
}
public static void main(String[] args) {
Alibaba alibaba = new Alibaba();
}
}
2nd file(Intro.java) :
package alibaba;
import javax.swing.JButton;
public class Intro extends javax.swing.JPanel implements Runnable{
Thread _intro_run;
public Intro() {
_intro_run = new Thread(this);
_intro_run.start();
}
#Override
public void run() {
// Here i tried to add a button to the Intro !!!
this.add(this.createbutton("Exit"));
}
public JButton createbutton(String text){
JButton _button = new JButton(text);
return _button;
}
}
So please tell me what is the problem and how to solve it , sorry but iam new to java , new to programming games world ! ,, thank you :)
You have to add the JButton inside the main thread, cross thread Component manipulation is bad.
For example:
public Intro() {
JButton exitButton = new JButton("Exit");
this.add(exitButton);
}
Alternatively, use SwingUtilities.invokeLater(Runnable). For example, in your run method:
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
add(createbutton("Exit"));
}
}
}
Based on discussion it seems that you are overriding the paint or paintComponent methods. You need to call super in them, like:
void paint(Graphics g) {
super.paint(g);
// do other stuff to g
}
In addition, it is a bad sign that you have a JPanel that implements Runnable. In Java, all UI work (here you are using Swing components) is done from the Event Dispatching Thread - having an actual Swing component (your Intro class is a JPanel) Runnable flies in the face of that.
Suggestions:
Anytime you add a new component to a container, you have to tell the layout managers to layout the new and existing components. This is done by calling revalidate() on the JPanel receiving the button. You also should call repaint() on the JPanel after this.
You shouldn't do any of this in a background thread.
Most important read the Swing tutorials as they will tell you all of this and more.