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
}
}
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);
This project requires that a user inputs data into text fields on a dialog box accessed from a menu bar and places the data from the text fields into a JTable. The problem is that once the user clicks okay on the dialog box after putting the information into the text field, the dialog box is no longer visible, but nothing appears in the JTable. The JTable headers are there, but the info just submitted is not.
It is a camping registration program, and all of the classes compile okay. I am only working on taking information from an RV reservation first, but will eventually do the same for a tent reservation. Here are the classes that correspond to an RV check in. There is an RV constructor that has parameters (String (name), String (check in day), int (days staying), String (leave day), int (site number), int (power needed)).
First the dialog box class:
package campingPrj;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogCheckInRv extends javax.swing.JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
private javax.swing.JTextField nameTxt;
private javax.swing.JTextField dateIn;
private javax.swing.JTextField stayingTxt;
private javax.swing.JTextField siteNumberTxt;
private javax.swing.JTextField checkOutDate;
private javax.swing.JTextField powerTxt;
private javax.swing.JButton okButton;
private javax.swing.JButton cancelButton;
private boolean cancel;
private boolean okay;
public DialogCheckInRv(java.awt.Frame parent) {
super(parent, true);
setupDialog();
setTitle("RV Check In");
}
private void setupDialog() {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
nameTxt = new javax.swing.JTextField(27);
dateIn = new javax.swing.JTextField(25);
stayingTxt = new javax.swing.JTextField(25);
siteNumberTxt = new javax.swing.JTextField(27);
powerTxt = new javax.swing.JTextField(27);
okButton = new javax.swing.JButton("Ok");
okButton.addActionListener(this);
cancelButton = new javax.swing.JButton("Cancel");
cancelButton.addActionListener(this);
setLayout(new GridLayout(6, 1));
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Name Reserving:"));
panel.add(nameTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Start Date (mm/dd/yy) :"));
panel.add(dateIn);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Days Planning on Staying:"));
panel.add(stayingTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Requested Site Number:"));
panel.add(siteNumberTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Power Needed (in AMPs):"));
panel.add(powerTxt);
add(panel);
panel = new JPanel();
panel.add(okButton);
panel.add(cancelButton);
add(panel);
pack();
setLocationRelativeTo(null);
}
public void actionPerformed(java.awt.event.ActionEvent event) {
if (event.getSource() == okButton) {
okay = true;
cancel = false;
setVisible(false);
}
if (event.getSource() == cancelButton) {
okay = false;
cancel = true;
setVisible(false);
}
}
public boolean isOk() {
return okay;
}
public boolean isCancel() {
return cancel;
}
public String getName() {
return nameTxt.getText();
}
public String getDateIn() {
return dateIn.getText();
}
public String getDaysStaying() {
return stayingTxt.getText();
}
public String getCheckOutDate() {
return checkOutDate.getText();
}
public String getPower() {
return powerTxt.getText();
}
public String getSiteNumber() {
return siteNumberTxt.getText();
}
public void clear() {
nameTxt.setText(null);
dateIn.setText(null);
stayingTxt.setText(null);
dateIn.setText(null);
powerTxt.setText(null);
siteNumberTxt.setText(null);
}
}
The GUI with the table (where I'm guessing the problem is in the actionPerformed method):
package campingPrj;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUICampingReg extends javax.swing.JFrame implements ActionListener {
private JMenuItem openSerialFileItem = new JMenuItem("Open Serialized File");
private JMenuItem openTextFileItem = new JMenuItem("Open Text File");
private JMenuItem saveSerialFileItem = new JMenuItem("Save Serialized File");
private JMenuItem saveTextFileItem = new JMenuItem("Save Text File");
private JMenuItem exitItem = new JMenuItem("Exit");
private JMenuItem checkInTentItem = new JMenuItem("Check in tent");
private JMenuItem checkInRVItem = new JMenuItem("Check in RV");
private JMenuItem checkOutItem = new JMenuItem("Date Leaving");
private JTextField nameReservingTxt;
private JTextField dateInTxt;
private JTextField daysStayingTxt;
private JTextField checkOutOnTxt;
private JTextField siteNumberTxt;
private JTextField powerTxt;
private JFrame frame;
private JTable table;
private SiteModel model;
private JScrollPane scrollPane;
private DialogCheckInRv newRv;
public GUICampingReg() {
setupFrame();
newRv = new DialogCheckInRv(this);
model = new SiteModel();
table.setModel(model);
}
private void setupFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Camping Registration Program");
scrollPane = new JScrollPane();
table = new JTable();
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(openSerialFileItem);
fileMenu.add(openTextFileItem);
fileMenu.add(saveSerialFileItem);
fileMenu.add(saveTextFileItem);
fileMenu.add(exitItem);
JMenu checkInMenu = new JMenu("Check In");
checkInMenu.add(checkInRVItem);
checkInMenu.add(checkInTentItem);
JMenu checkOutMenu = new JMenu("Check Out");
checkOutMenu.add(checkOutItem);
menubar.add(fileMenu);
menubar.add(checkInMenu);
menubar.add(checkOutMenu);
openSerialFileItem.addActionListener(this);
openTextFileItem.addActionListener(this);
saveSerialFileItem.addActionListener(this);
saveTextFileItem.addActionListener(this);
exitItem.addActionListener(this);
checkInTentItem.addActionListener(this);
checkInRVItem.addActionListener(this);
checkOutItem.addActionListener(this);
frame.setJMenuBar(menubar);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setToolTipText("");
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked();
}
});
scrollPane.setViewportView(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void tableMouseClicked() {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent evt) {
Object pressed = evt.getSource();
if (pressed == exitItem) {
System.exit(0);
}
if (pressed == openSerialFileItem) {
}
if (pressed == openTextFileItem) {
}
if (pressed == saveSerialFileItem) {
}
if (pressed == saveTextFileItem) {
}
if (pressed == checkInTentItem) {
}
if (pressed == checkInRVItem) {
newRv.clear();
newRv.setVisible(true);
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
}
if (pressed == checkOutItem) {
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUICampingReg();
}
});
}
}
The site model class:
package campingPrj;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class SiteModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private ArrayList<Site> listSites;
private String[] columnNames = { "Name Reserving", "Checked in Date",
"Days Staying", "Site #", "Tenters/RV Power Needed" };
public SiteModel() {
listSites = new ArrayList<Site>();
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return listSites.size();
}
public Object getValueAt(int row, int col) {
Object val = null;
switch (col) {
case 0:
val = listSites.get(row).getNameReserving();
break;
case 1:
val = listSites.get(row).getCheckIn();
break;
case 2:
val = listSites.get(row).getDaysStaying();
break;
case 3:
val = listSites.get(row).getSiteNumber();
break;
case 4:
val = listSites.get(row).getCheckOutOn();
break;
}
return val;
}
public Site get(int index) {
return listSites.get(index);
}
public int indexOf(Site s) {
return listSites.indexOf(s);
}
public void add(Site s) {
if (s != null) {
listSites.add(s);
fireTableRowsInserted(listSites.size() - 1, listSites.size() - 1);
}
}
public void add(int index, Site s) {
if (s != null) {
listSites.add(index, s);
fireTableRowsInserted(index, index);
}
}
public void remove(int index) {
listSites.remove(index);
fireTableRowsDeleted(index, index);
return;
}
public void remove(Site s) {
remove(indexOf(s));
}
public void saveAsSerialized(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(listSites);
os.close();
}
#SuppressWarnings("unchecked")
public void loadFromSerialized(String filename) throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream is = new ObjectInputStream(fis);
listSites = (ArrayList<Site>) is.readObject();
is.close();
}
}
So, how do I get the information to show up in JTable?
Maybe I'm misinterpreting your code, but I don't see where you areextracting the information that the user enters into the dialog. For example here:
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
You appear to be extracting information from the fields held by the GUICampingReg, not by the newRv object. Shouldn't you be calling methods of newRv to extract the data needed to create your RV object?
for example,
if (newRv.isOk()) {
String nameReserving = newRv.getName();
String checkIn = newRv.getDateIn();
// .... etc
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
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. :)
I'm working on a calculator application (which I have simplified downed to make it easier to debug). When the user hits '=' the IMPORTANTINT will change to 1. When the users clicks another button the field is supposed to clear with the if then statement in CalculatorEngine:
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
This is done so the user can view the result and then start a new calculation. The textField doesn't want to clear. Does anyone know why this is? Thanks!
CalculatorEngine.java
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener{
Calculator parent;
double firstNum, secondNum;
String symbol;
int IMPORTANTINT = 0;
CalculatorEngine(Calculator parent){
this.parent = parent;
}
public void actionPerformed(ActionEvent e){
JButton clickedButton = (JButton) e.getSource();
String clickedButtonLabel = clickedButton.getText();
String dispFieldText = parent.getDisplayValue();
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
if(clickedButtonLabel == "+"){
firstNum = (Double.parseDouble(parent.getDisplayValue()));
parent.setDisplayValue("");
symbol = clickedButtonLabel;
} else if(clickedButtonLabel == "="){
IMPORTANTINT = 1;
secondNum = Double.parseDouble(parent.getDisplayValue());
double answer = firstNum + secondNum;
parent.setDisplayValue(Double.toString(answer));
} else{
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
}
Calculator.java
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class Calculator {
private JPanel windowContent;
private JPanel p1;
private JPanel sideBar;
private JTextField displayField;
private JButton button8;
private JButton button9;
private JButton buttonEqual;
private JButton buttonPlus;
Calculator(){
windowContent= new JPanel();
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
displayField = new JTextField(30);
windowContent.add("North",displayField);
button8=new JButton("8");
button9=new JButton("9");
buttonEqual=new JButton("=");
buttonPlus = new JButton("+");
p1 = new JPanel();
GridLayout gl =new GridLayout(4,3);
p1.setLayout(gl);
sideBar = new JPanel();
GridLayout gl2 = new GridLayout(5,1);
sideBar.setLayout(gl2);
p1.add(button8);
p1.add(button9);
p1.add(buttonEqual);
sideBar.add(buttonPlus);
windowContent.add("Center", p1);
windowContent.add("East", sideBar);
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
frame.pack();
frame.setVisible(true);
CalculatorEngine calcEngine = new CalculatorEngine(this);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
}
public void setDisplayValue(String val){
displayField.setText(val);
}
public String getDisplayValue(){
return displayField.getText();
}
public static void main(String[] args)
{
Calculator calc = new Calculator();
}
}
public void setDisplayValue(String val){
SwingUtilities.invokeLater(new Runnable{
#Override
public void run()
{
displayField.setText(val);
}
});
}
You are effectively caching the dispFieldText before entering the IMPORTANTINT if statement block. Therefore the JTextField is being cleared but subsequently then to the cached value in the else block.
if (IMPORTANTINT == 1) {
dispFieldText = ""; // add this
...
}
if (clickedButtonLabel.equals("+")) {
...
} else if (clickedButtonLabel.equals("=")) {
...
} else {
// Field being reset here vvvv
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
Make sure to clear the variable. Use String#equals to check String content. The == operator checks Object references.
Aside: Use Java naming conventions, IMPORTANTINT is a modifiable variable so should be importantInt (A boolean typically handles a true/false scenario)
I have been working on a personal project to get better with programming. My goal is to make it much more robust, I am just starting. I am a current computer science student. Anyway, I am working on making a portion of the program as shown. I calculates the hourly wage and provides some outputs I havent implemented yet. I'm using DocumentListener so it it will automatically calculate. I am getting an error when the the text is removed completely from a box.I tried to fix it with the if statement:
if (tipMon.equals("") || tipMon == null) {
tipMon.setText("0");
}
Here is what I have so far. It's not done yet and I apologize for the noob code. I started 2 months ago with actual coding.
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.FieldView;
public class deliveryDocListener extends JFrame implements ActionListener,
DocumentListener{
private JLabel mon, tues, wed, thurs, fri, sat, sun, hourlyWage, blank, row2, monWage,
tuesWage,wedWage,thursWage, friWage, satWage, sunWage, total, totalTips, totalHours,
totalHourlyEarnings, totalPay, weekPay;
private JTextField hourlyWageInput, tipMon, tipTues, tipWed, tipThurs, tipFri, tipSat, tipSun,
hourMon, hourTues, hourWed, hourThurs, hourFri, hourSat, hourSun;
public deliveryDocListener(){
super("Delivery Helper v0.1 Alpha");
setLayout(new GridLayout(0,4));
hourlyWage = new JLabel("Hourly Wage: ");
add(hourlyWage);
hourlyWageInput = new JTextField("7.25", 5);
add(hourlyWageInput);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
row2 = new JLabel("Day of the Week");
add(row2);
row2 = new JLabel("Tips");
add(row2);
row2 = new JLabel("Hours Worked");
add(row2);
row2 = new JLabel("Hourly Earnings");
add(row2);
mon = new JLabel("Monday");
add(mon);
tipMon = new JTextField("0");
Document tipMonListener = tipMon.getDocument();
//Document class doc variable stores what happens in the getDocument()
//method, getDocument() i think is what checked it real time we shall see
tipMonListener.addDocumentListener(this);
//add listener to he text field, this refers to most recent object (tipMon = new JTextField("0");"
//notice how its purple is the same as new where the object got made?
add(tipMon);
hourMon = new JTextField("0");
Document hourMonListener = hourMon.getDocument();
hourMonListener.addDocumentListener(this);
add(hourMon);
monWage = new JLabel("0");
add(monWage);
tues = new JLabel("Tuesday");
add(tues);
tipTues = new JTextField("0");
add(tipTues);
hourTues = new JTextField("0");
add(hourTues);
tuesWage = new JLabel("0");
add(tuesWage);
wed = new JLabel("Wednesday");
add(wed);
tipWed = new JTextField("0");
add(tipWed);
hourWed = new JTextField("0");
add(hourWed);
wedWage = new JLabel("0");
add(wedWage);
thurs = new JLabel("Thursday");
add(thurs);
tipThurs = new JTextField("0");
add(tipThurs);
hourThurs = new JTextField("0");
add(hourThurs);
thursWage = new JLabel("0");
add(thursWage);
fri = new JLabel("Friday");
add(fri);
tipFri = new JTextField("0");
add(tipFri);
hourFri = new JTextField("0");
add(hourFri);
friWage = new JLabel("0");
add(friWage);
sat = new JLabel("Saturday");
add(sat);
tipSat = new JTextField("0");
add(tipSat);
hourSat = new JTextField("0");
add(hourSat);
satWage = new JLabel("0");
add(satWage);
sun = new JLabel("Sunday");
add(sun);
tipSun = new JTextField("0");
add(tipSun);
hourSun = new JTextField("0");
add(hourSun);
sunWage = new JLabel("0");
add(sunWage);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
total = new JLabel("Total: ");
add(total);
totalTips = new JLabel("totalTipsOutput");
add(totalTips);
totalHours = new JLabel("totalHoursOutput");
add(totalHours);
totalHourlyEarnings = new JLabel("totalHourlyEarningsOutput");
add(totalHourlyEarnings);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
blank = new JLabel();
add(blank);
totalPay = new JLabel("Gross Income: ");
add(totalPay);
weekPay = new JLabel("totalPayOutput");
add(weekPay);
}
#Override
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
#Override
public void insertUpdate(DocumentEvent e) {
//executes when someone enters text into input
String tipMonStr = tipMon.getText();
//monWage.setText(tipMonStr);
String hourMonStr = hourMon.getText();
double x = Double.parseDouble(tipMonStr);
double y = Double.parseDouble(hourMonStr);
double z = Double.parseDouble(hourlyWageInput.getText());
if (tipMonStr.length() == 0) {
tipMon.setText("0");
}
if (hourMonStr.length() == 0) {
y = 0;
hourMonStr = "0";
}
if (hourlyWageInput.getText().length() == 0) {
z = 0;
//String z = "0";
}
monWage.setText(Double.toString((z*y+x)/y));
//bug when nothing in cell because no number (0) to use in math
}
#Override
public void removeUpdate(DocumentEvent e) {
//executes when someone enters text into input
String tipMonStr = tipMon.getText();
//monWage.setText(tipMonStr);
String hourMonStr = hourMon.getText();
double x = Double.parseDouble(tipMonStr);
double y = Double.parseDouble(hourMonStr);
double z = Double.parseDouble(hourlyWageInput.getText());
monWage.setText(Double.toString((z*y+x)/y));
if (tipMon.equals("") || tipMon == null) {
tipMon.setText("0");
}
}
public void updateLog(DocumentEvent e, String action) {
monWage.setText(Double.toString(5));
}
#Override
public void actionPerformed(ActionEvent arg0) {
monWage.setText(Double.toString(5));
}
}
As #HFOE suggests, InputVerifier is the right choice, but verify() "should have no side effects." Instead, invoke calcProduct() in shouldYieldFocus().
/**
* #see http://stackoverflow.com/a/11818946/230513
*/
private class MyInputVerifier extends InputVerifier {
private JTextField field;
private double value;
public MyInputVerifier(JTextField field) {
this.field = field;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
if (verify(input)) {
field.setText(String.valueOf(value));
calcProduct();
return true;
} else {
field.setText(ZERO);
field.selectAll();
return false;
}
}
#Override
public boolean verify(JComponent input) {
try {
value = Double.parseDouble(field.getText());
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
I'll make this an answer: I wouldn't use a DocumentListener for this purpose as it seems to me the wrong tool for the job. For one, it is continually listening and updating the results while the user is still entering data, data that is as yet incomplete, into the JTextField. Much better would be to use an ActionListener added to a JButton or to your JTextFields.
I suppose you could use a FocusListener, but even that concerns me since it is quite low-level.
Also: consider using an InputVerifier to validate your input.
Also: consider displaying your tabular data in a JTable where the 1st and 2nd columns are editable but the others are not.
Edit
I'm not sure if this is kosher, but it could work if you do your calculation from within the verifier. For example, updated for generality:
import javax.swing.*;
/**
* #see http://stackoverflow.com/a/11818183/522444
*/
public class VerifierEg {
private static final String ZERO = "0.0";
private JTextField field1 = new JTextField(ZERO, 5);
private JTextField field2 = new JTextField(ZERO, 5);
private JTextField resultField = new JTextField(ZERO, 10);
private void createAndShowGui() {
resultField.setEditable(false);
resultField.setFocusable(false);
JPanel mainPanel = new JPanel();
final JTextField[] fields = {field1, field2};
mainPanel.add(field1);
mainPanel.add(new JLabel(" x "));
mainPanel.add(field2);
mainPanel.add(new JLabel(" = "));
mainPanel.add(resultField);
for (JTextField field : fields) {
field.setInputVerifier(new MyInputVerifier(field));
}
JFrame frame = new JFrame("VerifierEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void calcProduct() {
double d1 = Double.parseDouble(field1.getText());
double d2 = Double.parseDouble(field2.getText());
double prod = d1 * d2;
resultField.setText(String.valueOf(prod));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
VerifierEg eg = new VerifierEg();
eg.createAndShowGui();
}
});
}
/**
* #see http://stackoverflow.com/a/11818946/230513
*/
private class MyInputVerifier extends InputVerifier {
private JTextField field;
private double value;
public MyInputVerifier(JTextField field) {
this.field = field;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
if (verify(input)) {
field.setText(String.valueOf(value));
calcProduct();
return true;
} else {
field.setText(ZERO);
field.selectAll();
return false;
}
}
#Override
public boolean verify(JComponent input) {
try {
value = Double.parseDouble(field.getText());
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
}
use JSpinner or JFormattedTextField with Number instance, then DocumentListener should be works correctly, no needed to parse String to Number instance
otherwise you have to use DocumentFilter for JTextField for filtering non numeric chars, rest (counting) stays unchanged, stil required robust parsing String to the Number instance