display series of images with next button - java

How can I display a series of images one by one every time the user clicks the next button?
I have few images stored in array. I used button next to go from image to image. How to programme the button? I used action listener but I just don't know how to get back to the array.

I know I'm being lazy here by not writing the entire code, but here goes anyway.
class whatEver implements ActionListener{
JButton btnNext = new JButton();
static int fileNumber = 0;
static int totalFiles;
void functionLoadInterface () //Function with
{
btnNext.addActionListener(this);
//Initialize array ImageArray with file paths.
}
public void cycleImage()
{
String file = ImageArray[fileNumber%totalFiles];
//Code to load the image wherever follows
}
public void actionPerformed(ActionEvent e)
{
filenumber++;
this.cycleImage();
}

Related

How to open another JFrame with selected RadioButton according to data in JTable?

I am trying to send data to JFrame named UpdateCar using a button. Data should say which radio button should be selected.
btnUpdateCar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpdateCar updatePage = new UpdateCar();
updatePage.setVisible(true);
int selectedRow = table.getSelectedRow();
updatePage.buttonGroup.setSelected(getSelectedButton(model,selectedRow).getModel(),true);
// when I use above line it doesn't work. But instead if I use the thing it will return, it works for that value.
}
});
I wrote a method like this for this purpose:
public JRadioButton getSelectedButton(DefaultTableModel model, int selectedRow) {
String selectedButton = (String) model.getValueAt(selectedRow,3);
UpdateCar updatePage = new UpdateCar();
if(selectedButton.equals("Automatic")) {
return updatePage.rdbtnAutomatic;
}else {
return updatePage.rdbtnManuel;
}
}
Well, apparently both method and btnUpdateCar's action perfrom method should have same reference for target JFrame. I was using two different calls for that JFrame. Now I have global variable for that Jframe and problem solved.

Java GUI adding buttons with a for loop

Hi i am making a lotto gui where the user picks 4 numbers from a selection of 28. The way i am currently doing it is as follows
private void no1InputButtonActionPerformed(java.awt.event.ActionEvent evt) {
numberSelectionList.add("1");
}
private void no2InputButtonActionPerformed(java.awt.event.ActionEvent evt) {
chosenNumDisplayLabel.setText(chosenNumDisplayLabel.getText()+" 2");
}
private void no3InputButtonActionPerformed(java.awt.event.ActionEvent evt) {
chosenNumDisplayLabel.setText(chosenNumDisplayLabel.getText()+" 3");
}
etc up through the 28 numbers.
Is there a way to add the actions to each button through a for loop
as this seems more logical?
Also is there a way to add each number picked into an array?
Create a single Action that can be shared by all buttons. The Action will then simply get the text of the button and then do some processing.
Check out setText method with panel and button. This example will show you how to:
create a single ActionListener to be shared by each button
"append" the text to the text field instead of replacing the text
use Key Bindings so the user can also just type the number
On each button you can set an action command:
button.setActionCommand("1");
And you can get the value after that using your ActionEvent:
evt.getActionEvent();
More complete:
ActionListener listener = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand()+" clicked");
}
};
int howMuchYouWant = 32;
for(int i = 0; i<howMuchYouWant; i++)
{
JButton button = new JButton(""+(i+1));
button.setActionCommand(""+i);
button.addActionListener(listener);
//add to whatever gui you want here
}

Swapping icons of 2 jbutton

