Get the text in a JTextField - java

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

Related

Swing Components invisible

When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();
And this...
package me.JavaProgramm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Frame extends JFrame {
private JButton bChange;
private JTextField tvonEur;
private JTextField tzuOCur; //andere Währung (other Currency)
private JTextField tzuEur;
private JTextField tvonOCur;
private JComboBox cbCur; //Wärhung wählen
private String curName;
private double faktorUSD;
private double faktorGBP;
private static String[] comboCur = {"USD", "GBP"};
public Frame() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Währungsrechner");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);
tvonEur = new JTextField("Euro");
tvonEur.setSize(80, 25);
tvonEur.setLocation(20, 50);
tvonEur.requestFocusInWindow();
tvonEur.selectAll();
tzuEur = new JTextField("Euro");
tzuEur.setSize(80, 25);
tzuEur.setLocation(20, 150);
tzuEur.requestFocusInWindow();
tzuEur.selectAll();
bChange = new JButton("Euro zu US-Dollar");
bChange.setSize(120, 25);
bChange.setLocation(110, 50);
tzuOCur = new JTextField("US-Dollar");
tzuOCur.setSize(80, 25);
tzuOCur.setLocation(240, 50);
tzuOCur.requestFocusInWindow();
tzuOCur.selectAll();
tvonOCur = new JTextField("US-Dollar");
tvonOCur.setSize(80, 25);
tvonOCur.setLocation(240, 50);
tvonOCur.requestFocusInWindow();
tvonOCur.selectAll();
cbCur = new JComboBox(comboCur);
cbCur.setSize(100, 20);
cbCur.setLocation(100, 100);
tvonEur.setVisible(true);
tzuEur.setVisible(true);
tzuOCur.setVisible(true);
tvonOCur.setVisible(true);
bChange.setVisible(true);
cbCur.setVisible(true);
add(tvonEur);
add(bChange);
add(tzuOCur);
add(cbCur);
Currency currency = new Currency();
String strUSD = currency.convertUSD();
try {
NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
Number numberUSD = formatUSD.parse(strUSD);
faktorUSD = numberUSD.doubleValue();
System.out.println(faktorUSD);
} catch (ParseException e) {
System.out.println(e);
}
String strGBP = currency.convertGBP();
try {
NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
Number numberGBP = formatGBP.parse(strGBP);
faktorGBP = numberGBP.doubleValue();
System.out.println(faktorGBP);
} catch (ParseException e) {
System.out.println(e);
}
cbCur.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cbCur = (JComboBox) e.getSource();
curName = (String) cbCur.getSelectedItem();
if (curName == "USD") {
tzuOCur.setText("US-Dollar");
} else if (curName == "GBP") {
tzuOCur.setText("British-Pound");
}
}
});
bChange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (curName == "USD") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleUSD = doubleEUR * faktorUSD;
tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
} else if (curName == "GBP") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleGBP = doubleEUR * faktorGBP;
tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
}
}
});
}
public static double roundScale3(double d) {
return Math.rint(d * 1000) / 1000.;
}
}
Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame.this.setVisible(true);
}
});

Swing delay between calls

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

Why is JApplet showing a blank gray screen?

