I'm trying to make something for fun and my components keep disappearing after I press the "ok" button in my gui.
I'm trying to make a "Guess a word" program, where one will get a tip and you can then enter a guess and if it matches it will give you a message and if not, another tip. The problem is, if you enter something that's not the word it will give you a message that it's not the correct word and it will then give you another tip. But the other tip won't show up. They disappear.
I've two classes, "StartUp" and "QuizLogic".
The problem arrives somewhere in the "showTips" method (I think).
If someone would try it themselves a link to the file can be found here: Link to file
Thank you.
public class StartUp {
private JFrame frame;
private JButton showRulesYesButton;
private JButton showRulesNoButton;
private JButton checkButton;
private JPanel mainBackgroundManager;
private JTextField guessEntery;
private QuizLogic quizLogic;
private ArrayList<String> tips;
private JLabel firstTipLabel;
private JLabel secondTipLabel;
private JLabel thirdTipLabel;
// CONSTRUCTOR
public StartUp() {
// Show "Start Up" message
JOptionPane.showMessageDialog(null, "Guess a Word!");
showRules();
}
// METHODS
public void showRules() {
// Basic frame methods
frame = new JFrame("Rules");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(500, 500));
frame.setLocationRelativeTo(null);
// Creates JLabels and adds to JPanel
JLabel firstRule = new JLabel("1. You will get one tip at a time of what the word could be.");
JLabel secoundRule = new JLabel("2. You will get three tips and unlimited guesses.");
JLabel thirdRule = new JLabel("3. Every word is a noun and in its basic form.");
JLabel understand = new JLabel("Are you ready?");
// Creates JPanel and adds JLabels to JPanel
JPanel temporaryRulesPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 60));
temporaryRulesPanel.add(firstRule);
temporaryRulesPanel.add(secoundRule);
temporaryRulesPanel.add(thirdRule);
temporaryRulesPanel.add(understand);
// Initialize buttons
showRulesYesButton = new JButton("Yes");
showRulesNoButton = new JButton("No");
showRulesYesButton.addActionListener(new StartUpEventHandler());
showRulesNoButton.addActionListener(new StartUpEventHandler());
// Creates JPanel and adds button to JPanel
JPanel temporaryButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 100, 35));
temporaryButtonPanel.add(showRulesYesButton);
temporaryButtonPanel.add(showRulesNoButton);
// Initialize and adds JPanel to JPanel
mainBackgroundManager = new JPanel(new BorderLayout());
mainBackgroundManager.add(temporaryRulesPanel, BorderLayout.CENTER);
mainBackgroundManager.add(temporaryButtonPanel, BorderLayout.SOUTH);
//Adds JPanel to JFrame
frame.add(mainBackgroundManager);
frame.setVisible(true);
}
public void clearBackground() {
mainBackgroundManager.removeAll();
quizLogic = new QuizLogic();
showGuessFrame();
showTips();
}
public void showGuessFrame() {
JPanel guessPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 10));
firstTipLabel = new JLabel("a");
secondTipLabel = new JLabel("b");
thirdTipLabel = new JLabel("c");
tips = new ArrayList<String>();
guessEntery = new JTextField("Enter guess here", 20);
checkButton = new JButton("Ok");
checkButton.addActionListener(new StartUpEventHandler());
guessPanel.add(guessEntery);
guessPanel.add(checkButton);
mainBackgroundManager.add(guessPanel, BorderLayout.SOUTH);
frame.add(mainBackgroundManager);
}
public void showTips() {
JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
temporaryTipsPanel.removeAll();
tips.add(quizLogic.getTip());
System.out.println(tips.size());
if (tips.size() == 1) {
firstTipLabel.setText(tips.get(0));
}
if (tips.size() == 2) {
secondTipLabel.setText(tips.get(1));
}
if (tips.size() == 3) {
thirdTipLabel.setText(tips.get(2));
}
temporaryTipsPanel.add(firstTipLabel);
temporaryTipsPanel.add(secondTipLabel);
temporaryTipsPanel.add(thirdTipLabel);
mainBackgroundManager.add(temporaryTipsPanel, BorderLayout.CENTER);
frame.add(mainBackgroundManager);
frame.revalidate();
frame.repaint();
}
public void getGuess() {
String temp = guessEntery.getText();
boolean correctAnswer = quizLogic.checkGuess(guessEntery.getText());
if (correctAnswer == true) {
JOptionPane.showMessageDialog(null, "Good Job! The word was " + temp);
}
else {
JOptionPane.showMessageDialog(null, temp + " is not the word we are looking for");
showTips();
}
}
private class StartUpEventHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == showRulesYesButton) {
clearBackground();
}
else if (event.getSource() == showRulesNoButton) {
JOptionPane.showMessageDialog(null, "Read the rules again");
}
else if (event.getSource() == checkButton) {
getGuess();
}
}
}
}
public class QuizLogic {
private ArrayList<String> quizWord;
private ArrayList<String> tipsList;
private int tipsNumber;
private String word;
public QuizLogic() {
tipsNumber = 0;
quizWord = new ArrayList<String>();
quizWord.add("Burger");
try {
loadTips(getWord());
} catch (Exception e) {
System.out.println(e);
}
}
public String getWord() {
Random randomGen = new Random();
return quizWord.get(randomGen.nextInt(quizWord.size()));
}
public void loadTips(String word) throws FileNotFoundException {
Scanner lineScanner = new Scanner(new File("C:\\Users\\Oliver Nielsen\\Dropbox\\EclipseWorkspaces\\BuildingJava\\GuessAWord\\src\\domain\\" + word + ".txt"));
this.word = word;
tipsList = new ArrayList<String>();
while (lineScanner.hasNext()) {
tipsList.add(lineScanner.nextLine());
}
}
public String getTip() {
if (tipsNumber >= tipsList.size()) {
throw new NoSuchElementException();
}
String temp = tipsList.get(tipsNumber);
tipsNumber++;
System.out.println(temp);
return temp;
}
public boolean checkGuess(String guess) {
return guess.equalsIgnoreCase(word);
}
}
I figured it out!
I don't know why it can't be done but if I deleted this line: JPanel temporaryTipsPanel = new JPanel(new GridLayout(3, 1));
and placed it in another method it worked. If someone could explain why that would be great but at least I/we know what was the problem.
Thank you. :)
Related
So for school, we have to make 2 separate JFrames that interact with each other. From within the first JFrame, a button gets pressed which opens the second one, where a name, speed, and position can be filled in.
When pressing OK on the second JFrame, I save the filled-in text and numbers but I have no clue how to use them in the code of the first JFrame. I had tried to use a "getter" from the second JFrame to check in the first one if the "OK" button had been pressed. But this gets checked immediately after opening the window. That means it isn't true YET and it doesn't check it again.
CONTEXT:
We are forced to use 2 separate JFrame.
We are not allowed to add extra methods.
We are not allowed to change the constructor.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TourFrame extends JFrame implements ActionListener{
private Etappe etappe;
private JLabel jlAantal;
private JTextField jtfAantal;
private JButton knopPrint;
private JButton knopStap;
private JButton knopVoegFietsenToe;
private JButton knopVoegCustomFietsToe;
public TourFrame(Etappe etappe){
this.etappe = etappe;
setTitle("Tour de Windesheim: " + etappe.toString());
setSize(650, 550);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlAantal = new JLabel("aantal:");
add(jlAantal);
jtfAantal = new JTextField(10);
add(jtfAantal);
knopPrint = new JButton("print");
add(knopPrint);
knopPrint.addActionListener(this);
knopStap = new JButton("stap");
add(knopStap);
knopStap.addActionListener(this);
knopVoegFietsenToe = new JButton("voeg fietsen toe");
add(knopVoegFietsenToe);
knopVoegFietsenToe.addActionListener(this);
knopVoegCustomFietsToe = new JButton("voeg custom fiets toe");
add(knopVoegCustomFietsToe);
knopVoegCustomFietsToe.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == knopPrint){
etappe.print();
} else if(e.getSource() == knopStap){
etappe.stap();
setTitle("Tour de Windesheim: " + etappe.toString());
} else if(e.getSource() == knopVoegFietsenToe){
try {
int aantal = Integer.parseInt(jtfAantal.getText());
for(int i = 0; aantal > i; i++){
Fiets tijdelijk = new Fiets();
etappe.voegDeelnemerToe(tijdelijk);
}
} catch (NumberFormatException nfe){
jlAantal.setText("Voer een getal in");
}
} else if(e.getSource() == knopVoegCustomFietsToe){
FietsDialoog fietsdialoog = new FietsDialoog();
}
}
}
The Second one looks as follwed:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FietsDialoog extends JFrame implements ActionListener {
private JLabel jlNaam;
private JTextField jtfNaam;
private JLabel jlStartPositie;
private JTextField jtfStartPositie;
private JLabel jlSnelheid;
private JTextField jtfSnelheid;
private JButton knopOk;
private JButton knopCancel;
private String naam;
private int startpositie;
private int snelheid;
private boolean ok;
private boolean cancel;
public FietsDialoog(){
setTitle("FietsDialoog");
setSize(600, 100);
setLayout(new FlowLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
jlNaam = new JLabel("naam");
add(jlNaam);
jtfNaam = new JTextField(10);
add(jtfNaam);
jlStartPositie = new JLabel("startpositie");
add(jlStartPositie);
jtfStartPositie = new JTextField(10);
add(jtfStartPositie);
jlSnelheid = new JLabel("snelheid");
add(jlSnelheid);
jtfSnelheid = new JTextField(10);
add(jtfSnelheid);
knopOk = new JButton("ok");
add(knopOk);
knopOk.addActionListener(this);
knopCancel = new JButton("cancel");
add(knopCancel);
knopCancel.addActionListener(this);
setVisible(true);
}
public String getNaam() {
return naam;
}
public int getStartpositie() {
return startpositie;
}
public int getSnelheid() {
return snelheid;
}
public boolean isOk() {
return ok;
}
public boolean isCancel() {
return cancel;
}
public JButton getKnopOk() {
return knopOk;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == knopOk){
this.naam = jtfNaam.getText();
this.startpositie = Integer.parseInt(jtfStartPositie.getText());
this.snelheid = Integer.parseInt(jtfSnelheid.getText());
this.ok = true;
this.cancel = false;
} else if(e.getSource() == knopCancel){
this.ok = false;
this.cancel = true;
dispose();
}
}
}
Try and print fietsdialoog.getNaam(), fietsdialoog.getStartpositie()...etc, the getter from the fietsdialoog class after closing the window.
Also, rather than dispose the window: use setVisible to false. JFrame.setVisible(true/false);
I'm creating a program for my Java class and I'm having a hard time implementing a actionListener in conjunction to my main class.
This is an example of my main class, I am using other classes to create the components for the tabs. Where I'm running into trouble is when I try to implement action listeners in the other class. I keep running into errors regarding abstract classes. This is probably a simple solution, but I'm still fairly new to programming.
'
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import javax.swing.plaf.ColorUIResource;
public class TaikunStudyResource extends JFrame {
private static final int FRAME_WIDTH = 700;
private static final int FRAME_HIEGHT = 500;
private JPanel searchTab,addTab, grammerTab,testTab,homeTab;
public static void main(String[] args)throws UnsupportedOperationException {
TaikunStudyResource tsr = new TaikunStudyResource();
tsr.setVisible(true);
}
public TaikunStudyResource(){
//set basic features
setTitle("Taikun-Japanese Study Resource!");
setSize(FRAME_WIDTH,FRAME_HIEGHT);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(new Color(226,199,255));
addComponents(getContentPane());
}
public void addComponents(Container contentPane){
//add overlaying panel
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
contentPane.add(topPanel);
//create tabs
contentPane.add(createTabs());
}
public JTabbedPane createTabs(){
//UIManager.put("TabbedPane.contentAreaColor",ColorUIResource.getHSBColor(153,153,255));
//create tabs
JTabbedPane tabs = new JTabbedPane();
SearchPanel sp = new SearchPanel();
tabs.addTab("Search", sp);
addPanel ap = new addPanel();
tabs.addTab("Add",ap);
return tabs;
}
}
'
Here is a example of my my addPanel class
'
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
/**
*
* #author tyler.stanley.4937
*/
public abstract class addPanel extends JPanel{
//variables
private JPanel mainPanel, eastPanel,westPanel, checkboxPanel, radioPanel, typePanel, adjectivePanel, verbPanel, kanjiPanel;
private JLabel kanaKanjiLabel, romanjiLabel;
private JTextField kanaKanjiField, romanjiField,exampleInput, defInput, tagInput;
private JButton radicalButton, addDefButton, addExampleButton, addButton, addTagButton
,clearexButton,clearDefButton,clearTagButton;
private ButtonGroup commonGroup;
private JRadioButton[] commonButton;
private String[] commonTypeArray = {"very-common", "common", "Uncommon", "Out-dated"};
private JCheckBox[] typeCheckBox;
private String[] typeofWordArray = {"Noun", "Pronoun", "Verb","Adjective","Idiom"};
private JComboBox adjectiveTypeCombo;
private String[] adjectivetypeArray ={"Na","i"};
private JComboBox verbTypeCombo;
//private String[] verbTypetext = {"Suru","Kuru","da","desu","iku","-masu"};//these may not make it
private String[] verbTypeArray ={"-u","-ku","-gu","-su","-tsu","-nu","-bu","-mu","-ru"};
private JTextArea definitionArea, exampleArea, tagArea;
private List<String>definitionList, exampleList, tagList, radicalList,typeList;
private String kanjiKana,romanji;
private ActionListener a;
public static void main(String[] arg)throws UnsupportedOperationException{
}
public addPanel(){
setLayout(new BorderLayout());
//setBackground(Color.blue);
addComponents();
}
public void addComponents(){
fillSouthPanel();
fillEastPanel();
}
}
public void fillEastPanel(){
eastPanel = new JPanel(new BorderLayout());
//add definition pane
JPanel definitionPanel = new JPanel(new FlowLayout());
definitionPanel.setBorder(BorderFactory.createTitledBorder("Defintion"));
definitionArea = new JTextArea();
definitionArea.setColumns(22);
definitionArea.setRows(8);
definitionArea.setBorder(BorderFactory.createLineBorder(Color.black));
definitionArea.setEditable(false);
//add scroll pane
JScrollPane scrollPane = new JScrollPane(definitionArea);
scrollPane.setSize(200,135);
definitionPanel.add(scrollPane);
//add input and button
defInput = new JTextField(50);
definitionPanel.add(defInput);
addDefButton = new JButton("Add");
definitionPanel.add(addDefButton);
//addDefButton.addActionListener(al);
clearDefButton = new JButton("Clear");
definitionPanel.add(clearDefButton);
//clearDefButton.addActionListener(al);
//add tags
JPanel tagPanel = new JPanel(new FlowLayout());
tagPanel.setBorder(BorderFactory.createTitledBorder("Tags"));
tagArea = new JTextArea();
tagArea.setColumns(22);
tagArea.setRows(1);
tagArea.setBorder(BorderFactory.createLineBorder(Color.black));
tagArea.setEditable(false);
JScrollPane tagScrollPane = new JScrollPane(tagArea);
tagScrollPane.setSize(200,133);
tagPanel.add(tagScrollPane);
tagInput = new JTextField(22);
tagPanel.add(tagInput);
addTagButton = new JButton("Add Tag");
clearTagButton = new JButton("Clear Tag");
tagPanel.add(addTagButton);
tagPanel.add(clearTagButton);
//clearTagButton.addActionListener(al);
//addTagButton.addActionListener(al);
//examples
JPanel examplePanel = new JPanel(new FlowLayout());
examplePanel.setBorder(BorderFactory.createTitledBorder("example"));
exampleArea = new JTextArea();
exampleArea.setColumns(22);
exampleArea.setRows(8);
exampleArea.setBorder(BorderFactory.createLineBorder(Color.black));
exampleArea.setEditable(false);
JScrollPane exampleScrollPane = new JScrollPane(exampleArea);
exampleScrollPane.setSize(200,135);
examplePanel.add(exampleScrollPane);
exampleInput = new JTextField(30);
examplePanel.add(exampleInput);
addExampleButton = new JButton("Add");
examplePanel.add(addExampleButton);
//addExampleButton.addActionListener(this);
JButton clearExampleButton = new JButton("Clear");
examplePanel.add(clearExampleButton);
//clearExampleButton.addActionListener(this);
add(eastPanel, BorderLayout.EAST);
}
public void fillSouthPanel(){
JPanel southPanel = new JPanel(new FlowLayout());
addButton = new JButton("Add");
southPanel.add(addButton);
addButton.addActionListener(new Action() {
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
add(southPanel, BorderLayout.SOUTH);
}
public void addEntry(int buttonNumber){
switch(buttonNumber){
case 1:
tagList.add(tagInput.getText());
tagArea.append("/n"+tagInput.getText());
break;
case 2:
exampleList.add(exampleInput.getText());
exampleArea.append("/n"+exampleInput.getText());
break;
case 3:
definitionList.add(defInput.getText());
definitionArea.append("/n"+defInput.getText());
break;
}
}
public void clearEntry(int buttonNumber){
switch(buttonNumber){
case 0:
case 1:
case 2:
}
}
//public List radicalList(){
//RadicalFrame rf = new RadicalFrame();
//List<String>radicalList = rf.getRadicals();
//return
//}
public boolean getFieldEntries(){
boolean romaji,kanji, passable;
if(kanaKanjiField.getText()!= null){
kanjiKana = kanaKanjiField.getText();
kanji = true;
}else{
JOptionPane.showMessageDialog(null, "Please entry a vaild Japanese word");
kanaKanjiField.setText(null);
kanji = false;
}
//test if it's english
if(romanjiField.getText() !=null){
romanji = romanjiField.getText();
romaji = true;
}else{
JOptionPane.showMessageDialog(null, "please enter a vaild romaji entry");
romanjiField.setText(null);
romaji = false;
}
if(romaji == true && kanji == true){
passable =true;
}else{
passable = false;
}
return passable;
}
public boolean getTextArea(){
boolean defText, exText, tagText,passable;
if(tagList.size()!=0){
tagText = true;
}else{
JOptionPane.showMessageDialog(null, "Please enter tags to indentify the word");
tagText = false;
}
if(definitionList.size()!=0){
defText = true;
}else{
JOptionPane.showMessageDialog(null,"Please Enter defintion of the word");
defText = false;
}
if(exampleList.size()!=0){
exText = true;
}else{
JOptionPane.showMessageDialog(null, "Please Enter an Example of the word usage");
exText = false;
}
if(exText == true&&defText== true&& tagText == true){
passable = true;
}else{
passable = false;
}
return passable;
}
public void addWord() throws FileNotFoundException, IOException{
boolean vaild = getFieldEntries();
boolean vaild2 = getTextArea();
if(vaild == true&& vaild2 == true){
//Word word = new Word(KanjiKanaEntry, RomanjiEntry, CommonIndex, radicalList,typeentry, adjectiveIndex,VerbIndex);
File outFile = new File("dictionary.dat","UTF-8");
//Writer unicodeFileWriter = new OutputStreamWriter( new FileOutputStream("dictionary.dat)."UTF-8");//can't use writer
//fileOutputStream("dictionary.dat"),"UTF-8");
FileOutputStream outFileStream = new FileOutputStream(outFile,true);
ObjectOutputStream oos = new ObjectOutputStream(outFileStream);//append to a file
//oos.WriteObject(word);//store word
}
}
public void actionPermored(ActionEvent event) throws FileNotFoundException, IOException{
System.out.println("action");
//get even source
if(event.getSource() instanceof JButton){
JButton clickedButton = (JButton)event.getSource();
if(clickedButton == radicalButton){
//radicalList = radicalFrame();
}else if(clickedButton ==addButton){
addWord();
}else if(clickedButton == addTagButton){
addEntry(1);
}else if(clickedButton == addExampleButton){
addEntry(2);
}else if(clickedButton == addDefButton){
addEntry(3);
}else if(clickedButton == clearTagButton){
clearEntry(1);
}else if(clickedButton == clearDefButton){
clearEntry(0);
}else if(clickedButton == clearexButton){
clearEntry(2);
}
}
//get combo box entries
if(event.getSource() instanceof JComboBox){
JComboBox selectedComboBox = (JComboBox)event.getSource();
if(selectedComboBox == adjectiveTypeCombo){
int adjectiveform = selectedComboBox.getSelectedIndex();
}else if(selectedComboBox == verbTypeCombo){
int VerbForm = selectedComboBox.getSelectedIndex();
}
if(event.getSource() instanceof JCheckBox){
for(int i = 0;i<typeCheckBox.length;i++){
if(typeCheckBox[i].isSelected()){
typeList.add(typeCheckBox[i].getText()); //some how assign index numbers
}
}
}
}
}
}'
This is just a piece of code, so sorry if it seems a little jumbled, I'm trying to condense it as much as possible.
I've tried to create a internal class to handle the action listener, but I can't seem to get it to work. Also I know I can create actionlisteners for every button, but I would like to condense all the actionevents to one class or method.
The errors are due to unimplemented methods of the Action class anonymous instance.
Any instance of the Action interface requires that all the its methods be implemented. However using Action as an anonymous instance if neither practical or good practice. Rather create a single concrete instance of a class that extends AbstractAction and set the Action for for each component.
button.setAction(mySingleAction);
where
class SingleAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
// do stuff
}
}
Im making a contact list, and my code compiles and runs, when you add the contact, type or email or phone its supposed to read them to you, the problem I have here is when I add the contacts and press next or previous, first or last it doesnt read the Name Contact, but it reads everything else...does it have to do something with spacing ? here is what I have...thanks
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ContactSystem extends JFrame{
//Specify the size of five string fields in the record
final static int NAME_SIZE = 32;
final static int TYPE_SIZE = 32;
final static int CITY_SIZE = 20;
final static int PHONE_SIZE = 15;
final static int EMAIL_SIZE = 15;
final static int RECORD_SIZE =
(NAME_SIZE + TYPE_SIZE + CITY_SIZE + PHONE_SIZE + EMAIL_SIZE);
//access contact.dat using RandomAccessFile
private RandomAccessFile raf;
//Text Fields
private JTextField jbtName = new JTextField(NAME_SIZE);
private JTextField jbtType = new JTextField(TYPE_SIZE);
private JTextField jbtCity = new JTextField(CITY_SIZE);
private JTextField jbtPhone = new JTextField(PHONE_SIZE);
private JTextField jbtEmail = new JTextField(EMAIL_SIZE);
//Buttons
private JButton jbtAdd = new JButton("Add");
private JButton jbtFirst = new JButton("First");
private JButton jbtNext = new JButton("Next");
private JButton jbtPrevious = new JButton("Previous");
private JButton jbtLast = new JButton("Last");
public ContactSystem(){
//open or create a random access file
try {
raf = new RandomAccessFile("contact.txt", "rw");
}
catch(IOException ex) {
System.out.print("Error: " + ex);
System.exit(0);
}
//Panel p1 for holding labels Name , Type, Email or phone
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3,1));
p1.add(new JLabel("Name Contact"));
p1.add(new JLabel("Email Address"));
p1.add(new JLabel("Type of Contact"));
//Panel jpPhone for holding Phone
JPanel jpPhone = new JPanel();
jpPhone.setLayout(new BorderLayout());
jpPhone.add(new JLabel("Phone"), BorderLayout.WEST);
jpPhone.add(jbtPhone, BorderLayout.CENTER);
//Panel jpEmail for holding Phone
JPanel jpEmail = new JPanel();
jpEmail.setLayout(new BorderLayout());
jpEmail.add(new JLabel("Phone"), BorderLayout.WEST);
jpEmail.add(jbtEmail, BorderLayout.CENTER);
// Panel p2 for holding jpPhone and jpEmail
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(jpPhone, BorderLayout.WEST);
p2.add(jpPhone, BorderLayout.CENTER);
JPanel p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(jbtCity, BorderLayout.CENTER);
p3.add(p2, BorderLayout.EAST);
//panel p4 for holding jtfName, jtfType, and p3
JPanel p4 = new JPanel();
p4.setLayout(new GridLayout(3,1));
p4.add(jbtName);
p4.add(jbtType);
p4.add(p3);
//place p1 and p4 into jpContact
JPanel jpContact = new JPanel(new BorderLayout());
jpContact.add(p1, BorderLayout.WEST);
jpContact.add(p4, BorderLayout.CENTER);
//set panel with line border
jpContact.setBorder(new BevelBorder(BevelBorder.RAISED));
//add buttons to a panel
JPanel jpButton = new JPanel();
jpButton.add(jbtAdd);
jpButton.add(jbtFirst);
jpButton.add(jbtNext);
jpButton.add(jbtPrevious);
jpButton.add(jbtLast);
//add jpContact and jpButton to the frame
add(jpContact, BorderLayout.CENTER);
add(jpButton, BorderLayout.SOUTH);
jbtAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeContact();
}
});
jbtFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (raf.length() > 0) readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtNext.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if (currentPosition < raf.length())
readContact(currentPosition);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
jbtPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if(currentPosition - 2 * RECORD_SIZE > 0)
//why 2 * 2 * RECORD_SIZE? see the the follow-up remarks
readContact(currentPosition - 2 * 2 * RECORD_SIZE);
else
readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long lastPosition = raf.length();
if(lastPosition > 0)
//why 2 * RECORD_SIZE? see the follow up remarks
readContact(lastPosition - 2 * RECORD_SIZE);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
try {
if (raf.length() > 0) readContact(0);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//write a record at the end of file
public void writeContact() {
try {
raf.seek(raf.length());
FixedLengthStringIO.writeFixedLengthString(
jbtName.getText(), NAME_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtType.getText(), TYPE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtCity.getText(), CITY_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtPhone.getText(), PHONE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtEmail.getText(), EMAIL_SIZE, raf);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//read a contact at the specific position
public void readContact(long position) throws IOException{
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtName.setText(phone);
jbtName.setText(email);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ContactSystem frame = new ContactSystem();
frame.pack();
frame.setTitle("Contact System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
fixedlengthstringIO class
import java.io.*;
public class FixedLengthStringIO {
//read fixed number of characters from datainput stream
public static String readFixedLengthString(int size,
DataInput in) throws IOException {
//declare an array of characters
char[] chars = new char[size];
//read fixed number of characters to the array
for(int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String (chars);
}
//write fixed number of characters to a dataoutput stream
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException {
char[] chars = new char[size];
//fill an array of characters from the string
s.getChars(0, Math.min(s.length(), size), chars, 0);
//fill in blank characters in the rest of the array
for (int i = Math.min(s.length(), size); i < chars.length; i++)
chars[i] = ' ';
//create and write a new string padded with blank characters
out.writeChars(new String(chars));
}
}
here is when I type in contact name, type, email etc into the list
and when I press next or previous, or first or last, it doesnt read the name..
Glitch is in your readContact method, change this
public void readContact(long position) throws IOException {
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtPhone.setText(phone);
jbtEmail.setText(email);
}
Also instead of adding separate ActionListner command button you can implement like
public class ContactSystem extends JFrame implements ActionListener
{
.....
jbtAdd.addActionListener(this);
jbtFirst.addActionListener(this);
.....
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Add")) {
//do add stuff
} else if (actionCommand.equals("First")) {
// move first
}
}
}
I keep getting a stack overflow error when I run this short program I made! please help! Right now all it's supposed to do is take the users input and print their position (in X and Y coordinates). I'm not sure what Stack overflow error is or how to fix it.
import java.awt.*;
import javax.swing.*;
public class ExplorerPanel extends JFrame {
ExplorerEvent prog = new ExplorerEvent(this);
JTextArea dataa = new JTextArea(15, 20);
JTextField datain = new JTextField(20);
JButton submit = new JButton("Submit");
JTextField errors = new JTextField(30);
public ExplorerPanel() {
super("Explorer RPG");
setLookAndFeel();
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_…
BorderLayout bord = new BorderLayout();
setLayout(bord);
JPanel toppanel = new JPanel();
toppanel.add(dataa);
add(toppanel, BorderLayout.NORTH);
JPanel middlepanel = new JPanel();
middlepanel.add(datain);
middlepanel.add(submit);
add(middlepanel, BorderLayout.CENTER);
JPanel bottompanel = new JPanel();
bottompanel.add(errors);
add(bottompanel, BorderLayout.SOUTH);
dataa.setEditable(false);
errors.setEditable(false);
submit.addActionListener(prog);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLo…
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] args) {
ExplorerPanel frame = new ExplorerPanel();
}
}
public class ExplorerEvent implements ActionListener, Runnable {
ExplorerPanel gui;
Thread playing;
String command;
String gamedata;
ExplorerGame game = new ExplorerGame();
public ExplorerEvent(ExplorerPanel in) {
gui = in;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Submit")) {
startPlaying();
}
}
void startPlaying() {
playing = new Thread(this);
playing.start();
}
void stopPlaying() {
playing = (null);
}
void clearAllFields() {
gui.dataa.setText("");
}
public void run() {
Thread thisThread = Thread.currentThread();
while (playing == thisThread) {
// Game code
game.Game();
}
}
}
public class ExplorerGame {
ExplorerPanel gui = new ExplorerPanel();
String command;
int x = 1;
int y = 1;
public void Game() {
command = gui.submit.getText().toLowerCase();
if (command.equals("east")) {x--;}
else if (command.equals("south")) {y--;}
else if (command.equals("west")) {x++;}
else if (command.equals("north")) {y++;}
System.out.println(x + y);
}
}
In ExplorerGame, you have declared: -
ExplorerPanel gui = new ExplorerPanel();
then, in ExplorerPanel: -
ExplorerEvent prog = new ExplorerEvent(this);
and then again, in ExplorerEvent: -
ExplorerGame game = new ExplorerGame();
This will fill the Stack with recursive creation of objects.
ExplorerGame -> ExplorerPanel -> ExplorerEvent --+
^ |
|____________________________________________|
You want to solve the Issue?
I'll Suggest you: -
Throw away the code, and re-design your application. Having a cyclic dependency in your application is a big loop hole, showing a very poor design.
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);
}
}