I'm trying to add a line into my program, it runs however displays nothing, how do I fix this?
I've watched tutorials and I've come up with the following code, but it doesn't display anything. How do I fix this?
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
}
Here is my full program:
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
public class GuiLine {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiLine window = new GuiLine();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GuiLine() {
initialize();
}
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Your class GuiLine has the method paint(Graphics g), but it will never be called since the class isn't a component (nor is it added to the frame, so it wouldn't be visible).
You can make the class extend JPanel and in your initialize method call frame.add(this);. Then you can continue reading some more tutorials.
Related
I'm trying to add a rectangle to my JFrame with Window Builder and it gives me a syntax error, I tried all the things that can be the issue but Eclipse doesn't give me a hint of why it's not working. I tried to think on what's the issue but nothing came into mind.
This is my code:
package com.cookie.clicker;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PathFinder extends JPanel {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PathFinder window = new PathFinder();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PathFinder() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
PathFinder pf = new PathFinder();
frame = new JFrame();
frame.setBounds(0, 0, 1920, 1080);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.setResizable(false);
pf.paint(null);
}
public void paint(Graphics g)
{
// set Color for rectangle
g.setColor(Color.red);
// draw a rectangle by drawing four lines
g.drawLine(100, 100, 100, 300);
g.drawLine(100, 300, 300, 300);
g.drawLine(300, 300, 300, 100);
g.drawLine(300, 100, 100, 100);
}
}
Okay, so you might like to start with
Performing Custom Painting
Painting in AWT and Swing
You'll also probably want to take a look at Laying Out Components Within a Container to get a better understanding of how components get laid out
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PathFinder extends JPanel {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PathFinder finder = new PathFinder();
JFrame frame = new JFrame();
frame.add(finder);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// set Color for rectangle
g.setColor(Color.red);
// draw a rectangle by drawing four lines
g.drawLine(100, 100, 100, 300);
g.drawLine(100, 300, 300, 300);
g.drawLine(300, 300, 300, 100);
g.drawLine(300, 100, 100, 100);
}
}
the code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PaintWindow {
private JFrame frame;
private aJPanel panel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PaintWindow window = new PaintWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PaintWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new aJPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.stam();
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
frame.setBounds(100, 100, 450, 300);
frame.setVisible(true);
}
public class aJPanel extends JPanel {
private static final long serialVersionUID = 8874943072526915834L;
private Graphics g;
public aJPanel() {
super();
System.out.println("Constructor");
}
public void paint(Graphics g) {
super.paint(g);
System.out.println("paint");
g.fillRect(10, 10, 10, 10);
this.g = g;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("paintComponent");
g.fillRect(20, 20, 20, 20);
this.g = g;
}
public void stam() {
System.out.println("stam");
this.g.fillRect(40, 40, 40, 40);
this.repaint();
}
}
}
what I want to do is paint custom shapes (lines, rectangles etc) after the user clicks a button or triggers a mouse event. but calling aJPanel.stam() does not show the rectangle its supposed to. I am fairly new to JPanel. any suggestions?
First of all:
class names should start with a capital letter
class names should be descriptive.
"aJPanel" does not follow either of the above.
but calling aJPanel.stam() does not show the rectangle its supposed to
See Custom Painting Apporoaches for the two common ways to do dynamic painting:
Add objects to a List and iterate the List to paint all the objects
Paint directly to a BufferedImage and then paint the BufferedImage
The examples add the Rectangle by dragging the mouse, but you can easily add Rectangles by just invoking the addRectangle(...) method when you click a button.
I want to make the JFrame transparent, but the image on top of it to be non-transparent. This is what I have now:
Does anyone know a way to make only the JFrame transparent?
Here's my code:
import javax.swing.*;
import java.awt.*;
import com.sun.awt.AWTUtilities;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
public class SplashDemo extends JFrame
{
public SplashDemo()
{
setUndecorated(true);
setSize(200, 200);
add(new JLabel(new ImageIcon("puppy2.png")));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setOpacity(0.85f);
}
public static void main(String[] args)
{
new SplashDemo();
}
}
Basically, you need to make a transparent window and a translucent content pane. This will mean anything added to the content pane will continue to be rendered without additional alphering...
public class TranscluentWindow {
public static void main(String[] args) {
new TranscluentWindow();
}
public TranscluentWindow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JWindow frame = new JWindow();
frame.setAlwaysOnTop(true);
frame.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
frame.setBackground(new Color(0,0,0,0));
frame.setContentPane(new TranslucentPane());
frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Puppy.png")))));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TranslucentPane extends JPanel {
public TranslucentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
}
First coord in this case should be 0,0 and not 8,30. What am i doing wrong(i am using NetBeans)
import java.awt.Color;
import java.awt.Graphics;
public class TEST extends javax.swing.JFrame {
#Override
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.blue);
g.drawRect(8, 30, 200, 200);
repaint();
}}
Add a JPanel to the frame and paint in that. The frame's coordinates include the decorations (title bar, borders, etc.). It would look something like this:
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
private Test() {
add(new MyPanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
}
private class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.drawRect(8, 30, 200, 200);
}
}
}
Also, don't call repaint(); in paint();. That will cause an infinite loop and will freeze the entire program.
The problem is your paint(..) method is not taking into account the JFrame Insets by calling getInsets which as docs state:
If a border has been set on this component, returns the border's
insets.
this code works fine:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void createAndShowGui() {
JFrame frame = new JFrame() {
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.blue);
g.drawRect(0 + getInsets().left, 0 + getInsets().top, 200, 200);
}
};
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
however this is not best practice.
Rather add JPanel to JFrame and override paintComponent(Graphics g) of JPanel dont forget call to super.paintComponent(g) as first call in the overridden method and than draw there (dont forget to override getPreferredSize() and return correct Dimensions so the JPanel will fit its drawing/graphic content) this problem will no longer persist as JPanel is added at correct co-ordinates on contentPane like so:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void createAndShowGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.setColor(Color.blue);
g2d.drawRect(0, 0, 200, 200);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
};
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
The above includes Graphics2D and RenderingHints i.e anti-aliasing. Just for some better looking drawings :)
I have the following program to test GlassPane, but it doesn't work with JDIC's WebBrowser. Does anyone know what I did wrong and how to make it work?
import org.jdesktop.jdic.browser.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class Test_Panel extends JPanel
{
static WebBrowser webBrowser=new WebBrowser();
static int W=802,H=702;
Test_Panel()
{
setPreferredSize(new Dimension(W,H));
setLayout(new BorderLayout());
webBrowser.setPreferredSize(new Dimension(W,H));
// add("Center",webBrowser);
try { webBrowser.setURL(new URL("http://www.yahoo.com")); }
catch (MalformedURLException e) { e.printStackTrace(); }
}
static void Create_And_Show_GUI()
{
JFrame frame=new JFrame("Test");
frame.add(new Test_Panel());
frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
new My_GlassPane(frame,W,H);
frame.pack();
frame.setBounds(0,0,W,H);
frame.setVisible(true);
}
public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } }); }
}
class My_GlassPane extends JComponent
{
JFrame f;
int W,H,Edge,Size;
public My_GlassPane(JFrame f,int W,int H)
{
this.f=f;
this.W=W;
this.H=H;
Edge=W/100;
Size=W/5;
f.setGlassPane(this);
f.getGlassPane().setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(W/6,H*18/120,W*2/3,H*2/3);
g.setColor(Color.white);
g.setFont(new Font("Times New Roman",0,Size));
g.drawString("Test",W/3,H*68/120);
}
}
If you uncomment add("Center",webBrowser); you will see what I mean-- the GlassPane won't show up. Why not?
You need to have "jdic.jar" and "IeEmbed.exe" to make it work. The version I have is 0.9.1.0 and you can get them here.
As I've read, WebBrowser is an AWT component while GlassPane is a Swing component. There is a common problem mixing heavyweight and lightweight components. I don't think there is a workaround on what you're trying to do.
More information on this subject can be found in this discussion.