import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class displayFullScreen extends JFrame {
private JLabel alarmMessage = new JLabel("Alarm !");
private JPanel panel = new JPanel();
public displayFullScreen() {
setUndecorated(true);
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
alarmMessage.setText("Alarm !");
alarmMessage.setFont(new Font("Cambria",Font.BOLD,100));
alarmMessage.setForeground(Color.CYAN);
panel.add(alarmMessage);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width,screenSize.height);
panel.setBackground(Color.black);
add(panel);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) { // handler
if(ke.getKeyCode() == ke.VK_ESCAPE) {
System.out.println("escaped ?");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // trying to close
} else {
System.out.println("not escaped");
}
}
});
}
public static void main(String args[]) {
new displayFullScreen().setVisible(true);
}
}
I have set a listener for the keys .When ever i press ESC key why doesn't the frame close ?
The invocation of setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); does not close the frame, it will define the behaviour when the windows decoration [X] close button is pressed (Which you have disabled for full screen).
You could replace this with setVisible(false); or exit your programm.
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
public abstract class EscapableFrame extends JFrame
{
public EscapableFrame()
{
// on ESC key close frame
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel"); //$NON-NLS-1$
getRootPane().getActionMap().put("Cancel", new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
//framename.setVisible(false);
}
});
}
}
Use dispose() method.
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) { // handler
if(ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.out.println("escaped ?");
displayFullScreen.this.dispose();
}
else {
System.out.println("not escaped");
}
}
});
You are not closing your your frame at esc key. You are just setting its default close operation so you must write
System.exit(0);
or
dispose();
instead of
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
If you don't want to exit the application then use setVisible(false).
Tip:
VK_ESCAPE is static filed of KeyEvent class so instead of ke.VK_ESCAPE you can write KeyEvent.VK_ESCAPE.
Related
I am currently making a volume slider for my game. I want to have a toggleable UI where the player can set their preferred volume, then resume playing.
Disclaimer: This is from a group project where everybody is a first timer to making a more complex game, and we're mainly using this project to gain experience. I'm sure this is full of bad practice and inefficiency, but at the end of the day we're making this mostly for fun.
Here's what it should look like:
Here's the minimal reproducible example in 3 classes:
Main
Intermediate
Slider
Main
import javax.swing.*;
import java.awt.*;
public class Main
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
Intermediate inte = new Intermediate(frame);
frame.add(inte);
frame.setPreferredSize(new Dimension(900,600));
frame.pack();
frame.setVisible(true);
}
}
Intermediate
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class Intermediate extends JPanel
{
boolean b = false;
private Timer tim;
private JFrame f;
private Slider s;
public Intermediate(JFrame f)
{
super();
this.f=f;
tim = new Timer(10, new NewFrameListener());
tim.start();
}
public void stop()
{
tim.stop();
}
public void restart()
{
tim.start();
}
public void handleInputs()
{
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "pressed left");
this.getActionMap().put("pressed left", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("left");
}
});
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_U, 0, false), "pressed u");
this.getActionMap().put("pressed u", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(b)
{
restart();
b=false;
}
else
{
s = new Slider();
f.getContentPane().add(s);
f.setVisible(true);
stop();
b=true;
}
}
});
}
#Override
protected void paintComponent(Graphics g)
{
g.setColor(Color.gray);
super.paintComponent(g);
g.fillRect(0,0,900,600);
}
class NewFrameListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae)
{
// System.out.println("woo");
handleInputs();
repaint();
}
}
}
Slider
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class Slider extends JPanel implements ChangeListener {
public Slider()
{
JPanel container = new JPanel();
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 10, 5);
slider.addChangeListener(this);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setSize(200, 50);
slider.setBounds(200,200, 200, 50);
slider.setEnabled(true);
container.setBackground(Color.GRAY);
container.add(slider);
this.add(container);
}
#Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
System.out.println(source.getValue());
}
}
}
The JPanel called container in Slider is completely optional, the functionality remains the same, but then the Slider would fill the whole frame.
The expected behaviour is that the visibility of the frame that contains the slider is toggled every time 'u' is pressed. And that does work, until the slider is interacted with. When that happens every input seems to be suppressed and the frame can no longer be hidden. No errors or exceptions thrown when this happens either.
What is causing this behaviour? How can it fixed?
Edit: Added the relevant code of newFrameTimer and NewFrameListener, as well as repaint and paintComponent.
Edit2: I have now tried placing the Slider's JPanel in an other JPanel to be able to set its size, and I can now interact with the outer JPanel without the action listener ceasing to function, but the moment I touch the Slider it breaks again.
Furthermore I tried disabling the change listener portion of the slider, but that still doesn't fix the issue.
Edit3: I have now also recreated this behaviour independently of the game, and the same thing happens. An input causes the slider (or a JPanel containing the slider) to get added to the frame, at this point the the slider can be toggled, using keyboard inputs, but as soon as the slider is interacted with all keyboard input to the outer Panel is lost. I'll try to see if pressing a button or something similar can restore the expected functionality.
The problem is now resolved, thanks to everyone who commented, special thanks to #macrofox #Abra and #Andrew Thompson .
The cause of the issue was that the when the Slider is in focus Intermediate's listeners are basically disabled, so to return to the game I have to disable the Slider's visibility in a KeyListener of its own.
Side note: In order to resume the game in one press of 'u' the input map in Intermediate for 'u' has to be on onKeyRelease = true
here are the 3 classes in their properly working states:
Main
(unchanged)
import javax.swing.*;
import java.awt.*;
public class Main
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
Intermediate inte = new Intermediate(frame);
frame.add(inte);
frame.setPreferredSize(new Dimension(900,600));
frame.pack();
frame.setVisible(true);
}
}
Intermediate
onKeyRelease = true for "u"'s input map
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Intermediate extends JPanel
{
boolean b = false;
private Timer tim;
private JFrame f;
private Slider s;
public Intermediate(JFrame f)
{
super();
this.f=f;
tim = new Timer(10, new NewFrameListener());
tim.start();
}
public void stop()
{
tim.stop();
}
public void restart()
{
tim.start();
}
public void handleInputs()
{
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "pressed left");
this.getActionMap().put("pressed left", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("left");
}
});
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_U, 0, true), "pressed u");
this.getActionMap().put("pressed u", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(b)
{
restart();
b=false;
remove(s);
}
else
{
s = new Slider();
f.getContentPane().add(s);
f.setVisible(true);
stop();
b=true;
}
}
});
}
#Override
protected void paintComponent(Graphics g)
{
g.setColor(Color.gray);
super.paintComponent(g);
g.fillRect(0,0,900,600);
}
class NewFrameListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae)
{
// System.out.println("woo");
handleInputs();
repaint();
}
}
}
Slider
the slider itself has the whole class Slider added to it as a key listener
now also implements KeyListener, if the key pressed is 'u', visibility of the JPanel is disabled
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Slider extends JPanel implements ChangeListener, KeyListener {
public Slider()
{
JPanel container = new JPanel();
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 10, 5);
slider.addChangeListener(this);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setSize(200, 50);
slider.setBounds(200,200, 200, 50);
slider.setEnabled(true);
//container.setBackground(Color.GRAY);
//container.add(slider);
slider.addKeyListener(this);
this.add(slider);
}
#Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
System.out.println(source.getValue());
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_U){this.setVisible(false);}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
I want do display a text filed in a popup. When popup is completly over the application frame (MediumWeightPopup) - all works fine, but when a part of popup is outside of frame (HeavyWeightPopup) it cannot be focused. In this case caret is invisible and no text input is possible.
Here is my code:
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class PopupTest {
public static void main(String[] args) {
JFrame frm = new JFrame("Popup test");
JPanel p = new JPanel();
p.addMouseListener(new MouseAdapter() {
Popup pop;
#Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
if (pop != null) {
pop.hide();
}
JPanel popupPanel = new JPanel(new BorderLayout());
JTextField field = new JTextField(20);
popupPanel.add(field);
pop = PopupFactory.getSharedInstance().getPopup(p, popupPanel, e.getXOnScreen(), e.getYOnScreen());
pop.show();
System.out.println("Popup type: " + pop.getClass().getName());
System.out.println("Can get focus? " + field.requestFocusInWindow());
}
}
});
frm.add(p);
frm.setSize(500, 300);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}
On right click near to right border of window I get a non-focusable text field. The same problem I get with any other component in popup that allows key control (for example JTable).
How can I focus a component in a HeavyWeightPopup?
I also struggled with this years ago. I can't figure out how to give initial focus to a component on the popup. Here are some of my questions/observations:
What is the Popup class used for?
I always thought that a Popup should have some basic functionality, such as the pupup should close when:
a) the escape key is pressed
b) the popup loses focus
The popup class provides none of the above functionality and in fact seems to require some obscure code to even get the keyboard focus to work properly.
Using a JWindow seems to provide the same functionality as a Popup.
JPopupMenu seems to support both of the above requirements.
Run the following program:
a) click on each of the buttons
b) click on an empty part of the frame
It appears to me that whenever you need a "popup" you should use a JPopupMenu.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class PopupTest extends JFrame
{
String[] numbers = { "one", "two", "three", "four", "five" };
public PopupTest()
{
getContentPane().setLayout( new FlowLayout() );
getContentPane().setBackground(Color.YELLOW);
JButton popup = new JButton("Popup as Popup");
popup.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
popupPopup(e);
}
});
getContentPane().add(popup);
JButton window = new JButton("Window as Popup");
window.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
windowPopup(e);
}
});
getContentPane().add(window);
JButton menu = new JButton("PopupMenu as Popup");
menu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
menuPopup(e);
}
});
getContentPane().add(menu);
}
private void popupPopup(ActionEvent e)
{
JList list = new JList(numbers);
list.setSelectedIndex(0);
PopupFactory factory = PopupFactory.getSharedInstance();
Popup popup = factory.getPopup(this, list, getLocation().x, getLocation().y+100);
//popup.show();
Window window = SwingUtilities.windowForComponent(list);
if (window != null)
{
window.setFocusableWindowState(true);
}
popup.show();
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(list);
}
private void windowPopup(ActionEvent e)
{
JList list = new JList(numbers);
list.setSelectedIndex(0);
JWindow window = new JWindow(this);
window.getContentPane().add(list);
window.pack();
window.setVisible(true);
window.setLocation(getLocation().x + 200, getLocation().y+100);
window.addWindowListener( new WindowAdapter()
{
public void windowDeactivated(WindowEvent e)
{
System.out.println("deactivated");
}
});
}
private void menuPopup(ActionEvent e)
{
JList list = new JList(numbers);
list.setSelectedIndex(0);
JPopupMenu menu = new JPopupMenu();
menu.add( new JTextField(10) );
menu.add( list );
menu.show((Component)e.getSource(), 0, 100);
}
private static void createAndShowGUI()
{
JFrame frame = new PopupTest();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(500, 200);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
Edit:
Based on Sergiy's answer, this code was close to working. The difference in the popupPopup() method is that the show() method needs to be invoked AFTER the window is made focusable. Code updated to reflect this change.
Source code analyse brought me another solution
pop = PopupFactory.getSharedInstance().getPopup(p, popupPanel, e.getXOnScreen(), e.getYOnScreen());
// some new stuff
Window win = SwingUtilities.windowForComponent(popupPanel);
if (win instanceof JWindow && win.getType() == Window.Type.POPUP) {
win.setFocusableWindowState(true);
}
// continue old stuff
pop.show();
So the complete example looks like
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class PopupTest {
public static void main(String[] args) {
JFrame frm = new JFrame("Popup test");
JPanel p = new JPanel();
p.addMouseListener(new MouseAdapter() {
Popup pop;
#Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
if (pop != null) {
pop.hide();
}
JPanel popupPanel = new JPanel(new BorderLayout());
JTextField field = new JTextField(20);
popupPanel.add(field);
pop = PopupFactory.getSharedInstance().getPopup(p, popupPanel, e.getXOnScreen(), e.getYOnScreen());
Window win = SwingUtilities.windowForComponent(popupPanel);
if (win instanceof JWindow && win.getType() == Window.Type.POPUP) {
win.setFocusableWindowState(true);
}
pop.show();
System.out.println("Popup type: " + pop.getClass().getName());
System.out.println("Can get focus? " + field.requestFocusInWindow());
}
}
});
frm.add(p);
frm.setSize(500, 300);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}
Interesting: the call field.requestFocusInWindow() still returns false, but field gets focus anyway.
BTW: this solution is also better for me because in my real code I get the Popup from a JComboBox (my goal is to create JTableComboBox with a table in popup and an optional filter field on top of the table).
I would like to create the simple window where one button will be.
When I will press him is supposed to be printed out "test" and when I will press F5 "F5".
I don't know what I am doing badly
I apologize for my English I still studying
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Okienko extends JFrame implements ActionListener , KeyListener
{
static Okienko frame;
JButton bTest;
public Okienko()
{
setLayout(null);
frame = this;
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setTitle("test");
frame.setLocation(150, 150);
frame.setSize(200, 400);
bTest = new JButton("Test");
bTest.setBounds(20, 50, 120, 20);
frame.add(bTest);
bTest.addActionListener(this);
frame.addKeyListener(this);
//frame.setFocusable(false);
//frame.requestFocus();
requestFocusInWindow();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == bTest)
{
System.out.println("Test");
}
}
#Override
public void keyPressed(KeyEvent e)
{
int id = e.getKeyCode();
if (id == KeyEvent.VK_ESCAPE)
{
this.dispose();
}
if (id == KeyEvent.VK_F5)
{
System.out.println("F5");
}
}
#Override
public void keyReleased(KeyEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
public static void main(String[] args)
{
new Okienko();
}
}
For example, you can enable keyboard focus for a component by calling the setFocusable(true) method on it.
Add in constructor:
setFocusable(true);
More info here: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
add
btest.setFocusable(false);
loadingLab=new JLabel("The name is being saved..");
loadPanel.add(loadingLab);
submitBttn=new JButton("Submit");
submitBttn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Submit Button Clicked!!");
try {
//something is wrong in here as it throws an exception
//what is wrong?
frame.setUndecorated(false);
frame.setOpacity(0.55f);
//when above both lines are commented, the code works fine
//but doesnt have transparency
frame.add(loadPanel,BorderLayout.SOUTH);
frame.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
I am trying to display transparent JFrame when "submit" button is clicked which displays panel with a JLabel...
I have tried using setOpacity(0.55f), but it throws exception.. what am i doing wrong?
Unfortunately I think there's no way to keep the system window decoration, you will probably have to go with the default one. Since I'm not 100% sure if you want to toggle the opacity of the whole frame or just the frame's background, I've included both functions in my example. (mKorbels answer help you more if you don't want to have a decoration)
Code:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class TransparentExample extends JFrame {
public TransparentExample() {
super("TransparentExample");
Color defaultBackground = getBackground();
float defaultOpacity = getOpacity();
JToggleButton button1 = new JToggleButton("Toggle background transparency");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button1.isSelected()) {
setBackground(new Color(defaultBackground.getRed(), defaultBackground.getGreen(),
defaultBackground.getBlue(), 150));
} else {
setBackground(defaultBackground);
}
}
});
JToggleButton button2 = new JToggleButton("Toggle opacity of whole frame");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
if (button2.isSelected()) {
setOpacity(0.55f);
} else {
setOpacity(defaultOpacity);
}
setVisible(true);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(button1);
getContentPane().add(button2);
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
TransparentExample frame = new TransparentExample();
frame.setVisible(true);
}
});
}
}
Picture of frame with no togglebutton selected:
Picture of frame with the first togglebutton selected:
Picture of frame with the second togglebutton selected:
#Programmer007 wrote - the exception is "
java.awt.IllegalComponentStateException: The frame is displayable."
please where I can't see any, for more info about the possible exceptions to read,
as mentioned no idea, everything is about your effort, transformed to the SSCCE / MCVE, short, runnable, compilable
.
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class GenericForm extends JDialog {
private static final long serialVersionUID = 1L;
private Timer timer;
private JDialog dialog = new JDialog();
private int count = 0;
public GenericForm() {
dialog.setSize(400, 300);
dialog.setUndecorated(true);
dialog.setOpacity(0.5f);
dialog.setName("Toggling with opacity");
dialog.getContentPane().setBackground(Color.RED);
dialog.setLocation(150, 150);
dialog.setVisible(true);
timer = new javax.swing.Timer(1500, updateCol());
timer.setRepeats(true);
timer.start();
}
private Action updateCol() {
return new AbstractAction("Hello World") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
boolean bol = dialog.getOpacity() < 0.55f;
count += 1;
if (count < 10) {
if (bol) {
dialog.setOpacity(1.0f);
dialog.getContentPane().setBackground(Color.WHITE);
} else {
dialog.setOpacity(0.5f);
dialog.getContentPane().setBackground(Color.RED);
}
} else {
System.exit(0);
}
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GenericForm();
}
});
}
}
public class ClickButtonClass implements ActionListener
{
public void actionPerformed(ActionEvent cbc)
{
clickcounter++;
clicklabel.setText("Clicks: "+clickcounter);
}
}
I did this code for counting clicks. But it only counts left mouse clicks. How do I add right mouse clicks too?
Use MouseListener. Here is an example:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
JLabel label = new JLabel("click me");
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent me) {
if (SwingUtilities.isRightMouseButton(me)) {
System.out.println("right click");
} else {
System.out.println("left click");
}
});
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
Don't use an ActionListener.
Instead you should be using a MouseListener. Read the section from the Swing tutorial on How to Write a MouseListener for more information and examples.
To count rightclicks:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Demo extends Frame {
Integer counter=0;
Button btn;
Label label;
public Demo() {
setLayout(new FlowLayout());
btn = new Button("OK");
label= new Label("Number of rightclicks: "+counter);
btn.addMouseListener(new MouseAdapter(){
public void mouseClicked (MouseEvent e) {
if (e.getModifiers() == MouseEvent.BUTTON3_MASK) {
counter++;
label.setText("Number of rightclicks: " +counter.toString());} }
});
add(btn);
add(label);
setSize(300,300);
setVisible(true);
}
public static void main(String args[]) {
new Demo();
}
}