I had a problem while calling two mouse events, one into the other. I wanted to show a second frame (frame2) when the user clicks on a component (component1) from the first frame (frame1), then returns to the previous frame (frame1) if the component2 is clicked on. All this using one file.
This is what I wrote:
component1.addMouseListener(this on);
#Override
public void mouseClicked(MouseEvent e)
{
if(e.getSource() == component1)
{
frame1.dispose();
frame2.setVisible(true);
component2.addMouseListener(new MouseAdapter() {
public void mouseClicked() {
frame2.dispose();
frame1.setVisible(true);
}
});
}
}
The first event works, but not the second.
Thank you for answering.
Here is a fully functional example where there are 2 frames, each with a label that, when clicked, hides one frame and shows the other, done in Java 10. See if this works for you and explain how your code differs from this. Note that I only created 2 MouseListeners, one for each frame. I did not recreate the MouseListener in the other MouseListener's code. Also, I did not dispose the frame, which will likely cause problems. If I had disposed frame1, I would most likely have to create a new JFrame and assign it to the frame1 instance member.
Please note you have to click on the label itself, not somewhere else on the frame.
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class TwoFrames {
public static void main(String[] args) {
TwoFrames twoFrames = new TwoFrames();
twoFrames.start();
}
private void start() {
setupFrames();
}
JFrame frame1 = new JFrame("Frame 1"),
frame2 = new JFrame("Frame 2");
JLabel component1 = new JLabel("Click me 1"),
component2 = new JLabel("Click me 2");
private void setupFrames() {
frame1.getContentPane().add(component1);
frame2.getContentPane().add(component2);
component1.setOpaque(true);
component2.setOpaque(true);
component1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
frame1.setVisible(false);
frame2.setVisible(true);
}
});
component2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
frame2.setVisible(false);
frame1.setVisible(true);
}
});
frame1.setSize(300, 300);
frame2.setSize(400, 400);
frame1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(() -> frame1.setVisible(true));
}
}
The dispose() method actually destroys the window and so, frame1 should become null and you are most likely getting a null pointer exception.
Consider calling frame1.setVisible(false) and frame2.setVisible(false) instead of the dispose() method.
Also, you could consider using to separate mouse listener objects instead of adding a new mouse listener to component2 when component1 is clicked.
Related
I'm making a program that has a popup menu with two buttons, one of which should close the popup menu, but I have no idea how to do that and googling hasn't gone too well.
I've tried using popup.hide() but then the menu wouldn't come back, despite doing so when I tried just moving the popup. It also required me to put a SuppressWarning in that case and it took a few seconds for it to close at all. Is there any better way of doing it?
I'm not sure what kind of code is relevant, but here's the relevant buttons and their roles in this(I skipped all the creating the GUI parts that didn't seem relevant, everything looks good and I know that the buttons are working):
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
interface CustomButton {
JButton create();
void react(JPopupMenu popup, JFrame frame);
}
class ErrandsButton implements CustomButton {
private JButton errands = new JButton("Errands");
public JButton create() {
return errands;
}
public void react(JPopupMenu popup, JFrame frame) {
errands.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
popup.show(frame, 120, 65);
}
});
}
}
class Test {
static JFrame frame = new JFrame("List");
static CustomButton errands = new ErrandsButton();
static JButton cancelTask = new JButton("Cancel");
static JPopupMenu popup = new JPopupMenu();
static void cancelTask() {
cancelTask.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
popup.hide();
}
});
}
public static void main(String args[]) {
createInterface();
cancelTask();
errands.react(popup, frame);
}
static void createInterface() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JPanel popup1 = new JPanel();
JPanel button = new JPanel();
popup1.add(cancelTask);
popup.add(popup1);
frame.add(popup);
button.add(errands.create());
frame.getContentPane().add(BorderLayout.CENTER, button);
frame.setVisible(true);
}
}
Use popup.setVisible(true) and popup.setVisible(false).
frame.add(popup); is the problem. Do not add a JPopupMenu to a Container. Instead, use setComponentPopupMenu.
Alternatively, you could do the work yourself by adding a MouseListener whose mousePressed, mouseReleased and mouseClicked methods call isPopupTrigger and show. (It is vital that you do this in all three of those methods—different platforms have different conditions for showing popup menus.)
But really, using setComponentPopupMenu is easier.
I have a jframe that includes JButton.I have six buttons in this frame, but I don't know how to define action listener for this buttons.please help to solve this problem.
First you have to import the package java.awt.event.* to enable events. After the class name you have to add implements ActionListener so that the class can handle events. When you have created the buttons you have to add an actionlistener to each button. Since you haven't showed which code you use I make an example with a simple program that counts votes, if the user clicks the yesButton the votes are increased with 1 and if the user clicks the noButton the votes are decreased with 1.
Here is the code to add an ActionListener to each button:
yesButton.addActionListener(this);
noButton.addActionListener(this);
Then write the following code to handle the events:
public void actionPerformed(ActionEvent e) {
JButton src = (JButton) e.getSource();
if(src.getActionCommand().equals("Yes")) {
yesCount++;
} else {
noCount++;
}
label.setText("Difference: " + (yesCount - noCount));
}
If you have 6 buttons you need to have an if statement and then 5 "else if" statements instead of only an if and an else statement.
Have a look at the Java tutorials on how to use ActionListeners:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Here's a simple example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Hello extends JPanel implements ActionListener {
JButton button;
public Hello() {
super(new BorderLayout());
button = new JButton("Say Hello");
button.setPreferredSize(new Dimension(180, 80));
add(button, BorderLayout.CENTER);
button.addActionListener(this); // This is how you add the listener
}
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e) {
System.out.println("Hello world!");
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Hello");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Hello();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
buttons have a method called addActionListener, use that for adding the action listener that you can implement for the click...
Example:
dummyButton = new JButton("Click Me!"); // construct a JButton
add(dummyButton); // add the button to the JFrame
dummyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(" TODO Auto-generated method stub");
}
});
It's really simple.
I suppose you have an instance of your button, right? Let's say that instance is called myButton.
You can just add an action listener by calling addActionListener:
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do whatever you like here
}
});
Protip: next time you don't know what method to call, just type the instance name and .. Then, your IDE will show you all the methods you can call, unless you are not using an IDE. If that is the case, download one.
I'm working on a program which has multiple JFrame and JDialog windows.
I have a JFrame which contains a button, when I click on this button a JDialog window opens up. In this JDialog windows there is another button, which when is clicked it opens up a second JDialog window. In the second JDialog window I have a last button.
What I want to do is to close both JDialog windows and JFrame window when this last button is clicked.
This is how the opening order is:
JFrame Frame1;
JButton Button1;
JDialog Dialog1;
JButton Button2;
JDialog Dialog2;
JButton Button3;
Button1ActionPerformed(ActionEvent e){
new Dialog(Frame1Frame);
}
Button2ActionPerformed(ActionEvent e){
new Dialog2(Dialog1Frame)
}
Button3ActionPerformed(ActionEvent e){
//Here I wnat to add the code that closes JDialog2 JDialog1 and JFrame1 windows.
}
I have tried super.dispose(); but it doesn't work. Any ideas?
As shown here using Action, your actionPerformed() implementation can dispatch the WINDOW_CLOSING event to the desired Window instances.
#Override
public void actionPerformed(ActionEvent e) {
d1.dispatchEvent(new WindowEvent(d1, WindowEvent.WINDOW_CLOSING));
d2.dispatchEvent(new WindowEvent(d2, WindowEvent.WINDOW_CLOSING));
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
There may be better ways of doing this, but here is one general approach that might help.
In your code you create the windows but you do not store the reference to the windows you created into a variable. For example, you have:
JDialog Dialog1;
Then later, when you create the instance of Dialog1, you have this code:
Button1ActionPerformed(ActionEvent e){
new Dialog(Frame1Frame);
}
This means you have created the Dialog, but you have not retained a reference to the Dialog for later manipulation by your code. If you assign this value here, you should be able to manipulate it later.
If you change your implementation to:
Button1ActionPerformed(ActionEvent e){
Dialog1 = new Dialog(Frame1Frame);
}
Then later in your code you will have a reference to the Dialog in order to manipulate it,
Button3ActionPerformed(ActionEvent e){
Dialog1.dispose();
// you can manipulate the variables of the class from here and close other windows etc.
}
If you have the objects reference, you can do:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class Main
{
private static JFrame frame;
private static JButton buttonFrame;
private static JDialog dialog1;
private static JButton buttonDialog1;
private static JDialog dialog2;
private static JButton buttonDialog2;
public static void main(String[] args) {
/* frame */
frame = new JFrame("Main Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
buttonFrame = new JButton("open dialog 1");
buttonFrame.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
dialog1.setVisible(true);
}
});
frame.add(buttonFrame);
/* dialog 1 */
dialog1 = new JDialog(frame, "Dialog 1");
dialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog1.setSize(300, 300);
dialog1.setLocationRelativeTo(null);
buttonDialog1 = new JButton("open dialog 2");
buttonDialog1.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
dialog2.setVisible(true);
}
});
dialog1.add(buttonDialog1);
/* dialog 2 */
dialog2 = new JDialog(dialog1, "Dialog 2");
dialog2.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog2.setSize(200, 200);
dialog2.setLocationRelativeTo(null);
buttonDialog2 = new JButton("close all");
buttonDialog2.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
dialog2.dispose();
dialog1.dispose();
frame.dispose();
}
});
dialog2.add(buttonDialog2);
/* show frame */
frame.setVisible(true);
}
}
Otherwise you can use System.exit(0);:
buttonDialog2.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Closing multiple JFrame by another JFrame-
It is possible to close multiple windows, even non-static Java swing windows. Type below small code, step by step.
The below code is mainly for closing the First frame through the second open frame which has been opened by the same First frame.
*Make a **second class global variable** in the first-class & a **button global variable in first-class*
Class2 NiceApp1 = new Class2();
JToggleButton Nice=new JToggleButton("Nice One");
// *After the Class1 above code, you will need a close method. I use a jar of NiceApplication1 with class New Close you can use the same jar or very below close method and can call the close method. You will need to type the method in Class1, just type your **close method in the method**.*
public void method (){
NewClose NiceO = new NewClose();
NiceO.Close(this);
//or
Close();
}
*// Now make a **Button Global variable in Class2**.*
javax.swing.JToggleButton Zero = new javax.swing.JToggleButton();
*// Type in Class2 the below **method**.*
public void methodclass2(JToggleButton Nice){
Zero = Nice;
}
*//Now you will need to type the below code, type the below code in the **Class1 button action** by which you will open the Class2.*
Nice.addActionListener((ActionEvent e) -> {
method();
});
NiceApp1.methodclass2(Nice);
NiceApp1.setVisible(true);
*//Now just type a **single line code** in the second class, type anywhere from which you want to close Class1.*
Zero.doClick();
*//Now the **close method** if you don't have a close method.*
public void Close() {
WindowEvent winclosing = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winclosing);
}
**You have done now if you did the above process.
If you only want to close which opens secondly so by the only close method change the this into your frame variables.
You can also visit NiceApplication1.BlogSpot.Com.
You can use the above code. From Class2 after the button's click, you will see your previous Class1 window will close.**
I am making a jFrame that represents a go board. I want a click of a given button to change the color to represent placing a piece on the board. In my code below, I show a method that should be able to change the color of a button (it only changes the background of the whole frame). First question: Why is the button color not changing (this is not my bigger problem about changing color after click occurs, my preliminary issue is that the button color will not change). I do not get any errors, the button color just never changes.
public static void showBoard()
{
JFrame frame2 = new JFrame("Go Board");
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
for(int i = 19*19; i > 0; i--)
{
JButton firstButton = new JButton("");
firstButton.setBackground(Color.blue);
firstButton.setVisible(true);
firstButton.setContentAreaFilled(true);
firstButton.setOpaque(true);
firstButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
System.out.println("ddsd");
//int[] arr = findMove(0);
}
});
}
});
frame2.getContentPane().add(firstButton);
}
frame2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame2.setLayout(new GridLayout(19,19));
frame2.pack();
frame2.setVisible(true);
}
My second problem, getting the button to change color after being clicked, is presumably affected by the fact that I am not able to even change the button color. To get the button to change color after a click, I plan to put the button color change code inside the action listener.
So in summation, how can I change the color of the button after a click?
ANSWER:
The problem was the look and feel of my mac. Look to the checked answer for how to fix this if you have similar problem on your mac.
You don't need to call SwingUtilities.invokeLater inside your ActionListener, as the actionPerformed(ActionEvent) method will be invoked on the Event Thread already.
The following example demonstrates how to change a Button's background color when it's clicked on:
public class ChangeButtonColor implements Runnable {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
System.err.println("Cannot set LookAndFeel");
}
SwingUtilities.invokeLater(new ChangeButtonColor());
}
#Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
JButton button1 = new JButton("click me");
JButton button2 = new JButton("click me too");
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
((Component)source).setBackground(Color.RED);
}
}
};
button1.addActionListener(listener);
button2.addActionListener(listener);
frame.add(button1);
frame.add(button2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Please note that the ActionListener used here can be used for all buttons. There is no need to create a new instance of it for every button.
Why this code never prints "Hello2" ?
public class Test4 {
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel p = new JPanel();
f.getContentPane().add(p);
JLabel x = new JLabel("Hello");
p.add(x);
p.addComponentListener(new ComponentListener() {
public void componentResized(ComponentEvent arg0) {
System.err.println("Hello1");
}
public void componentMoved(ComponentEvent arg0) {
}
public void componentShown(ComponentEvent arg0) {
System.err.println("Hello2");
}
public void componentHidden(ComponentEvent arg0) {
}
});
f.setVisible(true);
f.pack();
}
}
I would guess that it's called when the visibility state of the actual object changes.
in this case, you change the visibility of the Frame, not of the Panel.
(by default, Frame starts hidden, but panels are visible)
try to add the listener to the frame.
AWT's definition of "visible" may be a bit counter-intuitive. From the Javadoc of java.awt.Component#isVisible:
"Components are initially visible, with the exception of top level components such as
Frame objects."
According to this description, p is already visible before you add the ComponentListener. In fact, you can verify this if you insert a
System.out.println(p.getVisible());
anywhere before you call f.setVisible(true). In that sense, the visibility is not changed when displaying the frame and hence componentShown(..) is not called.
From Java Tutorials
The component-hidden and
component-shown events occur only as
the result of calls to a Component 's
setVisible method. For example, a
window might be miniaturized into an
icon (iconified) without a
component-hidden event being fired.