why wouldn't it work? using getMouseClicked with no results - java

this program suppose to create a window that has a status bar under it that shows how many times the mouse was clicked without being moved on the screen. when you move the mouse and click it suppose to start a new count. it also distinguishes different mouse buttons. I've followed this code exactly as a tutorial I saw, but it doesn't work. I just get the window with a status bar that never changes.
public class Adapter_class extends JFrame {
private String details;
private JLabel statusBar;
public Adapter_class() {
super("Adapter mouse:");
this.statusBar = new JLabel("Default");
add(this.statusBar, BorderLayout.SOUTH);
addMouseListener(new MouseClass());
}
private class MouseClass extends MouseAdapter {
public void MouseClicked (MouseEvent event) {
details = String.format("You clicked the mouse %d", event.getClickCount());
//this is for using a mouse from a mac
if (event.isMetaDown())
details += " with the right mouse button";
else if (event.isAltDown())
details += " with the center mouse button";
else
details += " with the left mouse button";
statusBar.setText(details);
}
}
}
this is the main:
import javax.swing.JFrame;
public class Adapter_main {
public static void main(String[] args) {
Adapter_class window = new Adapter_class();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 300);
window.setVisible(true);
}
}

You have written the method MouseClicked with capital M. Use the lower case version
public void mouseClicked(MouseEvent event) { ... }
Otherwise you are creating a new method and not override the adapter's one. You may also want to include a #Override annotation which would force the compiler to show you the issue.

