How can I add an event to this code such that if i drag the slider, the number is displayed. Please, let me know as I am new to Java..
import javax.swing.*;
public class Slider extends JFrame {
JSlider pickNum = new JSlider(JSlider.HORIZONTAL, 0, 30, 5);
public Slider() {
super("Slider");
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pickNum.setMajorTickSpacing(10);
pickNum.setMinorTickSpacing(1);
pickNum.setPaintTicks(true);
pickNum.setPaintLabels(true);
getPointedValue();
this.add(pickNum);
this.setVisible(true);
}
public final int getPointedValue() {
int value;
value = pickNum.getValue();
return value;
}
public static void main(String[] args) {
Slider frame = new Slider();
int i;
i = frame.getPointedValue();
System.out.println("current value is:" + i);
}
}
See addChangeListener(ChangeListener), as well as How to Use Sliders & How to Write a Change Listener.
As a concrete example using ChangeListener, SpinSlider shows how to connect a JSlider and a JSpinner.
Related
I've created 2 JButtons.One of them has the function of a button and the other handles an image.I want that image to change when this button is clicked.So inserted the method repaint() and added a listener to the first JButton to change the image.When trying to add the listener or the event handler to the first JButton nothing happens.So the image doesn't change.Can anyone show me how can I insert this listener in a way that it works(changes the image when the button is clicked)?Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;
public class Back extends JFrame{
private Random ran;
private int value;
private JButton r;
private JButton c;
public Back(){
super("title");
ran = new Random();
value = nextValue();
setLayout(new FlowLayout());
r=new JButton("ROLL");
add(r);
Icon i=new ImageIcon(getClass().getResource("1.png"));
Icon img=new ImageIcon(getClass().getResource("2.png"));
c= new JButton(i);
if (value==1){
c= new JButton(i);
}
else if(value==2){
c= new JButton(img);
}
add(c);
thehandler hand=new thehandler(this);//konstruktori i handler merr nje instance te Background
r.addActionListener(hand);
c.addActionListener(hand);
}
private int nextValue() {
return Math.abs(ran.nextInt()) % 6 + 1 ;
}
public void roll() {
value = nextValue() ;
repaint() ;
}
public int getValue() {
return value ;
}
private class thehandler implements ActionListener{
private Back d;
thehandler(Back thisone) {
d = thisone ; }
public void actionPerformed(ActionEvent event) {
d.roll() ;
}
}
public static void main(String[] args) {
Back d = new Back() ;
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.getContentPane().setBackground(Color.GREEN);
d.setSize(700,500);
d.setVisible(true);
}
}
So, basically, all your code comes down to here...
public void roll() {
value = nextValue();
repaint();
}
This calculates a new random value and calls repaint. But nothing in your code is effected by value at the point in time it's called.
Instead, you need to update the state of some control, maybe something more like...
public void roll() {
value = nextValue();
Icon i = new ImageIcon(getClass().getResource("1.png"));
Icon img = new ImageIcon(getClass().getResource("2.png"));
if (value == 1) {
c.setIcon(i);
} else if (value == 2) {
c.setIcon(img);
}
}
The next thing I would do is store all your images in some kind of array or List to make it easier to access, then you could simply do something
like...
public void roll() {
value = nextValue();
c.setIcon(listOfImages.get(value - 1));
}
Maybe have a look at Java Swing Timer and Animation: how to put it together for a more detailed example
I have two frames (One main and one popup). On the main frame key & mouse listeners are added. Both work just fine. On the pop up there are 50 buttons. I have one action listener for all of them. It works fine. I also have key & mouse listeners. Mouse works. Key is flaky.
The same keyListener class used in main frame is added to the pop-up frame too.
As soon as the pop up shows, key listener works, once mouse click happens (Action listener kicks in) keylistener stops working. Please help. The code attached is a simplified version
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class key {
private static class toolsAction implements ActionListener {
public void actionPerformed (ActionEvent ae) {
log("Command " + Integer.parseInt(ae.getActionCommand()));
}
}
private static void log(String s) { System.out.println(s); }
private static class keyboardHandler implements KeyListener {
public void keyPressed( KeyEvent e) { log("KB Press called "); }
public void keyReleased(KeyEvent e) { log("KB Release called "); }
public void keyTyped (KeyEvent e) { log("KB Typed called "); }
}
public static void main(String [] args) {
JFrame pFrame = new JFrame("Frame");
pFrame.addKeyListener(new keyboardHandler());
Container pane = pFrame.getContentPane();
pane.setLayout(null);
pane.setVisible(true);
pFrame.setSize(650, 300);
pFrame.setVisible(true);
JButton[] buttons = new JButton[50];
toolsAction action = new toolsAction();
for (int i = 0; i < 50; i++) {
buttons[i] = new JButton("" + i);
buttons[i].setActionCommand("" + i);
buttons[i].addActionListener(action);
pane.add(buttons[i]);
buttons[i].setBounds(((i % 10) * 60), ((i / 10) * 40), 60, 40);
}
}
}
An alternative approach uses Action and key bindings. The example below binds 10 buttons to the number keys, also using the numbers as the MNEMONIC_KEY of each.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** #see http://stackoverflow.com/a/14182227/230513 */
public class Key {
public static final int SIZE = 10;
private static class ToolAction extends AbstractAction {
public ToolAction(int i) {
super(String.valueOf(i));
putValue(MNEMONIC_KEY, KeyEvent.VK_0 + i);
}
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand());
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Frame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, SIZE / 2));
for (int i = 0; i < SIZE; i++) {
final ToolAction toolAction = new ToolAction(i);
JButton b = new JButton(toolAction);
String name = b.getText();
b.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_0 + i, 0), name);
b.getActionMap().put(name, toolAction);
f.add(b);
}
f.pack();
f.setVisible(true);
}
});
}
}
The KeyListener will only be executed if the component, to which the listener is added, has the (keyboard) focus. If you click on another component, that component will become the focus and the keyboard events will be sent to its KeyListeners.
Not sure if that is the problem without seeing the code of the popup, but it's the problem in the posted code...
EDIT
you can add an AWTEventListener to the Toolkit to intercept all events independently of the focused component:
private static class AWTListener implements AWTEventListener {
#Override
public void eventDispatched(AWTEvent event) {
log("AWT: " + event);
}
};
...
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.addAWTEventListener(new AWTListener(), AWTEvent.KEY_EVENT_MASK);
I solved this problem by adding MouseMotionListener and in the mouseMoved method calling pFrame.requestFocusInWindow() & also adding focus request in the button's actionPerformed method.
Even with just one button in a frame as long as the ActionListener is added to the button, KeyListener does not work.
This is kludgy at best, but works for me. I would still love to hear from the community why my original code does not work.
I'm trying to write a game applet that responds to keys typed by the player. I'm trying to use key bindings to accomplish this. But I can't get it to work. The applet (what little of it there is, at the moment) seems to display correctly in Appletviewer, but nothing happens when I press keys. I haven't been able to test it in a browser, as it doesn't always display correctly in a browser.
I'm running Sun Java 6 on Ubuntu. I managed to find mention of a Ubuntu bug where iBus would block keyboard input to applets. However, I don't have iBus running, and I've been able to use keyboard input with other applets (not written by me).
Here is the code so far
public class AlxTestVersion extends JApplet {
private GridBagLayout layout;
private GridBagConstraints layoutConstraints;
private JPanel mainPanel;
public void init() {
this.setLayout ( new FlowLayout(FlowLayout.LEFT) );
//Main frame.
mainPanel = new JPanel();
layout = new GridBagLayout();
layoutConstraints = new GridBagConstraints();
layoutConstraints.anchor = GridBagConstraints.NORTHWEST;
layoutConstraints.fill = GridBagConstraints.NONE;
mainPanel.setLayout(layout);
mainPanel.setBackground(Color.pink);
getContentPane().add(mainPanel);
//Map display
JPanel leftPanel = new JPanel();
GlobalData.mainMap = new MapCanvas(9);
addComponent(GlobalData.mainMap, 0, 0, 1, 1);
/*
Define other components...
*/
}
public class MapCanvas extends JPanel {
private int tileSize;
private int mapTileWidth;
private int mapOffset;
private int mapDim;
private MapSquare screenTiles[];
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon testImage = new ImageIcon("tiles/test_land.gif");
int x,y;
for (x=0;x<mapTileWidth;x++) {
for (y=0;y<mapTileWidth;y++) {
g.drawImage(testImage.getImage(), x*tileSize + mapOffset, y*tileSize + mapOffset, this);
}
}
}
public MapCanvas(int numTiles) {
//Set up window
tileSize = 48;
mapTileWidth = numTiles;
mapOffset = 4;
mapDim = (tileSize * mapTileWidth) + (2 * mapOffset);
Dimension dim = new Dimension(mapDim, mapDim);
this.setPreferredSize(dim);
this.setMinimumSize(dim);
this.setMaximumSize(dim);
this.setLayout( new GridLayout(numTiles, numTiles, 0, 0) );
this.setBackground(Color.black);
screenTiles = new MapSquare[numTiles^2];
//Map-related actions
InputMap im = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = this.getActionMap();
AbstractAction north = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Just for testing", "testing",
JOptionPane.PLAIN_MESSAGE);
}
};
am.put("North", north);
im.put(KeyStroke.getKeyStroke('2'), "North");
im.put(KeyStroke.getKeyStroke('i'), "North");
}
}
About the only difference I can find between what I've used and working examples found in various places is they add the keystroke to the inputmap before mapping the keystroke to the action. I tried switching the order, but it didn't seems to have any effect.
Can anyone see what I'm doing wrong here? I just know I'm missing something obvious.
Your code doesn't work for me either (on a mac), until I click inside the window. Adding the following as the last thing in init() seems to help (but is not totally reliable):
GlobalData.mainMap.requestFocus();
Your applet window probably does not have the focus when you press the keys.
Try adding this to your init():
GlobalData.mainMap.addFocusListener(new FocusDebugger("canvas"));
this.addFocusListener(new FocusDebugger("applet"));
Here's FocusDebugger:
public static class FocusDebugger implements FocusListener {
private final String name;
public FocusDebugger(String name) {
this.name = name;
}
public void focusGained(FocusEvent focusEvent) {
System.out.println(name + ".focusGained");
}
public void focusLost(FocusEvent focusEvent) {
System.out.println(name+".focusLost");
}
}
Right now i change the background color of a button by using
button.setBackground(Color.WHITE);
That being an example.
But when i have a massive grid out of jbuttons (1000+), just running a for loop to change every buttons background is very, very slow. You can see the grid slowly turning white, box by box. I really don't want this
Is there a better way of changing every JButton on the grid to the same color at the same time?
This is how i am making the grid, the numbers used are only for example...
grid = new JPanel(new GridLayout(64, 64, 0, 0));
That's 4096 buttons, takes about 30+ seconds to change every button to the same color.
Edit 1: I need the buttons to be clickable, like when i click a button it turns blue for example. when all of the buttons are clicked, change the color of every button to white. Right now i have that working fine, but it is just slow to change the color of every button.
Edit 2: this is how i am changing the buttons:
new javax.swing.Timer(300, new ActionListener() {
int counter = 0;
public void actionPerformed(ActionEvent e) {
if (counter >= counterMax) {
((Timer) e.getSource()).stop();
}
Color bckgrndColor = (counter % 2 == 0) ? flashColor : Color.white;
for (JButton button : gridButton) {
button.setBackground(bckgrndColor);
}
counter++;
}
}).start();
The fact that you see the boxes being repainted individually indicates that either double buffering is turned off, or that the paint code in the button UI makes use of paintImmediately().
I tested your setup with 64x64 JButtons, an made sure that all UI operations were executed in the EDT (Event Dispatch Thread). I can confirm the effect you saw, changing the background of all buttons took about 1200 ms, with every box repainted immediately.
You can bypass the immediate repaints by setting the grid to non-visible before, and to visible after you changed the backgrounds:
grid.setVisible(false);
for (Component comp : grid.getComponents()) {
comp.setBackground(color);
}
grid.setVisible(true);
This caused the grid to do only one repaint, and reduced the time to ~300ms (factor 4).
This is still too slow for frequent updates, so you're better off with a custom component which draws the grid, or a flyweight container (what trashgod suggested in the comment to your question) if you want allow the grid cells to be arbitrary components.
You can get a considerable benefit if only visible buttons need to be repainted. In the MVC approach shown below, each button listens to a model that defines it's current state. Updating the model is quite fast compared to repainting. Although startup takes a few seconds, I see updates taking < 10 ms. in the steady-state. It's not as scalable as the flyweight pattern used by JTable, illustrated here, but it may serve.
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import javax.swing.*;
/** #see https://stackoverflow.com/questions/6117908 */
public class UpdateTest {
private static final int ROW = 64;
private static final int COL = 64;
private static final int MAX = COL * ROW;
private final DataModel model = new DataModel(MAX);
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new UpdateTest().create();
}
});
}
void create() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(ROW, COL));
for (int i = 0; i < MAX; i++) {
panel.add(new ViewPanel(model, i));
}
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long start = System.nanoTime();
model.update();
System.out.println(
(System.nanoTime() - start) / (1000 * 1000));
}
});
JFrame f = new JFrame("JTextTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(panel), BorderLayout.CENTER);
f.setPreferredSize(new Dimension(800, 600));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
timer.start();
}
private static class ViewPanel extends JPanel implements Observer {
private final JButton item = new JButton();
private DataModel model;
private int index;
public ViewPanel(DataModel model, int i) {
this.model = model;
this.index = i;
this.add(item);
item.setText(String.valueOf(i));
item.setOpaque(true);
item.setBackground(new Color(model.get(index)));
model.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
int value = model.get(index);
item.setBackground(new Color(value));
}
}
private static class DataModel extends Observable {
private final Random rnd = new Random();
private final int[] data;
public DataModel(int n) {
data = new int[n];
fillData();
}
public void update() {
fillData();
this.setChanged();
this.notifyObservers();
}
public int get(int i) {
return data[i];
}
private void fillData() {
for (int i = 0; i < data.length; i++) {
data[i] = rnd.nextInt();
}
}
}
}
I am trying to flash the background colour in a textfield. My timer setup is as follows:
Flash flash = new Flash(); //set up timer
tmr = new javax.swing.Timer(1000, new Flash());
tmr.addActionListener(flash);
tmr.setInitialDelay(0);
tmr.setRepeats(true);
tmr.start();
My actionListener is as follows:
static class Flash implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
if (flasher)
{
SpreademPanel.historyPnl.NameTxt.setBackground(Color.white);
}
else
{
SpreademPanel.historyPnl.NameTxt.setBackground(Color.pink);
}
flasher = !flasher;
} //actionPerformed
} //Flash
Now, when I put this in debug and follow the action, the program does repeatedly step through flash and toggle between the two alternatives. But onscreen, only the first toggle
occurs. After that, no action, although flash is still functioning.
What is wrong here?
Thanks in advance for any help.
This example continually varies the saturation of a panel's background color:
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.*;
public class FlashTest extends JPanel {
private static final Font font = new Font("Serif", Font.PLAIN, 32);
private static final String s = "Godzilla alert!";
FlashTest() {
this.setPreferredSize(new Dimension(256, 96));
this.setBackground(Color.red);
Timer t = new Timer(50, new Flash(this));
t.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
int xx = this.getWidth();
int yy = this.getHeight();
int w2 = g.getFontMetrics().stringWidth(s) / 2;
int h2 = g.getFontMetrics().getDescent();
g.setColor(Color.black);
g.drawString(s, xx / 2 - w2, yy / 2 + h2);
}
private static class Flash implements ActionListener {
private final float N = 32;
private final JComponent component;
private final Queue<Color> clut = new LinkedList<Color>();
public Flash(JComponent component) {
this.component = component;
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor(1, 1 - (i / N), 1));
}
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor(1, i / N, 1));
}
}
#Override
public void actionPerformed(ActionEvent e) {
component.setBackground(clut.peek());
clut.add(clut.remove());
}
}
static public void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new FlashTest());
f.pack();
f.setVisible(true);
}
});
}
}
There are a couple of problems here.
The first obvious thing is that you appear to be using mutable statics. This is a really bad idea and indicates (and causes!) confusion. In this particular case, one of the problems caused is that the flasher static is shared.
Flash flash = new Flash(); //set up timer
tmr = new javax.swing.Timer(1000, new Flash());
tmr.addActionListener(flash);
We are adding two Flash actions. Ordinarily this would be bad, but just produce an undetectable "bug". The colour would be set twice.
Bring these two things together, and we have two actions without a break that perform the same toggle. Two toggles. The state does not change (although there are repaint, property change events, etc.).
So, don't use mutable statics, and keep the code clean.
tmr = new javax.swing.Timer(1000, flash);
I tried your code and it works fine.
Why do you use a static context for SpreademPanel.historyPnl.NameTxt?
EDIT
You might want to redesign your class to pass the component in the constructor.
private class Flash implements ActionListener
{
private boolean flasher = false;
private JComponent component;
public Flash(JComponent component) {
this.component = component;
}
public void actionPerformed(ActionEvent evt)
{
if (flasher)
{
component.setBackground(Color.white);
}
else
{
component.setBackground(Color.pink);
}
flasher = !flasher;
} //actionPerformed
} //Flash
and then init it with
Flash flash = new Flash(SpreademPanel.historyPnl.NameTxt);
Timer tmr = new javax.swing.Timer(1000, flash);
tmr.start();