So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Assignment8 extends JApplet implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_DIGITS = 30;
private JTextArea operand, result;
private double answer = 0.0;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;
/** public static void main(String[] args)
{
Assignment8 aCalculator = new Assignment8( );
aCalculator.setVisible(true);
}**/
public void init( )
{
setup_layout();
}
private void setup_layout() {
setSize(WIDTH, HEIGHT);
JPanel MainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel calcPanel = new JPanel();
JPanel textPanel = new JPanel ();
buttonPanel.setLayout(new GridLayout(3, 4));
calcPanel.setLayout(new GridLayout(3, 3));
textPanel.setLayout(new FlowLayout());
MainPanel.setLayout(new BorderLayout());
MainPanel.setBackground(Color.red);
operand = new JTextArea();
result = new JTextArea();
operand.setEditable(false);
result.setEditable(false);
textPanel.add(operand);
textPanel.add(result);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
addB = new JButton("+");
resetB = new JButton("Reset");
clearB = new JButton("Clear");
sqrtB = new JButton("Sqrt");
absB = new JButton("Abs");
expB = new JButton("Exp");
sevenB.addActionListener(this);
eightB.addActionListener(this);
nineB.addActionListener(this);
divideB.addActionListener(this);
fourB.addActionListener(this);
fiveB.addActionListener(this);
sixB.addActionListener(this);
multiplyB.addActionListener(this);
oneB.addActionListener(this);
twoB.addActionListener(this);
threeB.addActionListener(this);
subtractB.addActionListener(this);
zeroB.addActionListener(this);
dotB.addActionListener(this);
addB.addActionListener(this);
resetB.addActionListener(this);
clearB.addActionListener(this);
absB.addActionListener(this);
expB.addActionListener(this);
sqrtB.addActionListener(this);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
calcPanel.add(subtractB);
calcPanel.add(multiplyB);
calcPanel.add(divideB);
calcPanel.add(sqrtB);
calcPanel.add(absB);
calcPanel.add(expB);
calcPanel.add(addB);
calcPanel.add(resetB);
calcPanel.add(clearB);
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
assumingCorrectNumberFormats(e);
}
catch (NumberFormatException e2)
{
result.setText("Error: Reenter Number.");
}
catch (DivideByZeroException e1) {
result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
}
}
//Throws NumberFormatException.
public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("1"))
{
int num = 1;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("2"))
{
int num = 2;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("3"))
{
int num = 3;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("4"))
{
int num = 4;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("5"))
{
int num = 5;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("6"))
{
int num = 6;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("7"))
{
int num = 7;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("8"))
{
int num = 8;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("9"))
{
int num = 9;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("0"))
{
int num = 0;
String text = operand.getText();
//double check = stringToDouble(text);
if(text.isEmpty()||text.contains(".")) {
operand.append(Integer.toString(num));
}
}
else if (actionCommand.equals("."))
{
String text = operand.getText();
if(!text.contains(".")) {
operand.append(".");
}
}
else if (actionCommand.equals("+"))
{
answer = answer + stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("-"))
{
answer = answer - stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("*"))
{
answer = answer * stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("/"))
{
double check = stringToDouble(operand.getText());
if(check >= -1.0e-10 && check <= 1.0e-10 ) {
throw new DivideByZeroException();
}
else {
answer = answer / stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Sqrt"))
{
double check = stringToDouble(result.getText());
if(check < 0 ) {
throw new NumberFormatException();
}
else {
answer = Math.sqrt(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Abs"))
{
answer = Math.abs(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Exp"))
{
answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Reset"))
{
answer = 0.0;
result.setText("");
operand.setText("");
}
else if (actionCommand.equals("Clear"))
{
operand.setText("");
}
else
result.setText("Unexpected error.");
}
//Throws NumberFormatException.
private static double stringToDouble(String stringObject)
{
return Double.parseDouble(stringObject.trim( ));
}
//Divide by Zero Exception Class
public class DivideByZeroException extends Exception {
DivideByZeroException() {
}
}
}
You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);
Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
to:
MainPanel.add(buttonPanel, BorderLayout.CENTER);
MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
MainPanel.add(textPanel, BorderLayout.PAGE_START);
Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
throws DivideByZeroException {
String actionCommand = e.getActionCommand();
String numbers = "1234567890";
if (numbers.contains(actionCommand)) {
operand.append(actionCommand);
// if you need to work with it as a number
int num = Integer.parseInt(actionCommand);
}
Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.

Clicking on the search button in JFrame is not opening the JDialog

I have a jframe with page navigation buttons,print,search buttons.When i clicked on the print button it is perfectly opening the window and i am able to print the page also.But when i clicked on search button i am not able to get the window.My requirement is clicking on the Search button should open a window(same as print window) with text field and when i enter the search data then it should display the matches and unmatches.
I have tried the below code but i am not succeed.
import com.google.common.base.CharMatcher;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import com.sun.pdfview.PagePanel;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import static com.google.common.base.Strings.isNullOrEmpty;
public class PdfViewer extends JPanel {
private static enum Navigation {
GO_FIRST_PAGE, FORWARD, BACKWARD, GO_LAST_PAGE, GO_N_PAGE
}
private static final CharMatcher POSITIVE_DIGITAL = CharMatcher.anyOf("0123456789");
private static final String GO_PAGE_TEMPLATE = "%s of %s";
private static final int FIRST_PAGE = 1;
private int currentPage = FIRST_PAGE;
private JButton btnFirstPage;
private JButton btnPreviousPage;
private JTextField txtGoPage;
private JButton btnNextPage;
private JButton btnLastPage;
private JButton print;
private JButton search;
private PagePanel pagePanel;
private PDFFile pdfFile;
public PdfViewer() {
initial();
}
private void initial() {
setLayout(new BorderLayout(0, 0));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
add(topPanel, BorderLayout.NORTH);
btnFirstPage = createButton("|<<");
topPanel.add(btnFirstPage);
btnPreviousPage = createButton("<<");
topPanel.add(btnPreviousPage);
txtGoPage = new JTextField(10);
txtGoPage.setHorizontalAlignment(JTextField.CENTER);
topPanel.add(txtGoPage);
btnNextPage = createButton(">>");
topPanel.add(btnNextPage);
btnLastPage = createButton(">>|");
topPanel.add(btnLastPage);
print = new JButton("print");
topPanel.add(print);
search = new JButton("search");
topPanel.add(search);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
JPanel viewPanel = new JPanel(new BorderLayout(0, 0));
scrollPane.setViewportView(viewPanel);
pagePanel = new PagePanel();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
pagePanel.setPreferredSize(screenSize);
viewPanel.add(pagePanel, BorderLayout.CENTER);
disableAllNavigationButton();
btnFirstPage.addActionListener(new PageNavigationListener(Navigation.GO_FIRST_PAGE));
btnPreviousPage.addActionListener(new PageNavigationListener(Navigation.BACKWARD));
btnNextPage.addActionListener(new PageNavigationListener(Navigation.FORWARD));
btnLastPage.addActionListener(new PageNavigationListener(Navigation.GO_LAST_PAGE));
txtGoPage.addActionListener(new PageNavigationListener(Navigation.GO_N_PAGE));
print.addActionListener(new PrintUIWindow());
search.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
}
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setPreferredSize(new Dimension(55, 20));
return button;
}
private void disableAllNavigationButton() {
btnFirstPage.setEnabled(false);
btnPreviousPage.setEnabled(false);
btnNextPage.setEnabled(false);
btnLastPage.setEnabled(false);
}
private boolean isMoreThanOnePage(PDFFile pdfFile) {
return pdfFile.getNumPages() > 1;
}
private class PageNavigationListener implements ActionListener {
private final Navigation navigation;
private PageNavigationListener(Navigation navigation) {
this.navigation = navigation;
}
public void actionPerformed(ActionEvent e) {
if (pdfFile == null) {
return;
}
int numPages = pdfFile.getNumPages();
if (numPages <= 1) {
disableAllNavigationButton();
} else {
if (navigation == Navigation.FORWARD && hasNextPage(numPages)) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_LAST_PAGE) {
goPage(numPages, numPages);
}
if (navigation == Navigation.BACKWARD && hasPreviousPage()) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_FIRST_PAGE) {
goPage(FIRST_PAGE, numPages);
}
if (navigation == Navigation.GO_N_PAGE) {
String text = txtGoPage.getText();
boolean isValid = false;
if (!isNullOrEmpty(text)) {
boolean isNumber = POSITIVE_DIGITAL.matchesAllOf(text);
if (isNumber) {
int pageNumber = Integer.valueOf(text);
if (pageNumber >= 1 && pageNumber <= numPages) {
goPage(Integer.valueOf(text), numPages);
isValid = true;
}
}
}
if (!isValid) {
JOptionPane.showMessageDialog(PdfViewer.this,
format("Invalid page number '%s' in this document", text));
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
}
}
}
}
private void goPage(int pageNumber, int numPages) {
currentPage = pageNumber;
PDFPage page = pdfFile.getPage(currentPage);
pagePanel.showPage(page);
boolean notFirstPage = isNotFirstPage();
btnFirstPage.setEnabled(notFirstPage);
btnPreviousPage.setEnabled(notFirstPage);
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
boolean notLastPage = isNotLastPage(numPages);
btnNextPage.setEnabled(notLastPage);
btnLastPage.setEnabled(notLastPage);
}
private boolean hasNextPage(int numPages) {
return (++currentPage) <= numPages;
}
private boolean hasPreviousPage() {
return (--currentPage) >= FIRST_PAGE;
}
private boolean isNotLastPage(int numPages) {
return currentPage != numPages;
}
private boolean isNotFirstPage() {
return currentPage != FIRST_PAGE;
}
}
private class PrintUIWindow implements Printable, ActionListener {
/*
* (non-Javadoc)
*
* #see java.awt.print.Printable#print(java.awt.Graphics,
* java.awt.print.PageFormat, int)
*/
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int pagenum = pageIndex+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) graphics;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) pageFormat.getImageableWidth (),
(int) pageFormat.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) pageFormat.getImageableX (),
(int) pageFormat.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) graphics, bounds,
null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
//JOptionPane.showMessageDialog (this, ie.getMessage ());
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (pageFormat.getImageableX (),
pageFormat.getImageableY (),
pageFormat.getImageableWidth (),
pageFormat.getImageableHeight ()));
return PAGE_EXISTS;
}
/*
* (non-Javadoc)
*
* #see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
* )
*/
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Inside action performed");
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
try
{
HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
//attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (printJob.printDialog (attset))
printJob.print (attset);
}
catch (PrinterException pe)
{
//JOptionPane.showMessageDialog (this, pe.getMessage ());
}
}
}
public PagePanel getPagePanel() {
return pagePanel;
}
public void setPDFFile(PDFFile pdfFile) {
this.pdfFile = pdfFile;
currentPage = FIRST_PAGE;
disableAllNavigationButton();
txtGoPage.setText(format(GO_PAGE_TEMPLATE, FIRST_PAGE, pdfFile.getNumPages()));
boolean moreThanOnePage = isMoreThanOnePage(pdfFile);
btnNextPage.setEnabled(moreThanOnePage);
btnLastPage.setEnabled(moreThanOnePage);
}
public static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
public static void main(String[] args) {
try {
long heapSize = Runtime.getRuntime().totalMemory();
System.out.println("Heap Size = " + heapSize);
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load a pdf from a byte buffer
File file = new File("/home/swarupa/Downloads/2626OS-Chapter-5-Advanced-Theme.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
final PDFFile pdffile = new PDFFile(buf);
PdfViewer pdfViewer = new PdfViewer();
pdfViewer.setPDFFile(pdffile);
frame.add(pdfViewer);
frame.pack();
frame.setVisible(true);
PDFPage page = pdffile.getPage(0);
pdfViewer.getPagePanel().showPage(page);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Where i am doing wrong.Can any one point me.
I think, that this should solve your problem ;) You've forgotten to set the window to be visible :)
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
parent.setVisible(true);
}
}
Btw-why do you create that JDialog?
You create JDialog and JFrame, why? You never call setVisible(true), why?
What you expect from the Action1?
Sorry for posting this answer to your comment as a new post, but it was too long to post it as a comment. You just can't remove close and minimize buttons from JFrame. If you want some window without those buttons, you have to create and customize your own JDialog. Nevertheless there will still be a close button (X). You can make your JDialog undecorated and make it to behave more like JFrame when you implement something like this:
class CustomizedDialog extends JDialog {
public CustomizedDialog(JFrame frame, String str) {
super(frame, str);
super.setUndecorated(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
And then you can call it in your code with this:
CustomizedDialog myCustomizedDialog = new CustomizedDialog(new JFrame(), "My title");
JPanel panel = new JPanel();
panel.setSize(256, 256);
myCustomizedDialog.add(panel);
myCustomizedDialog.setSize(256, 256);
myCustomizedDialog.setLocationRelativeTo(null);
myCustomizedDialog.setVisible(true);
I hope, this helps :)

Update JLabel every X seconds from ArrayList<List> - Java

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);
}
}

Categories