public abstract class MouseAdapter implements MouseListener, MouseWheelListener, MouseMotionListener {
/**
* {#inheritDoc}
*/
public void mouseClicked(MouseEvent e) {}
Use this:
private class MouseClass extends MouseAdapter {
public void mouseClicked (MouseEvent event){
Here the function you have to write is **mouseClicked** not **MouseClicked**
Thats why it helps to use annotations.
#Override would have helped you immediately.

Related

Two different buttons in one Panel in my own Component

I'm trying to create JPanel with two different buttons which one of them increasing and second decreasing size of text or window. I have class with button declaration. Everything is working when I put these buttons on JFrame separately.
I don't know how to get Action Listener in JPanel of each buttons. All I possibly do is listener of mouse click on JPanel...
Could you help me? I'm really begginer with coding so be polite please :]
public class ButtonMy extends Component {
private ButtonIncrease increase;
private PropertyChangeSupport propertyChangeSupport;
public ButtonMy() {
setPreferredSize(new Dimension(30,30));
kolor = Color.blue;
setForeground(kolor);
propertyChangeSupport = new PropertyChangeSupport(this);
increase = ButtonIncrease.Powieksz;
}
public ButtonIncrease getIncrease() {
return increase;
}
public void setIncrease(ButtonIncrease increase) {
ButtonIncrease oldIncrease = this.increase;
this.increase = increase;
propertyChangeSupport.firePropertyChange("increase", oldIncrease, increase);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
There is JPanel for bind 2 buttons. Here is the biggest problem :/ I'm lack of ideas.
public class ButtonB extends JPanel implements ActionListener{
public ButtonMy b1 = new ButtonMy();
public ButtonMy b2 = new ButtonMy();
public ButtonB (){
init();
}
public final void init(){
setLayout(new GridLayout(1,2));
this.przycisk1.setIncrease(ButtonIncrease.Powieksz);
this.przycisk2.setIncrease(ButtonIncrease.Zmniejsz);
add(b1);
add(b2);
}
}
JFrame where I test this component is very common. Code below shows only function for inc and dec size when separate button is clicked (not in JPanel).
private void buttonMy3MouseClicked(java.awt.event.MouseEvent evt) {
switch(buttonMy3.getIncrease()) {
case Powieksz: setSize(1);
break;
case Zmniejsz: setSize(0);
break;
}
}
I didn't paste full of my code. There some of math functions left which I think they are not needed here (setSize for example).
I'm not sure if i understand the problem correctly but I think under the actionListener class you should have a method called actionPerformed& it will say that if button1 is clicked increase the number, if button2 is clicked decrease the number:
public void actionPerformed( ActionEvent event ) {
if (event.getSource()== b1) // your "increase size" code
if(event.getSource()== b2)// your "decrease size" code
}
button listeners are actually different from mouse listeners; buttons implements ActionListeners and have the actionPerformed method with event variable. you could handle the event by:
getSource() -this method is inherited from java.util.EventObject and returns the OBJECT on which the event initially occurred (the button itself)
or by getActionCommand() -this method is available to action events, or any event that inherits from ActionEvent and returns the command STRING associated with this action.
however mouse listeners implements MouseListener and has a lot of methods depending on what the mouse does (pressed, clicked, released, etc.).

Mouse entered, mouse exited changing the text on the button on each event

I am trying to connect a button to say "Hi" when the mouse enters it and "Bye" when the mouse leaves. I have been using mouse events with a MouseListener but to no avail.
I'm new to Java and this question has been plaguing me for the last 2 days and I just have not been able to figure it out. Any help would be greatly appreciated.
private abstract class HandlerClass implements MouseListener {
}
private abstract class Handlerclass implements MouseListener {
#Override
public void mouseEntered(java.awt.event.MouseEvent e) {
mousebutton.setText("Hi");
}
#Override
public void mouseExited(java.awt.event.MouseEvent e) {
mousebutton.setText("Bye");
}
}
Try like this. It is working for me.
public class ChangeTextMouseEvent extends Frame
{
static JButton btn;
public ChangeTextMouseEvent()
{
setTitle("ChangeText");
btn = new JButton("SSS");
add(btn);
setVisible(true);
setBounds(0, 0, 100, 100);
}
public static void main(String[] args)
{
ChangeTextMouseEvent frame = new ChangeTextMouseEvent();
btn.addMouseListener(new MouseAdapter(){
#Override
public void mouseExited(MouseEvent e)
{
btn.setText("Bye");
}
#Override
public void mouseEntered(MouseEvent e)
{
btn.setText("Hi");
}
});
}
}
Updating the UI component alone is often not enough; you also have to trigger a repaint action.
In other words: there are two "layers" here. One is the "data model" (where some button knows about its text); the other is the actual "graphical content". The later one comes into existence by somehow displaying the first parts. Therefore both layers need to be addressed in order to make your chances visible to the user.
See here for some examples around that.

Implementing the observer pattern with Java and MouseListener

I have three classes, Main, DrawingPanel, and ToolboxPanel. ToolboxPanel contains all my buttons, including an Undo button. DrawingPanel is where I draw objects. I want the undo button to become enabled when an object is drawn on the screen, and disabled when there are no more objects left on the screen. Main creates an instance of DrawingPanel and of ToolboxPanel. I can get my undo button to work correctly if I use static methods and call, say, Main.setUndoStatus(false); from drawingPanel. The setUndoStatus then calls a setter in toolboxPanel. However, I've been reading about the Observer pattern and listeners and think I'm probably not doing it in a best-practice way.
How should I go about this using the observer pattern and/or mouse listeners correctly? (Or any "better" way of doing it).
Here's some code somewhat similar to what I'm doing.
public class Main
{
DrawingPanel drawingPanel;
ToolboxPanel toolboxPanel;
public Main()
{
drawingPanel = new DrawingPanel();
toolboxPanel = new ToolboxPanel(drawingPanel);
}
}
//A static method here to setUndoStatus, but I feel like I shouldn't have it
public static void setUndoStatus(boolean b)
{
{
toolboxPanel.setUndoStatus(b);
}
}
public class ToolboxPanel
{
JButton undoButton;
public ToolboxPanel(DrawingPanel drawingPanel)
{
undoButton = new JButton("Undo");
undoButton.setEnabled(false);
undoButton.addActionListener
(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
drawingPanel.undo();
undoButton.setEnabled(drawingPanel.getUndoStatus());
}
}
);
}
public void setUndoStatus(boolean status)
{
undoButton.setEnabled(status);
}
}
public class DrawingPanel
{
public DrawingPanel()
{
addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
//Some code here that's unrelated
if(objectsExist == true) //If something gets drawn, whatever
{
Main.setUndoStatus(true); //Don't like this
}
}
});
}
}

Java Button adds label when clicked after being reized or dragged or something