I want to change the icon of 2 Jbuttons by selecting one and then the next to swap their icons. Something like candy crush or bejeweled.
I want to use action listener to accomplish this, how should i go about doing it?
this is the gui of my program:
public class UI implements Runnable {
private JFrame _frame;
private Model _model;
private ArrayList<JButton> _tiles;
public void run() {
_model = new Model();
_frame = new JFrame();
_frame.setLayout(new GridLayout(5,5));
_tiles = new ArrayList<JButton>();
for (int i=0; i<25; i++) {
JButton tile = new JButton();
tile.setBackground(Color.white);
//this just pick out random icon file from a folder
tile.setIcon(_model.randomIcon());
tile.addActionListener(new ButtonBorderHandler(_model,tile));
//this is the actionlistener that i want to implement the swap on
tile.addActionListener(new ButtonSwapHandler();
_tiles.add(tile);
}
i've tried doing it like so
public class ButtonSwapHandler implements ActionListener{
JButton _button1;
JButton _button2;
Model _model;
UI _ui;
public ButtonSwapHandler(UI u,Model m, JButton b1, JButton b2){
_model=m;
_button1=b1;
_button2=b2;
_ui =u;
}
#Override
public void actionPerformed(ActionEvent e) {
//this line should give me the position of the first button i press
int i = _ui.getTiles().indexOf(e.getSource());
//this is the part where i dont know how to keep going
//i want to know where is the 2nd button that i clicked
int j = _ui.getTiles().indexOf(e.
// this is the method i wrote to make the swap
// it just the Collections.swap(tile,positionOfButton1,postionOfButton2)
_model.swap(ui._tile,i,j);
}
Your logic needs little clarity. You are creating a 5x5 grid, where you are populating the buttons.
For example like this:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
But, when you are clicking on a button, how do you ensure the direction of swap? Say, if the user clicks on button 7, which adjacent button of 7 should be selected for swapping?
So, the missing piece of your logic is the direction.
For example:
If the swap always happens with immediate left button, you can calculate the swap button like indexOf(selectedButton)-1. Again, the swap may be happening on conditional basis only if that row in that two dimensional grid has immediate left button.
Update:
If the action is supposed to happen only after clicking two buttons, then you need to create one more class which actually keeps track of number of buttons clicked then swaps when count==2.
Following is a modified example:
public class ButtonClicksCounter {
static ArrayList<JButton> _buttonsClicked = new ArrayList<JButton>();
public static void addButton(JButton btn) {
_buttonsClicked.add(btn);
}
public static int getButtonClicksCount() {
return _buttonsClicked.size();
}
public static void clearButtonClicksCount() {
_buttonsClicked.clear();
}
public ArrayList<JButton> getButtonsClicked() {
return _buttonsClicked;
}
}
public class ButtonSwapHandler implements ActionListener{
JButton _button;
Model _model;
UI _ui;
public ButtonSwapHandler(UI u, Model m, JButton b1){
_model=m;
_button=b1;
_ui =u;
}
#Override
public void actionPerformed(ActionEvent e) {
//Add the button
ButtonClicksCounter.addButton((JButton)e.getSource());
//Check if count==2
if(ButtonClicksCounter.getButtonClicksCount()==2) {
ArrayList<JButton> buttonsToSwap = ButtonClicksCounter.getButtonsClicked();
//Get positions
int i = _ui.getTiles().indexOf(buttonsToSwap[0]);
int j = _ui.getTiles().indexOf(buttonsToSwap[1]);
//Swap
_model.swap(ui._tile,i,j);
//Clear selection
ButtonClicksCounter.clearButtonClicksCount();
}
}

Is there a way to stop MouseListener?

Okay, so what I'm trying to do is place an image by clicking. I have a boolean and I have it set so that it's true when the mouse is being pressed, and false when it's released. Then I have the following codes:
if (place == true){
msex = MouseInfo.getPointerInfo().getLocation().x;
msey = MouseInfo.getPointerInfo().getLocation().y;
}
and this on the main screen so it shows up:
if (place == true){
d.drawImage(twilightblock,msex - 45,msey - 85,this);
}
However, when I try it, I click and it shows up, but it disappears when I release the mouse button. It also moves around with the mouse instead of staying in one place. I'm wondering, is there a way to stop MouseListener in the middle, like, right after the button is pressed? If so, that would be perfect. :D
Use a MouseAdapter and select the appropriate methods: http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseAdapter.html
onClick on the image (the first component)
store the image's data or reference in a temporary structure/object
onCLick on a second component
access the image's data from the tempprary structure/object and apply it to the second component
delete the image from the first component
Answering your comment, this is a high level scaffold of what you could do:
public static void main() {
SomeOtherObject so; // use to store app data
// create possibly many components of type B
JComponentB compB = new JComponentB(so);
JComponentA compA = new JComponentA(so);
// add them to your JFrame, or other component
}
import java.awt.event.MouseAdapter;
class JComponentA extends MouseAdapter {
String imagePath;
Image myImage;
public JComponentA(SomeOtherObject so) { };
public void mouseClicked(MouseEvent e) {
this.imagePath = so.getImagePath;
// display new image, or maybe swap images
}
}
import java.awt.event.MouseAdapter;
class JComponentB extends MouseAdapter {
String imagePath;
Image myImage;
public JComponentB(SomeOtherObject so) { };
public void mouseClicked(MouseEvent e) {
so.setImagePath(this.imagePath);
// delete image, or maybe do a swap (that requires two strings in SomeOtherObject)
}
}

java Pause code and wait for user input

I wrote my program in two parts, I wrote the actual functionality first, and then the GUI to display it all.
I need to wait/pause for a user to click a "Done" button from another class(DisplayImages) before continuing executing code.
My DisplayImages class takes a list of MyImage. The images are then displayed in a jpanel and the user selects a couple of images
and then clicks a 'Done' button. How can I wait for a response or something like that?
public class One{
ArrayList<MyImage> images = new ArrayList<MyImage>();
public One(){
DisplayImages displayOne = new DisplayImages(images);
displayOne.run();
//I need to pause/wait here until the user has pressed the done button
//in the DisplayImages class
images.clear();
images = displayOne.getSelectedImages();
//do stuff here with images arrylist
}
}
DisplayImages class
public class DisplayImages extends JFrame{
private ArrayList<MyImage> images = new ArrayList<MyImage>();
private ArrayList<MyImage> selectedImages = new ArrayList<MyImage>();
public DisplayImages(ArrayList<MyImage> images){
this.images = images;
}
public void run(){
//code creates a jpanel and displays images along with a done button
//user presses done button
done.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
setVisible(false);
selectedImages = getSelectedImages();
//here I would send a signal to continue running in class One
}
});
}
private ArrayList<MyImage> getSelectedImages(){
//code returns list of all the images the user selected on JPanel
return results;
}
}
If for some reason you need to open and process the dialog in the same method then using the dialog approach suggested with JOptionPane seems fine. However this seems bad design (opening a frame and waiting for input in a constructor?). I would prefer an approach similar to the one below (please read my inline comments):
public class One {
ArrayList<MyImage> images = new ArrayList<MyImage>();
public One() {
// perform only initialization here
}
// call this method to create the dialog that allows the user to select images
public void showDialog() {
DisplayImages displayOne = new DisplayImages(images);
// pass a reference to this object so DisplayImages can call it back
displayOne.run(this);
}
// this will be called by the action listener of DisplayImages when Done is clicked
public void processSelectedImages(List<MyImage> selectedImages) {
images.clear();
images = selectedImages;
// do stuff here with images arrylist
}
}
public class DisplayImages {
...
public void run(final One callback){ // Note that now a reference to the caller is passed
// creates jpanel and displays images along with a done button
// user presses done button
done.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
setVisible(false);
selectedImages = getSelectedImages();
// here is how we can send a signal to notify the caller
callback.processSelectedImages(selectedImages);
}
});
}
...
}
As a side note please do not name your methods run() if you are not implementing the Runnable interface and/or using threads. This is very confusing
That is quite easy, some people here are thinking to complicated. You will need no multithreading, you just need a modal dialog. JOptionPane provides easy access to them.
I modified your code:
public class One{
ArrayList<MyImage> images = new ArrayList<MyImage>();
public One(){
DisplayImages displayOne = new DisplayImages(images);
int n = JOptionPane.showConfirmDialog(null, displayOne);
if (n == JOptionPane.OK_OPTION){
//I need to pause/wait here until the user has pressed the done button
//in the DisplayImages class
images = displayOne.getSelectedImages();
//do stuff here with images arrylist
}
}
}
MyImage class
public class DisplayImages extends JPanel{
private ArrayList<MyImage> images = new ArrayList<MyImage>();
public DisplayImages(ArrayList<MyImage> images){
this.images = images;
//code creates a jpanel and displays images along with a done button
}
public ArrayList<MyImage> getSelectedImages(){
//code returns list of all the images the user selected on JPanel
return results;
}
}
You will have to use threading.
http://docs.oracle.com/javase/tutorial/essential/concurrency/
Then you can set up each instance on a separate thread, and either use the built in Object.notify and Object.wait
Or have yourself a global flag variable, static, available to both classes, which you change to notify the other class that the done button was clicked.

Categories

Resources