Is it possible to make hover effect on images using graphics? - java

I am trying to make hover effect on multiple images in Swing using graphics, I know this can be done by using CSS but confused to make this effect in Java, can anybody help me?

Yes, it is quite possible to do that.
Assume you have a JPanel with an image inside it that you want to change every time the user hovers over it. The code would be something like this:
JPanel panel = new JPanel(); // create a JPanel
this.setupGI(panel); // prepare your background
panel.addMouseListener(new MouseHandler()); // add a listener
this.getContentPane.add(panel); // add it to JApplet / JFrame
This is to add the listener where MouseHandler will be your custom handler class.
class MouseHandler extends java.awt.event.MouseAdapter{
#Override public void mouseEntered(MouseEvent e){
// your logic here
}
#Override public void mouseExited(MouseEvent e){
//
}
}
Now, how the MouseHandler class will get access to the JPanel, well that is up to you. Usually, I make the handler class a sub-class so it has access to all the methods, fields of the enclosing class. Alternatively, you can make getter and setter methods. It is up to you.
More here: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

Use MouseListener with events mouseEntered and mouseExited.

Related

How i can access method from jframe to jpanel?

In my btcFrame class I have the method
private void closeButtonMouseClicked(MouseEvent evt){
this.dispose();
}
In my BtcTitleBarPanel I have in button for that I tend to close the frame. In the constructor I am adding my listener to closeButton like below.
closeButton.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent evt){
closeButtonMouseClicked(evt);
}
});
Problem is I cannot reach closeButtonMouseClicked method within the panel. How should I be doing to solve this?
Images in case.
Methods from jframe
Methods in jpanel
I would add a getter within the Panel for the closeButton. After initializing the Panel in the frame I would add the listener to button within the Frame. Like, btcPanel.getCloseButton().addActionListener(new ...); and within this action listener you could close the frame, like btcFrame.this.dispose()
Though I am not sure if that is a good practise, I almost always create new classes for listening events, but in this case of yours maybe helpful.
PS(Out of topic): You should see how to name classes and methods, your
naming style is wrong.(i.e classes starts with Capital etc.)

How to detect that a button is clicked inside a JFrame in java

I'm working on a little game in Java and I have a class that is extended JFrame and that is the interface of my game. I have an other class that instantiate my First class and it needs to when a button is clicked and which one. How do I do that?
Check out EventListeners. They may help you https://docs.oracle.com/javase/tutorial/uiswing/events/intro.html
this is an example of how you can detect the click inside a JFrame:
myJFrame.getContentPane().addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Clickin' =)");
}
});

Refresh java program with Button

I am trying to make a refresh button that will essentially restart the program when ever I click the button. I don't know how I should go about doing this.
I've place the Graphical User Interface i decided to use do complete this action. Any and all help would be greatly appreciated.
package pdfView;
import javax.swing.*;
import java.awt.*;
public class View extends JFrame {
public View() {
super("PDF Viewer");
setLookAndFeel();
setSize(500, 125);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
JTextField Search = new JTextField ("Search", 29);
JButton Search1 = new JButton("Search");
//this is where i have the button
JButton ReFresh = new JButton("ReFresh");
add(Search);
add(Search1);
add(ReFresh);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.squing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc){
}
}
public static void main(String[] args) {
View pdf = new View();
}
}
What do you mean by refresh or restart?
Do you mean:
Let the application be as it is, just update what it's showing?
Really restart the application?
Updating what the application is showing
You first need to decide what actually should cause your application to refresh. You already talked about a Button. The mechanism for activating something like a button is called Action. You can do that stuff manually, using an ActionListener, or you could extend AbstractAction, which is what I recommend. Extending AbstractAction allows you to use the same logical action something in more than one location on the UI. Look at typical applications, they offer Cut/Copy/Paste through menu, toolbar, popupmenu and keyboard shortcuts. The simplest way to achieve this in Java is using Action by extending AbstractAction.
The methods you need to call to update your application are invalidate(), validate() or repaint().
Restarting an application
So you want to run through main() again? That should actually not be required, unless you have an application that supports updating itself. Even then it can sometimes be avoided by smart usage of a ClassLoader.
Some more notes on your code
Usage by extension anti-pattern
I wouldn't extend JFrame just to display a window on the screen. Usage by extension is an anti-pattern. You don't need to extend JFrame to get a JFrame displayed on the screen and do what you want.
Referring static members
I would refer to constants via their original declaration. I.e. I'd refer to EXIT_ON_CLOSE via WindowConstants.EXIT_ON_CLOSE, not JFrame.EXIT_ON_CLOSE.
Typo
You have a typo in your UIManager.setLookAndFeel() code. Search for swing and you will see the typo.
Exception information
You might actually want to print the exception to stderr using exc.printStackTrace() instead of ignoring it completely, because when you have a typo in the LaF class name, as you do, and you don't print the exception, you might actually not come to know what's going wrong.
Sequence of widget construction and UIManager.setLookAndFeel()
The sequence of UIManager.setLookAndFeel() and the effective new JFrame() via super(...) does not guarantee you that the whole UI will be in Nimbus, parts of it might still be in Metal. I recommend to set the LaF before even constructing the first widget, to be on the safe side. As far as I remember, it's not guaranteed that changing the LaF after component construction has an effect, unless you tell the UIManager to update the LaF. See also this quote from the documentation of UIManager:
Once the look and feel has been changed it is imperative to invoke updateUI on all JComponents. The method SwingUtilities.updateComponentTreeUI(java.awt.Component) makes it easy to apply updateUI to a containment hierarchy. Refer to it for details. The exact behavior of not invoking updateUI after changing the look and feel is unspecified. It is very possible to receive unexpected exceptions, painting problems, or worse.
http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html
setSize() vs. pack() with a little help of Insets and Border
Instead of setting the size manually, you might want to play with Insets or Border and JFrame.pack() in order to get a decent layout of your window. Setting the size manually assumes that you know a lot about the screen resolution and the font size of the user.
The pack() method performs automatic size calculation based on the contents. Insets and Border allow you to create some space and borders, even with some designs or labels, around components so they wouldn't be cramped tightly in a window but be nicely spaced.
First you have to assign an actionListener to the ReFresh Jbutton.
You can either implement the interface ActionListener to the class, and override the actionPerformed() method like this
public class View extends JFrame implements ActionListener{
private JButton ReFresh;
public View() {
super("PDF Viewer");
setLookAndFeel();
setSize(500, 125);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
JTextField Search = new JTextField ("Search", 29);
JButton Search1 = new JButton("Search");
//this is where i have the button
ReFresh = new JButton("ReFresh");
ReFresh.addActionListener(this);
add(Search);
add(Search1);
add(ReFresh);
setVisible(true);
}
private void setLookAndFeel() { //right way for nimbus: http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.equals(ReFresh))
{
super.repaint();
}
}}
public static void main(String[] args) {
View pdf = new View();
}
Or you can do inline assignment to addActionListener, like this
ReFresh.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
super.repaint();
}
});
You can try these methods to refresh/reload the JFrame,
invalidate();
validate();
repaint();
you can also use dispose(); and then new View(); to create the new JFrame, but in this sequence it will close the window and create new one.
or you can even try setVisible(false); then setVisible(true);
I recommend the first 3.