I have a simple code here which adds a label after being clicked. it works fine, but in order to the label to be added i have to drag or reize the window after clicking the button.
Here is my code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class server01 extends Applet implements ActionListener {
Label helloLabel = new Label("applet v 0.0.1 | created for testing purpose");
Label hello2Label = new Label("this applet will be up-to-date.");
Button buttonButton = new Button("START" + " Button");
Label buttonLabel = new Label("Starting server...");
private static final long serialVersionUID = 1L;
public void init() {
setBackground(Color.black);
setForeground(Color.white);
buttonButton.setForeground(Color.black);
add(helloLabel);
add(hello2Label);
add(buttonButton);
buttonButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonButton) {
add(buttonLabel);
}
}
}
use repaint() method in actionPerformed() - (At the method ending) method.
It will repaint the applet window and will run again adding your label.
public void actionPerformed(ActionEvent ae)
{
/*
your code here..
*/
repaint();
}
You need to call the validate method after making gui changes so that the applet can check if it is still rendered correctly.
Doing a resize will basically do the same thing.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonButton) {
add(buttonLabel);
validate();
}
}

Key Listener doesn't work in a JFrame when traversing from another JFrame

I have 2 classes.
One extends canvas and inside creates a jframe and add the canvas to that jframe and add another keyadapter class to receive key events. I also have main function to test the code. When running from main, the form is displayed and recieves key events too.
Now i create another class that extends jframe and implements keylistener to receive events in this form.
Once the functionality done in the second class i want to close the second form and show the first form. When showing it from the key event functions in the second class the first class key listener is not working.
Please just have a glimpse at my code and tell me how to correct my prob. Thanks for your time and valuable suggestion.
Class 1
public class Test extends Canvas {
private JFrame container;
public Test() {
container = new JFrame("Space Invaders");
JPanel panel = (JPanel) container.getContentPane();
panel.setPreferredSize(new Dimension(screenSize.width, screenSize.height));
panel.setLayout(null);
setBounds(0, 0, screenSize.width, screenSize.height);
panel.add(this);
container.pack();
container.setResizable(false);
container.setVisible(true);
try {
addKeyListener(new KeyInputHandler(this));
} catch (Exception e) {
e.printStackTrace();
}
requestFocus();
}
private class KeyInputHandler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
//Some Action
}
public void keyReleased(KeyEvent e) {
//Some Action
}
public void keyTyped(KeyEvent e) {
//Some Action
}
}
public static void main(String args[]){
//Running this canvas here works perfectly with all added keylisteners
}
}
Class 2
public class Sample extends JFrame implements KeyListener {
public Sample() {
init();
this.setSize(100, 100);
this.setVisible(true);
Sample.this.dispose();
// Created a window here and doing some operation and finally redirecting
// to the previous test window. Even now the test window works perfectly
// with all keylisteners
new Test();
}
public static void main(String[] args) {
new Sample();
}
private void init() {
addKeyListener(this);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
removeKeyListener(this);
Sample.this.dispose();
// But when calling the previous Test window here, the window
// gets displayed but the keylistener is not added to the
// window. No keys are detected in test window.
new Test();
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Simple dont use KeyListener/KeyAdapter that is for AWT components and has known focus issues when used with Swing.
The issues can be got around by making sure your component is focusable via setFocusable(true) and than call requestFocusInWindow() after component has been added/is visible.
Rather use KeyBindings for Swing.
For example say now we wanted to listen for D pressed and released:
public static void addKeyBindings(JComponent jc) {
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "D pressed");
jc.getActionMap().put("D pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("D pressed");
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "D released");
jc.getActionMap().put("D released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("D released");
}
});
}
We would call this method like:
JPanel ourPanel=new JPanel();
...
addKeyBindings(ourPanel);//adds keybindings to the panel
Other suggestions on code
Always create and manipulate Swing components on Event Dispatch Thread, via SwingUtilities.invokeLater(Runnable r) block
Dont extend JFrame class unnecessarily
Dont implement interfaces on a class unless the class will be used for that purpose, or other classes need access to the interfaces methods.
As mentioned by #AndrewThompson, dont use multiple JFrames, either swap the rest for JDialog, or use CardLayout. See here for an example.

Categories

Resources