Java- Draw rectangle after clicking button - java

This simple code is supposed to draw rectangle after hitting button, but it doesn't work.I didn't know how to do it and the only thing came to my mind was a boolean variable trigger but it doesn't seem to work.Any suggestions? Thank you.
public class testing extends JFrame implements ActionListener{
public JButton button;
public boolean check;
public void paint(Graphics g){
if(check==true){
g.setColor(Color.red);
g.fillRect(30, 50, 50, 50);
}
}
public void start(){
setLayout(new BorderLayout());
button=new JButton();
button.setPreferredSize(new Dimension(200,20));
button.setText("ClickMe");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
setSize(500,500);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
check=true;
}
public static void main(String args[]){
testing x=new testing();
x.start();
}
}

You can call repaint inside actionPerformed.
public void actionPerformed(ActionEvent e) {
check=true;
repaint();
}

Related

What do I need to implement to make the JLabels clickable?

so I created a 2 JLabels which display an icon but now I want that if you click on of the JLabels it produces a text which is displayed on the JFrame. What I know is that you can add some kind of Listener, but the ActionListener doesnt work, so I searched more and came to the MouseListener but I don't understand the explanations and the projects are way more complicated to my. Everthing Im copy pasting is underlined in red.
void mouseClicked(MouseEvent e){}
So i came to this method and it looks kinda similar to the ActionListener method, but again, i dont know which correct Java class i should import or should i "classname implement MouseListener"?
import javax.swing.*;
import java.awt.*;
public class Main1{
public static void main(String[] args){
ImageIcon frameBG = new ImageIcon("res/bg.png");
ImageIcon dogIcon = new ImageIcon("res/dog.png");
ImageIcon catIcon = new ImageIcon("res/cat.png");
JLabel bgLabel = new JLabel();
JLabel dogLabel = new JLabel();
JLabel catLabel = new JLabel();
bgLabel.setBounds(0, 0, 400, 250);
bgLabel.setIcon(frameBG);
dogLabel.setBounds(50, 30, 150, 150);
dogLabel.setIcon(dogIcon);
catLabel.setBounds(210, 30, 150, 150);
catLabel.setIcon(catIcon);
JFrame frame = new JFrame("Cat and Dog Clicker");
frame.setSize(400, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(dogLabel);
frame.add(catLabel);
frame.add(bgLabel);
frame.setVisible(true);
}
}
You can try:
bgLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
bgLabel.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("click");
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("press");
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("released");
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("entered");
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println("exit");
}});
Steffi

Press JButton to draw a ball, the ball is not visible

So, I want to draw a ball whenever the user presses JButton. My problem is that the ball is not visible after I call revalidate() and repaint(). Am I forgetting something?
Here is my code, I have another class for the queue and stack that's why I extended Queueue. My buttons are visible and I know they work when I press them, it's jst that the ball doesn't show up on the screen. Earlier I tried to have my void paintComponent in my ActionListener but it would not work. I then wanted to just call the method but because of the Graphics g parameter it would not work as well. So I saw similar issue where someone suggested to use boolean
public class Main extends Queueue {
static boolean clicked = false;
public void paintComponent(Graphics g) {
if(clicked) {
g.setColor(Color.BLACK);
g.fillOval(60, 60, 15, 15);
}
}
public static void main (String[] args) {
Queueue qq = new Queueue();
JFrame f = new JFrame();
JPanel p = new JPanel();
JButton b1 = new JButton("Queue");
JButton b2 = new JButton("Stack");
JButton b3 = new JButton("Ball");
f.setSize(700, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.setBackground(Color.RED);
p.add(b1);
p.add(b2);
p.add(b3);
f.add(p);
f.setVisible(true);
b1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
qq.Q();
}
});
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
qq.S();
}
});
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clicked = true;
f.revalidate();
f.repaint();
}
});
You had some syntax errors which I corrected. I also trimmed it down to more clearly demonstrate the procedure. Here is a working version that just paints the ball.
public class Main extends JPanel {
static boolean clicked = false;
public static void main(String[] args) {
JFrame f = new JFrame();
Main m = new Main();
JButton b3 = new JButton("Ball");
f.setSize(700, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(m);
m.add(b3);
f.setVisible(true);
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clicked = true;
f.repaint();
}
});
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (clicked) {
g.setColor(Color.BLACK);
g.fillOval(60, 60, 15, 15);
}
}
}
Your class should extend JPanel
Add it to the JFrame.
Add the JButton to Main instance
and in paintComponent call super.paintComponent(g) first.
Check out The Java Tutorials for more information on how to paint.
In response to your comments, the following should work. The main issue is that you need to have the paintComponent inside a JPanel, not as a method in Queueue.
public class Main extends Queueue {
static boolean clicked = false;
public static void main(String[] args) {
JFrame f = new JFrame();
Main m = new Main();
JPanel panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (clicked) {
g.setColor(Color.BLACK);
g.fillOval(60, 60, 15, 15);
}
}
};
JButton b3 = new JButton("Ball");
f.setSize(700, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
panel.add(b3);
f.setVisible(true);
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
clicked = true;
f.repaint();
}
});
}
}

Glasspane does not work, java