Displaying a JPanel on JFrame by a label click

I have tried it over and over.Its not working.When I click the lablel, nothing happens.
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt)
{
setLayout(new BorderLayout());
JPanel o = new JPanel ();
o.setPreferredSize(new Dimension(122,200));
o.setBackground(Color.red);
add(o,BroderLayout.CENTER);
// TODO add your handling code here:
}
Looks a stupid question, but, are you sure that your method is getting called? Is your object registered as an event listener of this label?
Just to be sure, you should implement the MouseListener interface:
public class YourClass () implements MouseListener{
public YourClass(){
...
label.addListener(this);
}
// and then implement the method to handle the event
public void mouseClicked(MouseEvent e) {
// TODO: Handle the event
}
}
jLabel1MouseClicked does not look like the event handler method
EDIT: By the way, you may want to implement the other methods in this interface, even if you don't need them. Check the documentation: MouseListener example
if the Listener is implemented correctly, then you should change this
o.setPreferredSize(new Dimension(122,200));
with this
o.setSize(122,200);
you can put a setVisible method too, but it should work without it, too
I Think you are using Netbeans, If yes then the method you showed is auto-generated which means that it has correctly implemented Listeners in it's Auto-Generated Code Segment, well for now this means that you have error in Showing JPanel not in implementing listener, so I found some suggestions for you,
you have written BroderLayout but its BorderLayout but this seems to be a typo when posting Question.
Secondly you are not updating your frame, just adding the JPanel is not enough for showing it, so Add this code, this.revalidate();
so finally your block code should be like this,
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt)
{
setLayout(new BorderLayout());
JPanel o = new JPanel ();
o.setPreferredSize(new Dimension(122,200));
o.setBackground(Color.red);
add(o,BorderLayout.CENTER);
revalidate();
}

How to switch JPanels from different classes

I have three classes one JFrame class and two JPanel classes. I have added the intial JPanel to the JFrame like so
public JFrame() {
add(new 1stPanel(this));
setVisible(true);
setLayout(null);
}
Then i want to use an actionlistener on a button in the 1st panel to remove it and add the other panel which is in another class. I tried giving each class a variable and using the simple remove() and add() like this:
private 1stpanel 1p;
private 2ndpanel 2p;
btn.addActionListener((new ActionListener(){
public void actionPerformed(ActionEvent e)
{
remove(1p);
add(2p);
validate();
repaint();
}
}));
that doesn't work i have also tried using JFrame.remove(1p) but that doesn't work either. When i do removeAll() it gets rid of everything in the 1stpanel JPanel but then i can't add the 2ndpanel.
What code can i use to take out the 1st panel or 1stpanel class and add the 2nd panel which is in another class.
Thanks for the help in advance.
Try to use CardLayout and swap cards (panels).
Could be you problem is the creation add(new 1stPanel(this)). You add a local variable but then use fields of class.
your code lines
remove(1p);
add(2p);
validate();
repaint();
which you are calling inside the action listener are being called on the this object which I suspect is the JPanel itself. If it is so define a method in the class that is extending the JFrame, place these codes inside that method, and on action event call that method.

Categories