I'm trying to make a program that load 4 images, put it in 4 labels and change the icons of each label in the frame regarding the random number in the list, like if it was blinking the images. It need to blink each image in the order that is sorted in comecaJogo() but when I press the btnComecar in the actionPerformed all imagens seems to change at the same time:
Here is my logic class:
public class Logica {
List<Integer> seqAlea = new ArrayList<Integer>();
List<Integer> seqInsere = new ArrayList<Integer>();
int placar = 0;
boolean cabouGame = false;
Random geraNumero = new Random();
int numero;
Timer timer = new Timer(1500,null);
public void comecaJogo() {
for (int i = 0; i < 4; i++) {
numero = geraNumero.nextInt(4) + 1;
seqAlea.add(numero);
}
}
public void piscaImagen(ImageIcon img1, ImageIcon img1b, JLabel lbl) {
timer.addActionListener(new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent evt) {
if(lbl.getIcon() != img1){
lbl.setIcon(img1);
} else {
lbl.setIcon(img1b);
}
count++;
if(count == 2){
((Timer)evt.getSource()).stop();
}
}
});
timer.setInitialDelay(1250);
timer.start();
}
}
In the frame:
public class Main extends JFrame implements ActionListener {
JLabel lblImg1 = new JLabel();
JButton btnImg1 = new JButton("Economize Energia");
final URL resource1 = getClass().getResource("/br/unip/IMGs/img1.jpg");
final URL resource1b = getClass().getResource("/br/unip/IMGs/img1_b.png");
ImageIcon img1 = new ImageIcon(resource1);
ImageIcon img1b = new ImageIcon(resource1b);
JButton btnImg2 = new JButton("Preserve o Meio Ambiente");
JLabel lblImg2 = new JLabel("");
final URL resource2 = getClass().getResource("/br/unip/IMGs/img2.jpg");
final URL resource2b = getClass().getResource("/br/unip/IMGs/img2_b.jpg");
ImageIcon img2 = new ImageIcon(resource2);
ImageIcon img2b = new ImageIcon(resource2b);
JButton btnImg3 = new JButton("N\u00E3o \u00E0 polui\u00E7\u00E3o!");
JLabel lblImg3 = new JLabel("");
final URL resource3 = getClass().getResource("/br/unip/IMGs/img3.jpg");
final URL resource3b = getClass().getResource("/br/unip/IMGs/img3_b.jpg");
ImageIcon img3 = new ImageIcon(resource3);
ImageIcon img3b = new ImageIcon(resource3b);
JButton btnImg4 = new JButton("Recicle!");
JLabel lblImg4 = new JLabel("");
final URL resource4 = getClass().getResource("/br/unip/IMGs/img4.jpg");
final URL resource4b = getClass().getResource("/br/unip/IMGs/img4_b.jpg");
ImageIcon img4 = new ImageIcon(resource4);
ImageIcon img4b = new ImageIcon(resource4b);
Logica jogo = new Logica();
JButton btnComecar = new JButton("Come\u00E7ar");
public static void main(String[] args) {
Main window = new Main();
window.setVisible(true);
}
public Main() {
lblImg1.setIcon(img1b);
lblImg1.setBounds(78, 48, 250, 200);
add(lblImg1);
btnImg1.setBounds(153, 259, 89, 23);
btnImg1.addActionListener(this);
add(btnImg1);
setBounds(100, 100, 800, 600);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnImg2.setBounds(456, 272, 186, 23);
btnImg2.addActionListener(this);
lblImg2.setIcon(img2b);
lblImg2.setBounds(421, 61, 250, 200);
add(btnImg2);
add(lblImg2);
btnImg3.setBounds(114, 525, 186, 23);
btnImg3.addActionListener(this);
lblImg3.setIcon(img3b);
lblImg3.setBounds(78, 314, 250, 200);
add(lblImg3);
add(btnImg3);
btnImg4.setBounds(456, 525, 186, 23);
btnImg4.addActionListener(this);
lblImg4.setIcon(img4b);
lblImg4.setBounds(421, 314, 250, 200);
add(lblImg4);
add(btnImg4);
btnComecar.setBounds(68, 14, 89, 23);
btnComecar.addActionListener(this);
add(btnComecar);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(btnImg1)) {
jogo.piscaImagen(img1, img1b, lblImg1);
} else if (e.getSource().equals(btnComecar)) {
jogo.comecaJogo();
System.out.println(jogo.seqAlea);
for (int i = 0; i < jogo.seqAlea.size(); i++) {
switch (jogo.seqAlea.get(i)) {
case 1:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img1, img1b, lblImg1);
break;
case 2:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img2, img2b, lblImg2);
break;
case 3:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img3, img3b, lblImg3);
break;
case 4:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img4, img4b, lblImg4);
break;
}
}
}
}
}
Thanks for the help!
one at time, like a memory game :)
There are multitudes of ways this might work, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements ActionListener {
JButton btnImg1 = new JButton();
JButton btnImg2 = new JButton();
JButton btnImg3 = new JButton();
JButton btnImg4 = new JButton();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Main();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public Main() {
JPanel buttons = new JPanel(new GridLayout(2, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
buttons.add(btnImg1);
buttons.add(btnImg2);
buttons.add(btnImg3);
buttons.add(btnImg4);
add(buttons);
JButton play = new JButton("Play");
add(play, BorderLayout.SOUTH);
play.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
List<JButton> sequence = new ArrayList<>(Arrays.asList(new JButton[]{btnImg1, btnImg2, btnImg3, btnImg4}));
Collections.shuffle(sequence);
Timer timer = new Timer(1000, new ActionListener() {
private JButton last;
#Override
public void actionPerformed(ActionEvent e) {
if (last != null) {
last.setBackground(null);
}
if (!sequence.isEmpty()) {
JButton btn = sequence.remove(0);
btn.setBackground(Color.RED);
last = btn;
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setInitialDelay(0);
timer.start();
}
}
This just places all the buttons into a List, shuffles the list and then the Timer removes the first button from the List until all the buttons have been "flashed".
Now this is just using the button's backgroundColor, so you'd need to create a class which allows you to associate the JButton with "on" and "off" images, these would then be added to the List and the Timer executed in a similar manner as above
Related
So, I have got this problem in my Java Swing project where I am making a bot that automatically runs through a whileloop and outputs a text that the user can define in a textfield.
Here you can see my code for adding a textline into a jlabel into my frame:
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
After that I start my bot by pressing the following button:
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
}
});
Via that button I start a thread which runs through a code that outputs the string. But after I've runned that Thread, my frame doesn't show newly-added jlabels anymore that you've added by clicking the btnAddTalking-button after you've run the Thread by clicking on the btnStartTalking-button! So, my question is: does anyone now how that's even possible (why my UI doesn't update anymore after i've run the thread)?
Greetz,
Jarnov
Here you can see my whole code for the two classes (class 1):
import java.awt.EventQueue;
import java.awt.event.InputEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.sun.glass.events.KeyEvent;
import com.sun.glass.ui.Robot;
import java.awt.AWTException;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.GroupLayout.Alignment;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
public class AutoTalker {
private static JFrame frame;
private JTextField txtTalk;
private JTextField timeTalk;
public String robotTalk;
private JButton btnStopTalking;
private JButton btnAddTalking;
private JButton btnStartTalking;
private int yLabel = 266;
private Runnable autoTalkStart;
/**
* Launch the application.
*/
public static void NewFrame() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoTalker window = new AutoTalker();
window.frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #return
*/
public AutoTalker() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 415);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("AutoTalker");
frame.getContentPane().setLayout(null);
JRadioButton rdbtnGlow = new JRadioButton("Glow");
rdbtnGlow.setBounds(6, 113, 64, 23);
rdbtnGlow.setActionCommand("glow");
frame.getContentPane().add(rdbtnGlow);
JRadioButton rdbtnFlash = new JRadioButton("Flash");
rdbtnFlash.setBounds(182, 113, 69, 23);
rdbtnGlow.setActionCommand("flash");
frame.getContentPane().add(rdbtnFlash);
JRadioButton rdbtnRed = new JRadioButton("Red");
rdbtnRed.setBounds(364, 113, 64, 23);
rdbtnGlow.setActionCommand("red");
frame.getContentPane().add(rdbtnRed);
final ButtonGroup rdbtnPressed = new ButtonGroup();
rdbtnPressed.add(rdbtnRed);
rdbtnPressed.add(rdbtnFlash);
rdbtnPressed.add(rdbtnGlow);
txtTalk = new JTextField();
txtTalk.setBounds(130, 28, 173, 20);
txtTalk.setColumns(10);
btnStopTalking = new JButton("Stop AutoTalk");
btnStopTalking.setBounds(144, 177, 146, 23);
btnStopTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Talk.action = "stop";
btnStartTalking.setEnabled(true);
btnStopTalking.setEnabled(false);
btnAddTalking.setEnabled(true);
frame.repaint();
}
});
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
frame.repaint();
}
});
timeTalk = new JTextField();
timeTalk.setBounds(174, 71, 86, 20);
timeTalk.setColumns(10);
JLabel lblNewLabel = new JLabel("Text:");
lblNewLabel.setBounds(24, 28, 46, 20);
JLabel lblDelayInMs = new JLabel("Delay in ms:");
lblDelayInMs.setBounds(24, 71, 101, 20);
frame.getContentPane().add(txtTalk);
frame.getContentPane().add(btnStartTalking);
frame.getContentPane().add(btnStopTalking);
frame.getContentPane().add(timeTalk);
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
btnStopTalking.setEnabled(false);
}
}
class 2:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
public class Talk extends AutoTalker {
Robot robot = new Robot();
public static String action;
public static ArrayList<String> Talks = new ArrayList<String>();
public Talk(int wait) throws AWTException, InterruptedException {
robot.delay(5000);
while(action == "start") {
for(int i = 0; i < Talks.size();i++) {
String text = Talks.get(i);
type(text);
robot.delay(wait);
}
}
}
public static void addTalk(String text) {
Talks.add(text);
}
private void type(String s)
{
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
switch(c) {
case '!':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_1);
break;
case ':':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
break;
default:
robot.keyPress(Character.toUpperCase(c));
break;
}
robot.delay(10);
}
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.delay(10);
}
}
Use instead
invalidate();
validate();
I have a swing application where the user inputs a number into two of the three fields, and my application does Pythagoras Theorem on those two numbers, and sets the answer field with the answer. However, the three fields (hypotenuse, short side 1, short side 2) are all returning 0 (shorter side 1 and shorter side 2 are different fields, forgot to add the : there), and 0 is the default value. This is not the case for other windows, this is only the case for the Maths tab. My question is, what is the problem?
Here is a screenshot of the error:
And here is the code:
Entry.java
package Entry;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuBar;
import Settings.SettingsLoader;
import Window.ErrorWindow;
import Window.SmallLinkWindow;
import Window.Window;
import Window.WindowEntry;
public class Entry {
public static JFrame frame;
public static File file;
public static JInternalFrame currentframe;
public static void main(String[] args){
file = new File("settings.txt");
frame = new JFrame("GUI_Base");
JMenuBar menu = new JMenuBar();
JMenuBar bottom = new JMenuBar();
SmallLinkWindow[] smallwindows = WindowEntry.getSmallWindows();
for(int i = 0; i < smallwindows.length; i++){
SmallLinkWindow window = smallwindows[i];
JButton button = window.getButton(); //ActionListener already added at this point.
button.addActionListener(getActionListener(window));
bottom.add(button);
}
List<String> data = readAllData();
SettingsLoader loader = new SettingsLoader(data);
loader.obtainSettings();
Window[] windows = WindowEntry.getAllWindows();
for(int i = 0; i < windows.length; i++){
Window window = windows[i];
JButton item = new JButton(window.getName());
item.addActionListener(getActionListener(window));
menu.add(item);
}
currentframe = windows[0].getInsideFrame();
menu.add(getRefresh(), BorderLayout.EAST);
frame.setSize(2000, 1000);
frame.add(menu, BorderLayout.NORTH);
frame.add(bottom, BorderLayout.SOUTH);
frame.getRootPane().setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("Loaded!");
}
private static JButton getRefresh() {
try {
BufferedImage image = ImageIO.read(new File("refresh.png"));
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
image = resizeImage(image, type, 25, 25);
ImageIcon icon = new ImageIcon(image);
JButton label = new JButton(icon);
label.addActionListener(getActionListener());
return label;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static ActionListener getActionListener() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
frame.repaint();
}
};
}
//Copied from http://www.mkyong.com/java/how-to-resize-an-image-in-java/
public static BufferedImage resizeImage(BufferedImage originalImage, int type, int width, int height){
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
private static ActionListener getActionListener(SmallLinkWindow window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static ActionListener getActionListener(Window window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static List<String> readAllData() {
try {
return Files.readAllLines(file.toPath());
} catch (IOException e) {
ErrorWindow.forException(e);
}
ErrorWindow.forException(new RuntimeException("Unable to read file!"));
System.exit(1);
return null;
}
}
MathWindow.java
package Window;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import Math.Pythagoras;
import Math.Trig;
import Math.TrigValue;
import Math.TrigonometryException;
import Settings.GUISetting;
public class MathWindow implements Window {
private Color colour;
private JSplitPane splitPane;
#Override
public String getName() {
return "Maths";
}
#Override
public JInternalFrame getInsideFrame() {
JInternalFrame frame = new JInternalFrame();
JSplitPane pane = new JSplitPane();
pane.setDividerLocation(300);
JPanel panel = new JPanel();
panel.setSize(300, 925);
JButton pyth = new JButton();
JButton trig = new JButton();
pyth.setText("Pythagoars theorem");
trig.setText("Trigonometry");
pyth.setSize(300, 200);
trig.setSize(300, 200);
pyth.addActionListener(getActionListenerForPythagoras());
trig.addActionListener(getActionListenerForTrignomotry());
panel.setLayout(new GridLayout(0,1));
panel.add(pyth);
panel.add(trig);
pane.setLeftComponent(panel);
splitPane = pane;
frame.getContentPane().add(pane);
return frame;
}
private ActionListener getActionListenerForPythagoras() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Small side 1");
bLabel.setText("Small side 2");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForPythagorasFinal(hypField.getText(), aField.getText(), bField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
protected ActionListener getActionListenerForPythagorasFinal(String hyp, String s1, String s2, JTextField field) {
return new ActionListener(){
private Pythagoras p = new Pythagoras();
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hypotenuse: " + hyp);
System.out.println("Shorter side 1" + s1);
System.out.println("Shorter side 2" + s2);
if(hyp.equals("0")){
double a = Double.parseDouble(s1);
double b = Double.parseDouble(s2);
if(a == 3 && b == 4 || a == 4 && b == 3) System.out.println("The result should be 5!");
field.setText(String.valueOf(p.getHypotenuse(a, b)));
}else if(s1.equals("0")){
double c = Double.parseDouble(hyp);
double b = Double.parseDouble(s2);
field.setText(String.valueOf(p.getShorterSide(b, c)));
}else if(s2.equals("0")){
double c = Double.parseDouble(hyp);
double a = Double.parseDouble(s1);
field.setText(String.valueOf(p.getShorterSide(a, c)));
}else throw new IllegalArgumentException("All of the fields have stuff in them!");
}
};
}
private ActionListener getActionListenerForTrignomotry(){
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JTextField anField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JLabel anLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Opposite");
bLabel.setText("Adjacent");
anLabel.setText("Angle size");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
anLabel.setSize(400, anLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
anField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
anField.setSize(400, anLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForTrigonomotryFinal(hypField.getText(), aField.getText(), bField.getText(), anField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(anLabel, BorderLayout.CENTER);
overseePanel.add(anField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
//a == opposite, b == adjacent
protected ActionListener getActionListenerForTrigonomotryFinal(String hyp,
String a, String b, String an, JTextField field) {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Trig trigonometry = new Trig();
double value = 0.000;
if(an == "0"){
if(hyp == "0"){
int shorta = Integer.parseInt(a);
int shortb = Integer.parseInt(b);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tA, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shortb = Integer.parseInt(b);
try {
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tH, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
value = trigonometry.getAngleSize(tA, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}else{
int angle = Integer.parseInt(an);
if(angle >= 90) throw new IllegalArgumentException("Angle is bigger than 90");
if(hyp.equals("0")){
if(a.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
value = trigonometry.getSideLength(tB, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
value = trigonometry.getSideLength(tA, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(a.equals("0")){
if(hyp.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tB, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(b.equals("0")){
if(hyp.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tA, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}
}
field.setText(String.valueOf(value));
}
};
}
#Override
public GUISetting[] getSettings() {
GUISetting setting = new GUISetting("Show working", "Maths");
GUISetting setting2 = new GUISetting("Round", "Maths");
return new GUISetting[]{setting, setting2};
}
#Override
public void setColour(Color c) {
colour = c;
}
#Override
public Color getCurrentColour() {
return colour;
}
}
If I need to add anything else please add a comment.
You create a new instance of JTextField, you then pass it's text property to the getActionListenerForPythagorasFinal method, so it no longer has what "will" be entered into the fields, only what it's initial value is (""), thus it's completely unable to perform the calculation on the fields in question
You could try passing the fields themselves to the method instead, but as a general piece of advice, I would create a custom class which contains the fields and associated actions which you can create whenever you need it, making significantly easier to manage and maintain
Hello I have to finish a project but I can't get further. The project is about having jlabels with icons generated dynamically on two sides (left and right) .
The icons are in different order on each side and there is a one to one icon relationship.
As an example one picture : link
Now you can draw lines from the left to the right between those pictures and after clicking on the check button it should tell you if its true or false :
Again one picture : link
My question is how can I compare the icons to know which combination is the right one and after comparing the drawings?
I already created two lists to know the component combination of the drawings.
Here is the code so far -
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class CatSameCoins{
public static JLabel label;
public ActionListener btn1Listener;
public ActionListener btn2Listener;
public ActionListener btn3Listener;
public ActionListener btn4Listener;
public ActionListener btn5Listener;
public ActionListener btn6Listener;
public JButton btn1;
public JButton btn2;
public JButton btn3;
public JButton btn4;
public JButton btn5;
public JButton btn6;
public JButton btnCheck;
public ArrayList<String> listto = new ArrayList<String>();
public ArrayList<String> listfrom = new ArrayList<String>();
public static boolean drawing = false;
public static List<Shape> shapes = new ArrayList<Shape> ();
public static Shape currentShape = null;
static Component fromComponent;
private JLabel lblCheck;
public void drawLine(Component from , Component to){
listfrom.add(from.getName()); //first list with component names from where the drawing start
listto.add(to.getName()); //second list with component names where the drawing ends
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX()+from.getWidth()/2; //get middle
fromPoint.y = from.getY()+from.getHeight()/2; //get middle
toPoint.x = to.getX()+to.getWidth()/2;
toPoint.y = to.getY()+to.getHeight()/2;
currentShape = new Line2D.Double (fromPoint, toPoint);
shapes.add (currentShape);
label.repaint();
drawing = false;
}
public CatSameCoins(){
JFrame frame = new JFrame ();
frame.getContentPane().setLayout(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
listfrom.removeAll(listfrom);
drawing= false;
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("btn1");
btn1.setBounds(21, 88, 45, 97);
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
btn1.removeActionListener(this);
}
};
btn1.addActionListener(btn1Listener);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("btn2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
btn2.removeActionListener(this);
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("btn3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
btn3.removeActionListener(this);
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("btn4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn4);
drawing = false;
btn4.removeActionListener(this);
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("btn5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn5);
drawing = false;
btn5.removeActionListener(this);
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("btn6");
btn6.setBounds(407, 307, 45, 91);
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn6);
drawing = false;
btn6.removeActionListener(this);
}
}
};
btn6.addActionListener(btn6Listener);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0;i< listfrom.size();i++){
System.out.println(listfrom.get(i)+" - "+listto.get(i));
}
lblCheck.setText("False");
//if().... lblCheck.setText("True")
//else lblCheck.setText("False")
/*if(btn6.getIcon().toString().equals(btn1.getIcon().toString())){
System.out.println("yes");
}
else{
System.out.println("neah");
}*/
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel (){
protected void paintComponent ( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setPaint ( Color.black);
g2d.setStroke(new BasicStroke(5));
for ( Shape shape : shapes )
{
g2d.draw ( shape );
repaint();
}
}
} ;
label.setSize(500,500);
frame.getContentPane().add (label);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize ( 500, 500 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
public static void main ( String[] args )
{
new CatSameCoins();
}
}
Would really appreciate for any help ;) .
Its done,
Solution : you can try it just change icon names for the second hashmap
I know this is not the best solution but at least i tried. I will try to improve it.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class Hashmap {
private JLabel label;
private ActionListener btn1Listener;
private ActionListener btn2Listener;
private ActionListener btn3Listener;
private ActionListener btn4Listener;
private ActionListener btn5Listener;
private ActionListener btn6Listener;
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btn5;
private JButton btn6;
private JButton btnCheck;
private JButton btnNext;
private boolean drawing = false;
private Shape currentShape = null;
private Component fromComponent;
private JLabel lblCheck;
private List<Shape> shapes = new ArrayList<Shape>();
private HashMap<String, String> userLines = new HashMap<String, String>();
private HashMap<String, String> resultLines = new HashMap<String, String>();
private HashMap<String, String> icons = new HashMap<String, String>();
public void drawLine(Component from, Component to) {
userLines.put(from.getName(), to.getName());
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX() + from.getWidth() / 2; // get middle
fromPoint.y = from.getY() + from.getHeight() / 2; // get middle
toPoint.x = to.getX() + to.getWidth() / 2;
toPoint.y = to.getY() + to.getHeight() / 2;
currentShape = new Line2D.Double(fromPoint, toPoint);
shapes.add(currentShape);
label.repaint();
drawing = false;
}
#SuppressWarnings("serial")
public Hashmap() {
loadIcons();
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
drawing = false;
userLines.clear();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("1");
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
}
};
btn1.addActionListener(btn1Listener);
btn1.setBounds(21, 88, 45, 97);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn4);
drawing = false;
btn4.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn5);
drawing = false;
btn5.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("6");
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn6);
drawing = false;
btn6.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn6.addActionListener(btn6Listener);
btn6.setBounds(407, 307, 45, 91);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (resultLines.equals(userLines) && !userLines.isEmpty()) {
lblCheck.setText("true");
} else {
lblCheck.setText("false");
}
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
btnNext = new JButton("next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userLines.clear();
resultLines.clear();
shapes.removeAll(shapes);
drawing = false;
changeCombination();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
btnNext.setBounds(335, 435, 117, 25);
frame.getContentPane().add(btnNext);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.black);
g2d.setStroke(new BasicStroke(3));
for (Shape shape : shapes) {
g2d.draw(shape);
repaint();
}
}
};
label.setSize(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(label);
frame.setVisible(true);
}
private void loadIcons() {
icons.clear();
icons.put("money/coin2/1_Cent.png", "money/coin2/1_Cent.png");
icons.put("money/coin2/5_Cent.png", "money/coin2/5_Cent.png");
icons.put("money/coin2/10_Cent.png", "money/coin2/10_Cent.png");
icons.put("money/coin2/20_Cent.png", "money/coin2/20_Cent.png");
icons.put("money/coin2/50_Cent.png", "money/coin2/50_Cent.png");
icons.put("money/coin2/2_Euro.png", "money/coin2/2_Euro.png");
icons.put("money/coin2/1_Euro.png", "money/coin2/1_Euro.png");
}
public void changeCombination() {
Random randLeftSide = new Random();
Random randRightSide = new Random();
while (resultLines.size() < 3) {
int left = randLeftSide.nextInt(3 - 1 + 1) + 1;
int right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("leftside: "+left+"rightside: "+y);
while (resultLines.containsKey(String.valueOf(left))) {
if (resultLines.size() > 3) {
break;
} else {
left = randLeftSide.nextInt(3 - 1 + 1) + 1;
// System.out.println("leftside : "+left);
}
}
while (resultLines.containsValue(String.valueOf(right))) {
if (resultLines.size() > 3) {
break;
} else {
right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("rightside: "+right);
}
}
resultLines.put(String.valueOf(left), String.valueOf(right));
}
// System.out.println("TOTAL MAP: "+resultLines.toString());
changeImages();
}
private void changeImages() {
List<Integer> randomIcon = new ArrayList<Integer>(); //creating array list for the icon random numbers
List<Integer> randomLines = new ArrayList<Integer>(); //creating array list for the lines random numbers
for (int i = 0; i < resultLines.size(); i++) {
int randomIndexIcon = new Random().nextInt(icons.size()); //generate random number for the icons from the hashmap
while (randomIcon.contains(randomIndexIcon)) { //while the list contains the random number generate a new one to prevent printing same pictures
randomIndexIcon = new Random().nextInt(icons.size());
}
randomIcon.add(randomIndexIcon); //add to the array list of the icon random numbers the generated random number
int randomIndexResult = new Random().nextInt(resultLines.size()); //generate random number for the lines
while (randomLines.contains(randomIndexResult)) { //while for second list to prevent generating same numbers
randomIndexResult = new Random().nextInt(resultLines.size());
}
randomLines.add(randomIndexResult); //add to the array list of the lines random numbers the generated random number
Object iconValue = icons.values().toArray()[randomIndexIcon]; //this is to get the icon string
Object valueLeft = resultLines.keySet().toArray()[randomIndexResult]; //this is to get the random key value from the resultLines map (left side)
if (valueLeft.equals("1")) { //check conditions
btn1.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("2")) {
btn2.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("3")) {
btn3.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
Object valueRight = resultLines.values().toArray()[randomIndexResult]; //get the values from the hashmap (right side)
if (valueRight.equals("4")) { //check conditions
btn4.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("5")) {
btn5.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("6")) {
btn6.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
}
}
public static void main(String[] args) {
new Hashmap();
}
}
The question is, I try to make second textfield (textFieldGen) to print out the exact result likes console. Currently, second textfield shows one string only.
This is my first coding on java GUI.
(extra info, I built it using Eclipse with WindowBuilder + GEF )
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.TextField;
import java.awt.Label;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class PassGenerator {
private JFrame frmPasswordGenerator;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassGenerator window = new PassGenerator();
window.frmPasswordGenerator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PassGenerator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPasswordGenerator = new JFrame();
frmPasswordGenerator.setTitle("Password Generator");
frmPasswordGenerator.setBounds(100, 100, 419, 229);
frmPasswordGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPasswordGenerator.getContentPane().setLayout(null);
final TextField textFieldGen = new TextField();
final TextField textFieldPass = new TextField();
textFieldPass.setBounds(74, 60, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldPass);
Label labelPass = new Label("Password Length:");
labelPass.setBounds(74, 33, 177, 21);
frmPasswordGenerator.getContentPane().add(labelPass);
Button genButton = new Button("Generate");
genButton.setBounds(262, 60, 86, 23);
frmPasswordGenerator.getContentPane().add(genButton);
// Add action listener to button
genButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
//System.out.println("You clicked the button");
String getTxt = textFieldPass.getText();
boolean y = true;
do{
try{
int c = Integer.parseInt(getTxt);
Random r = new Random();
String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x","y","z"};
int nc = 0-c;
int c2 = c/2;
int nc2 = 0-c2;
int ncm = (nc+1)/2;
if (c%2 == 0){
for(int x = nc2; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
}
else {
for(int x = ncm; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
y = false;
}
catch (NumberFormatException e1 ){
int messageType = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(null, "Please Enter Integer only", "Error!!", messageType);
y = false;
}
}while (y);
}
});
Label labelGen = new Label("Generated Password:");
labelGen.setBounds(74, 109, 149, 21);
frmPasswordGenerator.getContentPane().add(labelGen);
textFieldGen.setBounds(74, 136, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldGen);
Button copyButton = new Button("Copy");
copyButton.setBounds(262, 136, 86, 23);
frmPasswordGenerator.getContentPane().add(copyButton);
}
}
Use textFieldGen.setText (textFieldGen.getText () + "\n" + Integer.toString(numNum))
I don't see why you are setting the contents of the text field twice. I would just do:
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
//textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
//textFieldGen.setText(Integer.toString(numNum));
textFieldGen.setText(alpha + Integer.toString(numNum));
In general it is not a good practice to replace the entire text when all you want to do is append some characters to the text field. If you don't like the above then you can do:
textField.setText(alpha);
...
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), Integer.toString(numNum), null);
Edit:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JTextField textField = new JTextField(20);
add( textField );
textField.setText( "testing: " );
try
{
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), "1", null);
}
catch(Exception e) {}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
I have a simple Java program that reads in a text file, splits it by " " (spaces), displays the first word, waits 2 seconds, displays the next... etc... I would like to do this in Spring or some other GUI.
Any suggestions on how I can easily update the words with spring? Iterate through my list and somehow use setText();
I am not having any luck. I am using this method to print my words out in the consol and added the JFrame to it... Works great in the consol, but puts out endless jframe. I found most of it online.
private void printWords() {
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel(w.name,SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
I have a window that get's created with JFrame and JLable, however, I would like to have the static text be dynamic instead of loading a new spring window. I would like it to flash a word, disappear, flash a word disappear.
Any suggestions on how to update the JLabel? Something with repaint()? I am drawing a blank.
Thanks!
UPDATE:
With the help from the kind folks below, I have gotten it to print correctly to the console. Here is my Print Method:
private void printWords() {
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
However, it isn't updating the lable? My contructor looks like:
public TimeThis() {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
//_textField.setText("loading...");
}
Getting there... I'll post the fix once I, or whomever assists me, get's it working. Thanks again!
First, build and display your GUI. Once the GUI is displayed, use a javax.swing.Timer to update the GUI every 500 millis:
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
private Iterator<Word> it = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (it.hasNext()) {
label.setText(it.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
Never use Thread.sleep(int) inside Swing Code, because it blocks the EDT; more here,
The result of using Thread.sleep(int) is this:
When Thread.sleep(int) ends
Example code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private Queue<Icon> iconQueue = new LinkedList<Icon>();
private JLabel label = new JLabel();
private Random random = new Random();
private JPanel buttonPanel = new JPanel();
private JPanel labelPanel = new JPanel();
private Timer backTtimer;
private Timer labelTimer;
private JLabel one = new JLabel("one");
private JLabel two = new JLabel("two");
private JLabel three = new JLabel("three");
private final String[] petStrings = {"Bird", "Cat", "Dog",
"Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
private boolean runProcess = true;
private int index = 1;
private int index1 = 1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));
one.setFont(new Font("Dialog", Font.BOLD, 24));
one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
two.setFont(new Font("Dialog", Font.BOLD, 24));
two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
three.setFont(new Font("Dialog", Font.BOLD, 10));
three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelPanel.setLayout(new GridLayout(0, 3, 4, 4));
labelPanel.add(one);
labelPanel.add(two);
labelPanel.add(three);
//labelPanel.setBorder(new LineBorder(Color.black, 1));
labelPanel.setOpaque(false);
JButton button0 = createButton();
JButton button1 = createButton();
JButton button2 = createButton();
JButton button3 = createButton();
buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
buttonPanel.add(button0);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
//buttonPanel.setBorder(new LineBorder(Color.black, 1));
buttonPanel.setOpaque(false);
label.setLayout(new BorderLayout());
label.add(labelPanel, BorderLayout.NORTH);
label.add(buttonPanel, BorderLayout.SOUTH);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));
add(label, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
startBackground();
startLabel2();
new Thread(this).start();
printWords(); // generating freeze Swing GUI durring EDT
}
private JButton createButton() {
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon(nextIcon());
button.setRolloverIcon(nextIcon());
button.setPressedIcon(nextIcon());
button.setDisabledIcon(nextIcon());
nextIcon();
return button;
}
private Icon nextIcon() {
Icon icon = iconQueue.peek();
iconQueue.add(iconQueue.remove());
return icon;
}
// Update background at 4/3 Hz
private void startBackground() {
backTtimer = new javax.swing.Timer(750, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private Action updateBackground() {
return new AbstractAction("Background action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
// Update Label two at 2 Hz
private void startLabel2() {
labelTimer = new javax.swing.Timer(500, updateLabel2());
labelTimer.start();
labelTimer.setRepeats(true);
}
private Action updateLabel2() {
return new AbstractAction("Label action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
two.setText(petStrings[index]);
index = (index + 1) % petStrings.length;
}
};
}
// Update lable one at 3 Hz
#Override
public void run() {
while (runProcess) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
one.setText(petStrings[index1]);
index1 = (index1 + 1) % petStrings.length;
}
});
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Note: blocks EDT
private void printWords() {
for (int i = 0; i < petStrings.length; i++) {
String word = petStrings[i].toString();
System.out.println(word);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
three.setText(word);
}
three.setText("<html> Concurency Issues in Swing<br>"
+ " never to use Thread.sleep(int) <br>"
+ " durring EDT, simple to freeze GUI </html>");
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
class TimeThis extends JFrame {
private static final long serialVersionUID = 1L;
private ArrayList<Word> words;
private JTextField _textField; // set by timer listener
public TimeThis() throws IOException {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
_textField.setText("loading...");
readFile(); // read file
printWords(); // print results
}
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("adameve.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
//System.out.println(lineWords.length);
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
private void printWords() {
final Timer timer = new Timer(100, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
#Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
class Word{
private String name;
public Word(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) throws IOException {
JFrame ani = new TimeThis();
ani.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ani.setVisible(true);
}
}
I got it working with this code... Hope it can help someone else expand on their Java knowledge. Also, if anyone has any recommendations on cleaning this up. Please do so!
You're on the right track, but you're creating the frame's inside the loop, not outside. Here's what it should be like:
private void printWords() {
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("", SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
textLabel.setTest(w.name);
}
}