I have been working on a little java application, and I wanted to add a waiting graphics on the glasspane of the rootpane of the application, here is the classes:
public class WaitPanel extends JPanel {
public WaitPanel() {
this.setLayout(new BorderLayout());
JLabel label = new JLabel(new ImageIcon("spin.gif"));
this.setLayout(new BorderLayout());
this.add(label, BorderLayout.CENTER);
this.setOpaque(false);
this.setLayout(new GridBagLayout());
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
me.consume();
Toolkit.getDefaultToolkit().beep();
}
});
}
public void paintComponent(Graphics g) {
g.setColor(new Color(0, 0, 0, 140));
g.fillRect(0, 0, getWidth(), getHeight());
}}
and the main class :
public class NewJFrame extends JFrame {
public NewJFrame() {
JButton button =new JButton("Click");
getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
}
});
}
but when I change the button action to :
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
Scanner sc=new Scanner(System.in);
String s=sc.next();
getRootPane().getGlassPane().setVisible(false);
It does not work.
Your problem (one of them) is that your code freezes the Swing event thread with its use of a Scanner based on System.in, and in so doing prevents the GUI from updating its graphics, including it's glass pane. Solution -- don't do that. If you want to block the GUI or pause it, use a Swing Timer, or a JOptionPane.
For instance, you could change
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
Scanner sc=new Scanner(System.in);
String s=sc.next();
getRootPane().getGlassPane().setVisible(false);
to something like this:
getRootPane().setGlassPane(new WaitPanel());
getRootPane().getGlassPane().setVisible(true);
int delay = 4 * 1000; // 4 second delay
new javax.swing.Timer(delay, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getRootPane().getGlassPane().setVisible(false);
((javax.swing.Timer) e).stop();
}
}).start();

Moving element by KeyListener in Swing

I have problem with KeyListener, I've been searching solution but it should be working.
Unfortunately, it doesn't and i have no idea why. When i type up arrow, nothing happens.
I was reading about "Focus", but I don't know how this works, maybe you can give me some example, unnecessary to my problem.
public class Trawa extends JPanel implements KeyListener {
int wysokosc = 200;
public Trawa(){
addKeyListener(this);
setSize(200,600);
setBackground(Color.GREEN);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
Color c1 = new Color(36,217,36);
g2d.setColor(c1);
g2d.fillRect(10, wysokosc, 100, 100);
c1 = new Color(0,0,0);
g2d.setColor(c1);
g2d.fillRect(10, wysokosc, 30, 30);
g2d.fillRect(80, wysokosc, 30, 30);
c1 = new Color(252,3,0);
g2d.setColor(c1);
g2d.fillRect(40, wysokosc+60 ,30,30);
}
#Override
public void keyPressed(KeyEvent arg0) {
int key = arg0.getKeyCode();
if(key == KeyEvent.VK_UP)
wysokosc-=100;
repaint();
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
Here is my main class with frame. Maybe the problem is here.
public class GUI extends JFrame{
public GUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
add(new Trawa());
setLayout(new GridLayout(1,5));
pack();
setSize(1300, 600);
setLocation(40, 100);
setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
}
You have to understand how focus works before using a KeyListener.
Try calling setFocusable(true) from your JPanel's constructor.
You have done everything correctly, but you forgot to bind the key listener with your frame.
try this version of you GUI class
class GUI extends JFrame {
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
Trawa t = new Trawa();//this is a JPanel as well as a KeyListner
add(t);
this.addKeyListener(t);
setLayout(new GridLayout(1, 5));
pack();
setSize(500, 400);
setLocation(40, 100);
setVisible(true);
}
}
as pointed by Kevin: the minimal change required is to set focus on the panel
public Trawa() {
addKeyListener(this);
setSize(200, 600);
setBackground(Color.GREEN);
setFocusable(true);
}

drawing on new thread (canvas is good but not working on jpanel correctly)

I was drawing my game on Canvas, all was god, but I changed it into a JPanel, but now its not working correctly, here are the codes, you can just copy them and you'll see where is the problem (I have a menu and after clicking on the button it should create new thread and there i want to draw, the problem in JPanel is that the button is able to see, its blinking and i can press it, in canvas it was fine, there wasn't any button). I solved it, that after clicking on the button I setted him unvisible (button.setVisible(false)), but these codes are just examples and in my game I have more buttons, so its not practical because I need them to see after the game ends. I think I just forgot an important method in JPanel, thx for help, codes:
//Main class representing menu
public class Sandbox extends JFrame{
Panel p = new Panel();
public static void main(String[] args) {
new Sandbox();
}
public Sandbox() {
setLayout(null);
setPreferredSize(new Dimension(200, 200));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
final JButton but = new JButton("Button");
but.setBounds(0, 0, 50, 50);
but.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
p.start();
}
});
add(p);
add(but);
pack();
setVisible(true);
}
}
//Drawing on Canvas -> working well
public class Panel extends Canvas implements Runnable {
Thread t;
public Panel() {
setSize(new Dimension(200, 200));
setVisible(false);
}
public void start() {
t = new Thread(this);
t.start();
setVisible(true);
}
public void draw() {
BufferStrategy b = getBufferStrategy();
if(b == null) {
createBufferStrategy(3);
return;
}
Graphics g = b.getDrawGraphics();
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);
g.dispose();
b.show();
}
#Override
public void run() {
while(!t.isInterrupted()) {
try {
draw();
t.sleep(200);
} catch (InterruptedException ex) {}
}
}
}
//Drawing on JPanel -> here i can press the button after first click on it
public class Panel extends JPanel implements Runnable {
Thread t;
public Panel() {
setSize(new Dimension(200, 200));
setVisible(false);
}
public void start() {
t = new Thread(this);
t.start();
setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);
}
#Override
public void run() {
while(!t.isInterrupted()) {
try {
repaint();
t.sleep(200);
} catch (InterruptedException ex) {}
}
}
}
Not sure I understand exactly what you are trying to do but you do have a couple of problems:
the setVisible(true) method should be invoked AFTER you have added all the components to the frame and packed the frame.
by default the content pane of a JFrame uses a BorderLayout. You code is adding two components to the CENTER of the BorderLayout, but a BorderLayout only allows you to add one component to the CENTER, so only the last component added will be displayed.

Categories

Resources