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);
});
}
}
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 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());
}
}
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 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
According to your instruction i decided to use GridBagLayout, but i also face a problem in positioning buttons in a panel the button expected to be at top right, But it is displayed in the center, Please tell me what is the problem in my code`
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
public class Test extends JFrame {
private JPanel contentPane;
private JButton button2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 573, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridBagLayout());
contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setContentPane(contentPane);
button2 = new JButton("button2");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
contentPane.add(button2, c);
}
}
this the the output
http://postimg.org/image/bhnzskznj/
Since the answer just asks for a Layout - it's layout recommendation time!
My favourite - http://www.miglayout.com/ which satisfied all my layout needs for my last Swing project. wrap, span x and center layout arguments should be all that is needed to do what your picture does.
This is exactly why absolute layouts are not recommended.
Your best approach will be to use something like GridBagLayout which will position the elements and then let them move as the screen resizes and reshapes.
There are plenty of good documentation and tutorials online for GridBagLayout that will get you started. You can also use tools built into some IDEs (NetBeans has a good one for example) to let you lay things out graphically.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Can anybody explain why pack() isn't working on this JFrame?
It's got one JPanel inside (actually, a class that extends JPanel - inner).
Here's the code I'm using:
inner.setPreferredSize(new Dimension(800, 600));
add(inner);
pack();
setResizable(false);
setLocationRelativeTo(null); // to center the JFrame on screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
The extra space seems to be the exact width and height of the JFrame's decoration (that is, the JFrame's dimensions minus the JPanel's dimensions).
Invoke setResizable(false) before pack(). It's no coincidence that "extra space seems to be the exact width and height of the JFrame's decoration."
Addendum: Here's an sscce showing that my initial guess was incorrect.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/questions/7924830 */
public class NonResizable extends JPanel {
public NonResizable() {
this.setPreferredSize(new Dimension(400, 300));
this.setBackground(Color.lightGray);
this.setBorder(BorderFactory.createLineBorder(Color.blue));
}
private void display() {
JFrame f = new JFrame("NonResizable");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
f.setBackground(Color.white);
f.add(this);
f.pack();
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setSize(500, 400);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NonResizable().display();
}
});
}
}
Turns out I was drawing (active rendering) from the JFrame and not the JPanel... so the extra space was the result of the JPanel's draw() object being aligned at 0,0 (in the JFrame).
Solved by this post.