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
Related
I have started working with JFrames and am creating a simple programme with 3 panels that are different colours and I was just wondering what would be the best way to switch between panels for my programme. The panels are to be changed when a JMenuItem with the colours name is selected. I was looking at cards and was wondering if they would be a good solution and if it would be possible to implement them into my programme? Any other suggestions would be greatly appreciated & apologies if I have done anything wrong ive only started on stack overflow and am quite a newcomer to Java :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Colour extends JFrame
{
CardLayout card;
JPanel childPanel = new JPanel(), redPanel, bluePanel, greenPanel;
Container c;
public Colour(){
// Get Container
c=getContentPane();
//Create Menu and items
childPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu customer = new JMenu("Colour");
customer.setMnemonic(KeyEvent.VK_U);
JMenuItem blue = new JMenuItem("Blue");
JMenuItem red = new JMenuItem("Red");
JMenuItem green = new JMenuItem("Green");
customer.add(blue);
customer.add(red);
customer.add(green);
menuBar.add(customer);
this.setJMenuBar(menuBar);
//Adding panel to container
c.add(childPanel);
childPanel.setBackground(Color.PINK);
//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
} );}
//Creating my different panels and adding them to childPanel
public void redC() {
redPanel = new JPanel();
redPanel.setBackground(Color.RED);
childPanel.add(redPanel, "Red");
}
public void blueC() {
bluePanel = new JPanel();
bluePanel.setBackground(Color.BLUE);
childPanel.add(bluePanel, "Blue");
}
public void greenC() {
greenPanel = new JPanel();
greenPanel.setBackground(Color.GREEN);
childPanel.add(greenPanel, "Green");
}
public static void main(String[] args) {
Colour cl=new Colour();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
You are almost done with you code.
Here is the working code.
You need to revalidate the childPanel after adding/removing a panel so that it will be repainted:
//Action Listeners for switching panels
blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() >0)
childPanel.remove(0);
blueC();
childPanel.revalidate();
}
});
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.removeAll();
redC();
childPanel.revalidate();
}
});
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (childPanel.getComponentCount() > 0)
childPanel.remove(0);
greenC();
childPanel.revalidate();
}
});
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();
}
});
}
}
I'm trying to move around jframe on the window through an event triggered from an external jpanel class, my code is below, but the doesn't achieve this. Instead the panel is the one that's moving around.
What am I doing wrong here? I am new programming in general.
package casuls_app;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Titlebar extends JPanel {
public Titlebar() {
btnClose =new JButton("X");
btnClose.setFocusable(false);
btnClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeButtonPressed(e);
}
}
);
controlBox =new JPanel(new GridLayout(1,1));
controlBox.setPreferredSize(new Dimension(150,40));
controlBox.add(btnClose);
controlBox.setBackground(new Color(255,255,255));
setLayout(new BorderLayout());
add(controlBox,BorderLayout.EAST);
setPreferredSize(new Dimension(0,40));
setBackground(new Color(60, 173, 205));
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
mousePressedOnTitlebar(e);
}
}
);
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
mouseDraggedOnTitlebar(e);
}
}
);
}
private void mousePressedOnTitlebar(MouseEvent e) {
posX= e.getX();
posY=e.getY();
}
private void mouseDraggedOnTitlebar(MouseEvent e) {
setLocation(e.getXOnScreen() -posX, e.getYOnScreen() -posY);
}
private void closeButtonPressed(ActionEvent e){
System.exit(0);
}
//Variables declaration
private int posX,posY;
private JButton btnClose;
private JPanel controlBox;
}
setLocation() sets the location of your JPanel (because your class extends JPanel).
If you have a reference to the JFrame, you can call the setLocation method on that object.
frame.setLocation(x, y);
If you don't have the reference, then you can follow this post which accesses the frame via SwingUtilities:
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
I'm quite new to java here , and right now i'm working on a program which involves the following actions. Lets say i have a 3 X 3 grid of JLabel. How do i load an ImageIcon and then move it from on label to another. For example, say each label is named as label_1 to label_9, and the imageicon is on label_2 . When i click on label_3,imageicon it should go to label_3
Very quick example which you can adapt to your needs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Test extends JFrame {
public Test() {
JPanel container = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
JLabel label = new JLabel("Label" + i);
label.setPreferredSize(new Dimension(100, 100));
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
Icon icon = UIManager.getIcon("OptionPane.informationIcon");
JLabel clickedLabel = (JLabel) e.getSource();
Container parent = clickedLabel.getParent();
clearIcons(parent);
clickedLabel.setIcon(icon);
}
private void clearIcons(Container parent) {
Component[] components = parent.getComponents();
for (Component component : components) {
((JLabel) component).setIcon(null);
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
container.add(label);
}
add(container);
}
public static void main(String[] args) {
Test frame = new Test();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
}
}
Result should be following:
how can i change the color of a JLABEL with a link in java?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class XXX extends JFrame {
XXX(){
final JLabel lab1=new JLabel("Username:");
final JTextField text1=new JTextField(20);
lab1.setBounds(20,140,65,20);
text1.setBounds(85,141,185,20);
add(lab1);
add(text1);
lab1.setForeground(Color.white);
final JLabel lab2=new JLabel("Password:");
final JPasswordField text2=new JPasswordField(20);
lab2.setBounds(20,165,65,20);
text2.setBounds(85,166,185,20);
add(lab2);
add(text2);
lab2.setForeground(Color.white);
final JButton a=new JButton("Sign In");
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Code
}
});
a.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
a.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
a.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
a.setEnabled(false);
text1.setEditable(false);
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
a.setBounds(85,192,80,20);
add(a);
final String strURL = "http://www.yahoo.com";
final JLabel lab3 = new JLabel("<html>Register</html>");
lab3.setBounds(170,192,52,20);
add(lab3);
lab3.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
lab3.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
lab3.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
final JLabel map = new JLabel(new ImageIcon(getClass().getResource("XXXBG.png")));
map.setBounds(0,0,300,250);
add(map);
setTitle("XXX");
setSize(300,250);
setResizable(false);
setCursor(DEFAULT_CURSOR);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(8, 8);
setLayout(null);
toFront();
setVisible(true);
}
public static void main(String[] args)
{
new XXX();
}
}
as you can see, i cant change the foreground color of JLABEL lab3.
if posible, i want also to change color of border-like of the jframe.
anyone can help?
Yes, it's possible. Simple supply the foreground color you want to use...
lab3.setForeground(Color.BLUE);
You also don't need the mouse listener. Simply using lab3.setCursor(new Cursor(Cursor.HAND_CURSOR)); will change the mouse cursor automatically when the mouse is moved over the label for you...magically :D
Updated
public class TestLabel01 {
public static void main(String[] args) {
new TestLabel01();
}
public TestLabel01() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JLabel link = new JLabel("Linked in");
link.setForeground(Color.BLUE);
link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(link);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}