I have a JPanel with a drawn picture (created by paintComponent) and a JButton in front of the picture. Everything looks fine when I start the programme. After a click on the button the picture is redrawn using repaint, the JButton is removed and a new JButton is added instead. This new JButton should be in front of the drawing, but becomes visible only after I hover the mouse over it. What is the reason for this behaviour and how can I fix it? Schematic of my code, with all non-relevant parts left out:
public void paintComponent(Graphics g){
super.paintComponent(g);
//draw picture
}
private void updateDrawing(){
repaint();
}
public void updateButton(){
//remove button from JPanel
//add new button to JPanel
ActionListener pressButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateDrawing();
updateButton();
}
};
button.addActionListener(pressButton);
panel.add(button);
}
public static void main(String[] args){
updateButton();
}
Related
I am trying to make a panel showing a printed statement "Hello World!" and an OK button. Neither will show up on the panel and I have no idea why. I started with a block of code that was supposed to create just a blank popup. The blank popup worked great. I can't add the string or button and see them. I have tried calling paintComponent. I have tried adding the content to the panel. Does anyone know what I am missing?
Here is my code
package painting;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingPaintDemo1 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static class SwingPaintDemo extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello World!", 20,30);
}
}
private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(250,250);
f.setVisible(true);
JButton okbutton = new JButton("OK");
ButtonHandler listener = new ButtonHandler();
okbutton.addActionListener(listener);
SwingPaintDemo displayPanel = new SwingPaintDemo();
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okbutton, BorderLayout.SOUTH);
}
private static class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}
You forgot to add the JPanel to the JFrame. Just add the following line at the bottom of your createAndShowGUI() method:
f.add(content);
I would also recommend moving your f.setVisible(true); line to the bottom of the method just to be safe. When you make the frame visible, the component tree is set up to take into account all the components added to the JFrame. If you add more components after that, you will need to do either manually revalidate the tree or do something that triggers an automatic revalidation. I'm assuming you're not revalidating your tree anywhere, so you should move f.setVisible(true); to after all the components are added.
I'm making a GUI application which finds and draws convex hull for a set of points.
Here's the frame:
public class Frame extends JFrame{
Panel panel = new Panel();
JButton drawHull = new JButton("Draw Convex Hull");
Frame(String title) {
super(title);
// setLayout
setLayout(new BorderLayout());
// add components to the frame
add(panel, BorderLayout.CENTER);
add(drawHull, BorderLayout.SOUTH);
// add actionListener for drawHull button
drawHull.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
panel.drawConvexHull();
}
}
);
}
}
The frame contains a button (at the bottom of the frame) and a Panel object.
Here's the Panel class:
public class Panel extends JPanel{
ArrayList<Point> points = new ArrayList<Point>();
public Panel() {
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
points.add(new Point(e.getX(), e.getY()));
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
if(!points.isEmpty()) {
Point p = points.get(points.size()-1);
g.fillOval(p.x-2, p.y-2, 4, 4);
}
}
public void drawConvexHull() {
// code for finding convex hull
}
}
I have added a mouseListener to the Panel class so that when the user clicks anywhere on the panel, a point is drawn.
When I run the code, everything looks fine. Here's a sample run.
Now here's the problem:
As soon as I click the panel, this happens
A button appears on the top of the frame. Why is this happening?
One more thing. When I click this button on the top, a point is drawn. Here, have a look:
Without calling super.paintComponent(g) in paintComponent the background is not repainted leading to unpredictable results on the panel component.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Point point: points) {
g.fillOval(point.x - 2, point.y - 2, 4, 4);
}
}
So I am making a simple paint program, and I have two panels. The first panel is center right and is the canvas. The other, docked on the right and is to hold tool buttons, but it currently has only a clear button. The thing is when I start clicking on the canvas, the clear button is painted on it as a result. Any idea what I am missing?
public class Paint extends JFrame implements ActionListener {
private Canvas canvas;
private JButton clear;
private JPanel tools;
Paint(){
canvas= new Canvas();
add(canvas,BorderLayout.CENTER);
clear= new JButton("Clear");
clear.addActionListener(this);
tools= new JPanel();
tools.add(clear);
add(tools,BorderLayout.WEST);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==clear){
canvas.clear();
}
}
public static void main(String[] args) {
Paint paint=new Paint();
paint.setSize(1000,800);
paint.setVisible(true);
paint.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Canvas:
public class Canvas extends JPanel {
private int x= -10;
private int y= -10;
private boolean clear=false;
Canvas(){
addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent e){
x=e.getX();
y=e.getY();
draw();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent e){
x=e.getX();
y=e.getY();
draw();
}
});
}
#Override
public void paintComponent(Graphics g){
if(clear){
super.paintComponent(g);
clear=false;
}
else{
g.fillOval(x,y,4,4);
}
}
public void draw(){
this.repaint();
}
public void clear(){
clear=true;
repaint();
}
}
Graphics is a shared resources, that is, every component that is painted during a paint cycle uses the same Graphics context.
One of the jobs of paintComponent is to prepare the Graphics context for painting by the component, failing to call super.paintComponent EVERY TIME paintComponent is called is leaving what ever was previously painted to the Graphics context in tact.
Call super.paintComponent every time paintComponent is called.
Painting in Swing is destructive, that is, you are expected to repaint the entire state of your component whenever paintComponent is called.
Not sure if this has been discussed before. But I am having a odd issue with transparent JTextFields added on a transparent JPanel. For some reason (I could not dig enough to find why) there are additional paintings that get carried out. Perhaps there are dirty regions that needs to be dealt with? not sure.
Let me present this simple example:
public class TextFieldGame extends JPanel {
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame someFrame = new JFrame("Is this odd?");
someFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
someFrame.setSize(200,600);
someFrame.add(new TextFieldGame());
someFrame.setVisible(true);
}
});
}
public TextFieldGame() {
setupContentPane();
}
private void setupContentPane() {
setLayout(new BorderLayout());
final CanvasPanel canvasPanel = new CanvasPanel();
add(canvasPanel, BorderLayout.CENTER);
add(new ControlPanel(canvasPanel), BorderLayout.SOUTH);
}
public static class ControlPanel extends JPanel {
private final CanvasPanel canvasPanel;
ControlPanel(CanvasPanel canvasPanel) {
this.canvasPanel = canvasPanel;
setupContentPane();
}
private void setupContentPane() {
setLayout(new FlowLayout(FlowLayout.RIGHT));
final JButton load = new JButton("load");
add(load);
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
canvasPanel.addChildComponent(getComponent());
canvasPanel.revalidate();
canvasPanel.repaint();
}
});
}
private JComponent getComponent() {
final JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.setOpaque(false);
for (int i = 0; i < 10; i++) {
final JTextField textField = new JTextField("why you no work?") {
#Override
public Dimension getMaximumSize() {
return new Dimension(Short.MAX_VALUE, getPreferredSize().height);
}
};
textField.setOpaque(false);
container.add(textField);
}
return container;
}
}
public static class CanvasPanel extends JPanel {
private int paintCount = 0;
CanvasPanel() {
setupContentPane();
}
public void setupContentPane() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
setBackground(Color.white);
}
public void addChildComponent(JComponent component) {
component.setAlignmentY(TOP_ALIGNMENT);
add(component);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("paint count: " + ++paintCount);
}
}
}
I have added the System out statement to show the count of paint task.
When first loaded, there will be 2/3 paints - fair enough. Then if you are to press the "Load" button, 10 transparent JTextFields will be added to a transparent JPanel, and this transparent JPanel will be added to the CanvasPanel. (Canvas panel is in turn a subchild of the JFrame). You will notice upon doing this, 11 additional paint jobs will be done.
But in theory (well in my understanding) after "Load" is pressed, only one paint job should be carried out. That is because, I have added only one child to CanvasPanel (the child itself might have 10 textfields, but they should all be painted in one shot).
Just to test my understanding, if you are to use 10 JLabels instead of the 10 JTextFields, only one paint job is carried out after "Load" is pressed. Which is what it should be.
Also, if you are to keep JTextField opaque, only one paint job is carried out. (Just tested that if instead of JTextField, a JTextArea is used, one paint is done)
What is going on? Note that JLabel is transparent by default, so I am not sure why transparency of JTextField component causing these additional paints.
Please help/
I am new to Java....I studied that we can add two things on frame... I added button and in response by clicking on button I want rectangle as output....but i don't understand that..Why i am not getting output.....
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class customizedgui5 implements ActionListener {
JButton button;
JFrame frame;
public static void main(String[] args) {
customizedgui5 hi = new customizedgui5();
hi.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("click me");
button.addActionListener(this);
myclass a = new myclass();
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.getContentPane().add(a, BorderLayout.SOUTH);
frame.setSize(100, 100);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
frame.repaint();
frame.revalidate();
}
}
class myclass extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
I would start by taking a look at Performing Custom Painting.
The main problem in your code is you are getting NullPointerException when you click the button because the reference of frame is null.
It is null because you've shadowed it in the constructor (basically, declared another variable of the same name within the constructor)...
// I'm null..
JFrame frame;
public void go() {
// Not the same as frame above...
JFrame frame = new JFrame();
You are also going to not see any changes because of a number of reasons...
The myclass panel has no size. With BorderLayout, this won't be "too" much of a problem, but...
You've drawing outside of the visible range of the panel. The rectangle you are painting won't appear because it is being painted outside of the width and height of the panel.
The rectangle will appear before you press the button as paintComponent will be called to update the state of the panel once it's made visible on the screen...
The first thing you need to is provide some kind of size hints to the BorderLayout. Try adding...
#Override
public Dimension getPreferredSize() {
return new Dimension(120, 150);
}
To myclass.
You also don't need to repaint the frame, what you really want to repaint is the instance of myclass. Try updating customizedgui5 so that a becomes a instance variable (like frame...
//...
myclass a;
//...
public void go() {
//...
a = new myclass();
//...
}
public void actionPerformed(ActionEvent event) {
a.repaint();
}
Now, the rectangle will still be shown the moment that the panel is made visible on the screen. Sure you could try setting it invisible, but this will affect the layout of the frame, hiding your component to start with, so, instead, we need some kind of flag we can trip so we know when to paint the rectangle. This is easily achieved by using a simple boolean variable, for example...
class myclass extends JPanel {
private boolean paintRect;
public void setPaintRect(boolean paint) {
paintRect = paint;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(120, 150);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (paintRect) {
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
}
Then in you actionPerformed method, you just need to set the flag...
public void actionPerformed(ActionEvent event) {
a.setPaintRect(true);
}
You may also want to take a read through Code Conventions for the Java Programming Language. It will make it easier for people to read your code...
When you click on your button, you're calling the method actionPerformed(ActionEvent event)
Take a look at what you did there. Currently, you repaint and re-validate the frame. If you want to add a rectangle to your frame, you need to do so by adding a new component to the frame that will draw the rectangle.
You could add another instance of your myclass JPanel which paints a rectangle like so:
public void actionPerformed(ActionEvent event) {
frame.getContentPane().add(new myclass(), BorderLayout.NORTH);
frame.repaint();
}
This would add your custom rectangle-drawing panel to the North section of your BorderLayout. If you want to add the rectangle "on top of" your button, you should embed your button within a JPanel, then add the rectangle-drawing panel to that instead of your main JFrame