I am trying to add a class for each course in the drop down menu on the right corner of the image, as shown in the code in the action Performed there is one class but the same class opens for all the courses so how can i make each one of them open a different class?
this part is confusing me im not sure if i need to do anything with it or not
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
the list of courses in the left corner works perfectly fine with me but my only problem is instead of the list on the left i want the list on the right to work and it has something to do with crse
public class CourseWork extends JFrame implements ActionListener, KeyListener {
CommonCode cc = new CommonCode();
JPanel pnl = new JPanel(new BorderLayout());
JTextArea txtNewNote = new JTextArea();
JTextArea txtDisplayNotes = new JTextArea();
JTextField search = new JTextField();
ArrayList<String> note = new ArrayList<>();
ArrayList<String> course = new ArrayList<>();
JComboBox courseList = new JComboBox();
String crse = "";
AllNotes allNotes = new AllNotes();
public static void main(String[] args) {
// This is required for the coursework.
//JOptionPane.showMessageDialog(null, "Racha Chaouby");
CourseWork prg = new CourseWork();
}
// Using MVC
public CourseWork() {
model();
view();
controller();
}
#Override
public void actionPerformed(ActionEvent ae) {
if ("Close".equals(ae.getActionCommand())) {
}
if ("Course".equals(ae.getActionCommand())) {
crse = courseList.getSelectedItem().toString();
COMP1752 cw = new COMP1752();
}
if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
}
if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
}
if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
}
if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
if ("Course1752".equals(ae.getActionCommand())) {
COMP1752 cw = new COMP1752();
}
if ("Course1753".equals(ae.getActionCommand())) {
COMP1753 cw = new COMP1753();
}
if ("Cours1110".equals(ae.getActionCommand())) {
MATH1110 cw = new MATH1110();
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped not coded yet.");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed not coded yet.");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased not coded yet.");
}
private void model() {
course.add("COMP1752");
course.add("COMP1753");
course.add("MATH1110");
crse = course.get(0);
//Note nt = new Note();
//nt.noteID = 1;
//t.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "Arrays are of fixed length and are inflexible.";
//allNotes.allNotes.add(nt);
//nt = new Note();
//nt.noteID = 2;
//nt.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "ArraysList can be added to and items can be deleted.";
//allNotes.allNotes.add(nt);
}
private void view() {
Font fnt = new Font("Georgia", Font.PLAIN, 24);
JMenuBar menuBar = new JMenuBar();
JMenu kurs = new JMenu();
kurs = new JMenu("Courses");
kurs.setToolTipText("Course tasks");
kurs.setFont(fnt);
kurs.add(makeMenuItem("COMP1752", "Course1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("COMP1753", "Course1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("MATH1110", "Course1110", "Coursework requirments.", fnt));
menuBar.add(kurs);
JMenu note = new JMenu();
note = new JMenu("Note");
note.setToolTipText("Note tasks");
note.setFont(fnt);
note.add(makeMenuItem("New", "NewNote", "Create a new note.", fnt));
note.addSeparator();
note.add(makeMenuItem("Close", "Close", "Clear the current note.", fnt));
menuBar.add(note);
menuBar.add(makeMenuItem("Exit", "Exit", "Close this program", fnt));
// This will add each course to the combobox
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
this.setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar();
// Setting up the ButtonBar
JButton button = null;
button = makeButton("Document", "Coursework",
"Open the coursework window.",
"Coursework");
toolBar.add(button);
button = makeButton("Create", "NewNote",
"Create a new note.",
"New");
toolBar.add(button);
button = makeButton("closed door", "Close",
"Close this note.",
"Close");
toolBar.add(button);
toolBar.addSeparator();
button = makeButton("exit button", "Exit",
"Exit from this program.",
"Exit");
toolBar.add(button);
toolBar.addSeparator();
// This forces anything after it to the right.
toolBar.add(Box.createHorizontalGlue());
search.setMaximumSize(new Dimension(6900, 30));
search.setFont(fnt);
toolBar.add(search);
toolBar.addSeparator();
button = makeButton("search", "SearchKeyword",
"Search for this text.",
"Search");
toolBar.add(button);
add(toolBar, BorderLayout.NORTH);
JPanel pnlWest = new JPanel();
pnlWest.setLayout(new BoxLayout(pnlWest, BoxLayout.Y_AXIS));
pnlWest.setBorder(BorderFactory.createLineBorder(Color.black));
txtNewNote.setFont(fnt);
pnlWest.add(txtNewNote);
JButton btnAddNote = new JButton("Add note");
btnAddNote.setActionCommand("NewNote");
btnAddNote.addActionListener(this);
pnlWest.add(btnAddNote);
add(pnlWest, BorderLayout.WEST);
JPanel cen = new JPanel();
cen.setLayout(new BoxLayout(cen, BoxLayout.Y_AXIS));
cen.setBorder(BorderFactory.createLineBorder(Color.black));
txtDisplayNotes.setFont(fnt);
cen.add(txtDisplayNotes);
add(cen, BorderLayout.CENTER);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Coursework");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Needed to ensure that the items can be seen.
}
private void controller() {
addAllNotes();
}
protected JMenuItem makeMenuItem(
String txt,
String actionCommand,
String toolTipText,
Font fnt) {
JMenuItem mnuItem = new JMenuItem();
mnuItem.setText(txt);
mnuItem.setActionCommand(actionCommand);
mnuItem.setToolTipText(toolTipText);
mnuItem.setFont(fnt);
mnuItem.addActionListener(this);
return mnuItem;
}
protected JButton makeButton(
String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Create and initialize the button.
JButton button = new JButton();
button.setToolTipText(toolTipText);
button.setActionCommand(actionCommand);
button.addActionListener(this);
//Look for the image.
String imgLocation = System.getProperty("user.dir")
+ "\\icons\\"
+ imageName
+ ".png";
File fyle = new File(imgLocation);
if (fyle.exists() && !fyle.isDirectory()) {
// image found
Icon img;
img = new ImageIcon(imgLocation);
button.setIcon(img);
} else {
// image NOT found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
private void addNote(String text) {
allNotes.addNote(allNotes.getMaxID(), crse, text);
addAllNotes();
}
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotes()) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
public String getDateAndTime() {
String UK_DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
String ukDateAndTime;
Calendar cal = Calendar.getInstance();
SimpleDateFormat uksdf = new SimpleDateFormat(UK_DATE_FORMAT_NOW);
ukDateAndTime = uksdf.format(cal.getTime());
return ukDateAndTime;
}
}
code snippet
this is the AllNotes class:
public class AllNotes extends CommonCode {
private ArrayList<Note> allNotes = new ArrayList<>();
private String crse = "";
private int maxID = 0;
AllNotes() {
readAllNotes();
}
public final int getMaxID() {
maxID++;
return maxID;
}
private void readAllNotes() {
ArrayList<String> readNotes = new ArrayList<>();
readNotes = readTextFile(appDir + fileSeparator + "Notes.txt");
System.out.println(readNotes.get(0));
if (!"File not found".equals(readNotes.get(0))) {
allNotes.clear();
for (String str : readNotes) {
String[] tmp = str.split("\t");
int nid = Integer.parseInt(tmp[0]);
Note n = new Note(nid, tmp[1], tmp[2], tmp[3]);
allNotes.add(n);
if (nid > maxID) {
maxID = nid;
}
}
}
maxID++;
}
public void addNote(int maxID, String course, String note) {
Note myNote = new Note(maxID, course, note);
allNotes.add(myNote);
writeAllNotes();
}
public ArrayList<Note> getAllNotes() {
return allNotes;
}
private void writeAllNotes() {
String path = appDir + fileSeparator +"Notes.txt";
ArrayList<String> writeNote = new ArrayList<>();
for (Note n : allNotes) {
String tmp = n.getNoteID() + "\t";
tmp += n.getCourse() + "\t";
tmp += n.getDayte() + "\t";
tmp += n.getNote();
writeNote.add(tmp);
}
try {
writeTextFile(path, writeNote);
} catch (IOException ex) {
System.out.println("Problem! " + path);
}
}
public String searchAllNotesByKeyword(String noteList, int i, String s) {
if (i == allNotes.size()) {
return noteList;
}
if (allNotes.get(i).getNote().contains(s)) {
noteList += allNotes.get(i).getNote() + "\n";
}
return searchAllNotesByKeyword(noteList, i + 1, s);
}
}
When you init your drop down of courses, set the action command to be the same value that you record in your file, this will make everything consistent when looking up notes from the file. so this way
kurs.add(makeMenuItem("Course 1752", "COMP1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1753", "COMP1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1110", "MATH1110", "Coursework requirments.", fnt));
Then change actionPerformed to store the selected value form the drop down to the crse attribute, and call addAllNotes() to refresh the notes list
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("actionPerformed: " + ae.getActionCommand());
if ("Close".equals(ae.getActionCommand())) {
} else if ("Course".equals(ae.getActionCommand())) {
// set the value of the selected element into the crse attribute
crse = courseList.getSelectedItem().toString();
// Refresh the text area
addAllNotes();
} else if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
} else if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
} else if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
} else if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
System.out.println("selectedCourse: " + crse);
}
in AllNotes, create a new method to return the notes for a specific course.
public ArrayList<Note> getAllNotesForCourse(String course) {
ArrayList<Note> notes = new ArrayList<>();
for(Note note : allNotes) {
if(course.equalsIgnoreCase(note.getCourse())) {
notes.add(note);
}
}
return notes;
}
then in the addAllNotes method, call getAllNotesForCourse, passing the selected course. This will update txtDisplayNotes with the notes from the selected course
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotesForCourse(crse)) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
I think this is all I modified and it works for me.
Related
I am working on a school project using BlueJay and I have created two classes in package Logic which are the Game class, and the VectorGames class.
In my package GUI, I created a class called AddGame and ViewGame class.
The issue that I have encountered is that, when I click the Save Button on Addgame, it saves the file only once. When I try to save it doesn't do or say anything it just stays there returning nothing. Another issue encountered is that on ViewGame, the gameType column is remaining empty ( this is from combo type box )
AddGame code :
package GUI;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import Logic.*;
public class AddGame extends JFrame implements ActionListener{
private JPanel north, south, east, west, center;
private JLabel titleLabel, westLabel, eastLabel;
private JTextField gameNameFld, gameKeyFld;
private JComboBox gameTypeCombo;
private JButton saveButton, clearButton;
private VectorGames vg;
public AddGame(){
super("Adding a Game");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
//north panel
north = new JPanel();
this.add(north,BorderLayout.NORTH);
titleLabel = new JLabel("Add a game below");
titleLabel.setFont(new Font("Verdana",Font.BOLD,20));
titleLabel.setForeground(Color.black);
north.add(titleLabel);
//west and east panels
west = new JPanel();
east = new JPanel();
this.add(west, BorderLayout.WEST);
this.add(east, BorderLayout.EAST);
westLabel = new JLabel(" ");
eastLabel = new JLabel(" ");
west.add(westLabel);
east.add(eastLabel);
//center panel
center = new JPanel();
this.add(center, BorderLayout.CENTER);
center.setLayout(new GridLayout(4,2,0,20));
gameNameFld = new JTextField();
gameKeyFld = new JTextField();
gameTypeCombo = new JComboBox();
gameTypeCombo.setModel(new DefaultComboBoxModel(new String[]
{"<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay"}));
center.add(createLabel("Game Name"));
center.add(gameNameFld);
center.add(createLabel("Game Key"));
center.add(gameKeyFld);
center.add(createLabel("Game Type"));
center.add(gameTypeCombo);
//south panel
south = new JPanel();
south.setLayout(new FlowLayout());
this.add(south, BorderLayout.SOUTH);
clearButton = new JButton("Clear");
south.add(clearButton);
clearButton.addActionListener(this);
saveButton = new JButton("Save");
south.add(saveButton);
saveButton.addActionListener(this);
this.setSize(300,400);
this.setLocation(50,50);
this.setVisible(true);
}
private JLabel createLabel(String title){
return new JLabel(title);
}
private void clearFields(){
gameNameFld.setText("");
gameKeyFld.setText("");
gameTypeCombo.setSelectedIndex(0);
}
private boolean validateForm(){
boolean flag = false;
if(gameNameFld.getText().equals("")||gameKeyFld.getText().equals("")||
gameTypeCombo.getSelectedIndex()==0){
flag = true;
}
return flag;
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == clearButton){
clearFields();
}
if(event.getSource() == saveButton){
if(validateForm() == true){
JOptionPane.showMessageDialog(null,"You have empty fields",
"Empty Fields", JOptionPane.ERROR_MESSAGE);
} else if(vg.checkGamebyGameKey(gameKeyFld.getText()) == true){
JOptionPane.showMessageDialog(null,"Game Key already exists!",
"Game Key Check", JOptionPane.ERROR_MESSAGE);
} else {
Game tempGame = new Game(gameNameFld.getText(),gameKeyFld.getText(),
(String)gameTypeCombo.getSelectedItem());
vg.addGame(tempGame);
vg.saveToFile();
JOptionPane.showMessageDialog(null, "Game added successfully!", "Adding a Game",
JOptionPane.INFORMATION_MESSAGE);
clearFields();
}
}
}
}
ViewGame code:
package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import Logic.*;
public class ViewGame extends JFrame {
private JTable table;
private VectorGames vg;
public ViewGame(){
super("Viewing Games by Name");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
vg.sortGamesByName();
int numOfGames = vg.getVectorSize();
int count = 0;
Game tempGame = new Game();
String[] tableHeader = {"Game Name", "Game Type", "Game Key"};
Object [][] tableContent = new Object[numOfGames][3];
for(int i = 0; i < numOfGames; i++){
tempGame = vg.getGamesByIndex(count);
tableContent[i][0] = tempGame.getGameName();
tableContent[i][2] = tempGame.getGameType();
tableContent[i][1] = tempGame.getGameKey();
}
table = new JTable (tableContent, tableHeader);
JScrollPane scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(500, 400));
this.add(table.getTableHeader(), BorderLayout.NORTH);
this.add(table, BorderLayout.CENTER);
this.setSize(500,600);
this.setLocation(100,50);
this.setVisible(true);
}
}
Game code:
package Logic;
import java.io.*;
public class Game implements Serializable{ // Using serializable to allow easy save and read access
//Initializing variables related to Game
private String gameName, gameKey, gameType;
//Creating a constructor with the parameters for class Games
public Game(String gameName, String gamekey, String gameType){
setGameName(gameName);
setGameKey(gameKey);
setGameType(gameType);
}
//Setting up a parameterless constructor for class Games
public Game(){
}
public String getGameName(){//Get Method for gameName
return gameName;
}
public String getGameKey(){//Get Method for gameKey
return gameKey;
}
public String getGameType(){//Get Method for gameType
return gameType;
}
public void setGameName(String gameName){//Set Method for gameName
this.gameName = gameName;
}
public void setGameKey(String gameKey){//Set Method for gameKey
this.gameKey = gameKey;
}
public void setGameType(String gameType){//Set Method for gameType
this.gameType = gameType;
}
public String toString(){
return "Game Name : " + gameName + "\nGame Key : "
+ gameKey + "\nGame Type ; " + gameType;
}
}
VectorGames code:
package Logic;
import java.util.*;
import java.io.*;
import java.lang.*;
public class VectorGames extends IOException{
/* Add a Game, Remove a Game, getVectorGame Size, print allGamesAvailable,
* saveToFile , searchGame and return boolean literal, searchGame and return
* client object, sort games, readFromFile.
*
*/
private Vector<Game> games;
public VectorGames(){
games = new Vector<Game>();
}
//Adding a Game
public void addGame(Game game){
games.add(game);
}
public void deleteGame(Game game){
games.remove(game);
}
public int getVectorSize(){
return games.size();
}
public void clearVector(){
games.clear();
}
public void printGames(){
for(Game tempGame : games){
System.out.println(tempGame.toString());
System.out.println("");
}
}
public Game getGamesByIndex(int i){
Game tempGame = new Game();
if (i < getVectorSize()){
tempGame = games.get(i);
}
return tempGame;
}
public void sortGamesByName(){
Game currentGame = new Game();
Game nextGame = new Game();
Game tempGame = new Game();
for(int i = 0; i < getVectorSize(); i++){
for(int j = 0; j < getVectorSize()-i-1; j++){
currentGame = games.elementAt(j);
nextGame = games.elementAt(j+1);
if(currentGame.getGameName().compareTo(nextGame.getGameName())>0){
tempGame = currentGame;
games.setElementAt(nextGame, j);
games.setElementAt(tempGame, j+1);
}
}
}
}
public boolean checkGamebyGameKey(String gameKey){
boolean flag = false;
for(Game tempGames : games){
if(tempGames .getGameKey().equals(gameKey)){
flag = true;
}
}
return flag;
}
public Game accessGameByGameName(String gameName){
Game foundGameName = new Game();
for(Game tempGames: games){
if(tempGames.getGameName().equals(gameName)){
foundGameName = tempGames;
}
}
return foundGameName;
}
public void saveToFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(games);
oos.flush();
oos.close();
}catch (IOException ioe){
System.err.println("Cannot write to file!");
}
}
public void readFromFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
games = (Vector<Game>) ois.readObject();
ois.close();
} catch (FileNotFoundException fnfe){
System.err.println("Cannot find file!");
}catch (IOException ioe){
System.err.println("Cannot read from file!");
}catch(ClassNotFoundException cnfe){
System.err.println("Client class cannot be found!");
}
}
}
Main class: GameCenter
public class GameCenter extends JFrame {
public static void main(String... args) {
SwingUtilities.invokeLater(() -> new GameCenter().setVisible(true));
}
public GameCenter() {
super("Game Center");
init();
}
private void init() {
setLayout(new BorderLayout(5, 5));
Model model = new Model();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Add", new AddTabPanel(model));
tabbedPane.add("View", new ViewTabPanel(model));
add(tabbedPane, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 500);
setMinimumSize(new Dimension(400, 500));
setResizable(false);
}
}
Game entity:
final class Game {
private static final Pattern RECORD = Pattern.compile("(?<key>.+)\\|(?<name>.+)\\|(?<type>.+)");
private final String name;
private final String key;
private final String type;
public static Game createFromRecord(String str) {
Matcher matcher = RECORD.matcher(str);
return matcher.matches() ? new Game(matcher.group("name"), matcher.group("key"), matcher.group("type")) : null;
}
public Game(String name, String key, String type) {
this.name = name;
this.key = key;
this.type = type;
}
public String getName() {
return name;
}
public String getKey() {
return key;
}
public String getType() {
return type;
}
public String serialize() {
return String.format("%s|%s|%s", key, name, type);
}
}
Table model:
final class Model extends AbstractTableModel {
private static final long serialVersionUID = 1858846855164475327L;
private final Map<String, Game> keyGame = new TreeMap<>();
private final List<Game> data = new ArrayList<>();
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void add(String name, String key, String type) {
keyGame.put(key, new Game(name, key, type));
fireTableDataChanged();
}
public void remove(int rowIndex) {
keyGame.remove(data.get(rowIndex).getKey());
fireTableDataChanged();
}
public void save() throws IOException {
if (file == null)
return;
try (FileWriter out = new FileWriter(file, false)) {
for (Game game : keyGame.values())
out.write(game.serialize() + '\n');
}
}
public void read() throws IOException {
if (file == null)
return;
keyGame.clear();
for (String record : Files.readAllLines(file.toPath())) {
Game game = Game.createFromRecord(record);
if (game != null)
keyGame.put(game.getKey(), game);
}
fireTableDataChanged();
}
private enum Column {
NAME("Game Name", Game::getName),
KEY("Game Key", Game::getKey),
TYPE("Game Type", Game::getType);
private final String title;
private final Function<Game, Object> get;
Column(String title, Function<Game, Object> get) {
this.title = title;
this.get = get;
}
public Object getValue(Game game) {
return get.apply(game);
}
}
// ========== AbstractTableModel ==========
#Override
public void fireTableDataChanged() {
data.clear();
data.addAll(keyGame.values());
super.fireTableDataChanged();
}
// ========== TableModel ==========
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return Column.values().length;
}
#Override
public String getColumnName(int columnIndex) {
return Column.values()[columnIndex].title;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return Column.values()[columnIndex].getValue(data.get(rowIndex));
}
}
AddGame tab panel:
final class AddTabPanel extends JPanel implements ActionListener, DocumentListener {
private final Model model;
private final JTextField nameField = new JTextField();
private final JTextField keyField = new JTextField();
private final JLabel nameLabel = new JLabel("Game Name");
private final JLabel keyLabel = new JLabel("Game Key");
private final JLabel typeLabel = new JLabel("Game Type");
private final JComboBox<String> typeCombo = createGameTypeCombo();
private final JButton openButton = new JButton("Open");
private final JButton saveButton = new JButton("Save");
private final JButton clearButton = new JButton("Clear");
public AddTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = createConstraints();
add(createTitlePanel(), gbc);
add(createMainPanel(), gbc);
add(createButtonPanel(), gbc);
gbc.weighty = 1;
add(Box.createVerticalGlue(), gbc);
onNameFieldChanged();
onKeyFieldChanged();
onTypeComboChanged();
}
private static JPanel createTitlePanel() {
JLabel label = new JLabel("Add a game below");
label.setFont(new Font("Verdana", Font.BOLD, 20));
JPanel panel = new JPanel();
panel.add(label);
return panel;
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));
panel.add(nameLabel);
panel.add(nameField);
panel.add(keyLabel);
panel.add(keyField);
panel.add(typeLabel);
panel.add(typeCombo);
return panel;
}
private static GridBagConstraints createConstraints() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
return gbc;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
panel.add(clearButton);
panel.add(saveButton);
panel.add(openButton);
return panel;
}
private static JComboBox<String> createGameTypeCombo() {
JComboBox<String> combo = new JComboBox<>();
combo.setModel(new DefaultComboBoxModel<>(new String[] { "<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay" }));
return combo;
}
private void addListeners() {
clearButton.addActionListener(this);
saveButton.addActionListener(this);
openButton.addActionListener(this);
nameField.getDocument().addDocumentListener(this);
keyField.getDocument().addDocumentListener(this);
typeCombo.addActionListener(this);
}
private void validateFields() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
int type = typeCombo.getSelectedIndex();
saveButton.setEnabled(!name.isEmpty() && !key.isEmpty() && type != 0);
}
private void onNameFieldChanged() {
nameLabel.setForeground(nameField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onKeyFieldChanged() {
keyLabel.setForeground(keyField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onTypeComboChanged() {
typeLabel.setForeground(typeCombo.getSelectedIndex() == 0 ? Color.RED : Color.BLACK);
validateFields();
}
private void onCleanButton() {
nameField.setText(null);
keyField.setText(null);
typeCombo.setSelectedIndex(0);
validateFields();
}
private void onSaveButton() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
String type = (String)typeCombo.getSelectedItem();
model.add(name, key, type);
if (model.getFile() == null) {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showSaveDialog(this);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
}
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
private void onOpenButton() {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showOpenDialog(null);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
try {
model.read();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot read file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == typeCombo)
onTypeComboChanged();
else if (e.getSource() == clearButton)
onCleanButton();
else if (e.getSource() == saveButton)
onSaveButton();
else if (e.getSource() == openButton)
onOpenButton();
}
// ========== DocumentListener ==========
#Override
public void insertUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void removeUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void changedUpdate(DocumentEvent e) {
}
}
ViewGame tab panel:
final class ViewTabPanel extends JPanel implements ActionListener, PopupMenuListener {
private final Model model;
private final JTable table = new JTable();
private final JPopupMenu popupMenu = new JPopupMenu();
private final JMenuItem deleteItem = new JMenuItem("Delete");
public ViewTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridLayout(1, 1));
add(new JScrollPane(table));
popupMenu.add(deleteItem);
table.setComponentPopupMenu(popupMenu);
table.setAutoCreateRowSorter(true);
table.setModel(model);
table.updateUI();
}
private void addListeners() {
popupMenu.addPopupMenuListener(this);
deleteItem.addActionListener(this);
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == deleteItem) {
model.remove(table.getSelectedRow());
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
}
// ========== PopupMenuListener ==========
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
if (event.getSource() == popupMenu) {
SwingUtilities.invokeLater(() -> {
int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table));
if (rowAtPoint > -1)
table.setRowSelectionInterval(rowAtPoint, rowAtPoint);
});
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent event) {
}
}
I have a Swing Form (Java). In this form I have field, for example Name1. I initialize it so:
private JTextField Name1;
In this code i'm adding JTextField Name1 into my Form:
tabbedPane.addTab("T6", null, panel, "T6");
panel.setLayout(null);
Name1.setBounds(73, 11, 674, 20);
panel.add(Name1);
Additionaly I have Button1 on my form. The event in this button is changing the value of Name1. Its work normaly.
Moreover I have a Button 2 that hiding the Tab with Name1:
tabbedPane.remove(1);
tabbedPane.repaint();
tabbedPane.revalidate();
frame.repaint();
frame.revalidate();
(And, of course, I turn on my tabpane again after this)
After all that, by the pressing the Button 4 I want to change the vlue of Name1 to some text.
But it doesn't work!!!!!! SetTex doesnt work. The field is empty.
So, if I change the Name1 declaration from
private JTextField Name1;
to
static JTextField Name1;
Yes, it works. BUT! Then I can't change the value of Name1 by using
Name1.Settext("Example");
What i have to do to make Name1 available after Button 4 pressed and changable ????
The all code is:
public class GUI {
public JTextField Name_textField;
public static void main(String[] args) {
DB_Initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setResizable(false);
FirstConnect FC = window.new FirstConnect();
ConnectStatus = true;
FC.FirstEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
CurrentEnty_textField = new JTextField();
Name_textField = new JTextField();
EntriesCountlbl = new JLabel("New label");
initialize();
EntriesCountlbl.setText(Integer.toString(EC1));
if (LoginStatus == true) {
System.out.println("LoginStatus == true");
AdminPartOn();
btnNewButton.setEnabled(false);
} else {
btnNewButton_3.setEnabled(false);
tabbedPane.setEnabledAt(1, false);
// UnableForm();
AdminPartOff();
}
}
public static void DB_Initialize() {
conn3 = con3.DoConnect();
int ID;
ArrayList<String> list = new ArrayList<String>();
String l;
String p;
list = con3.LoginFileRead();
if (list.size() == 2) {
l = list.get(0);
p = list.get(1);
System.out.println("Логин из файла = " + l);
System.out.println("Пароль из файла = " + p);
ID = con3.CRMUserRequest(conn3, l, p);
AdminPanelData = con3.CRMUserFullData(conn3, l, p);
if (ID != 0) {
System.out.println("ID Юзера = " + ID);
LoginStatus = true;
}
}
EC1 = con3.CRMQuery_EntriesCount(conn3); // запрашиваем кол-во записей
StatusTableEntriesCount = con3.CRMQueryStatus_EntriesCount(conn3);
StatusTableFromCount = con3.CRMQueryFRom_EntriesCount(conn3);
System.out.println("Entries count(Из модуля GYU): " + EC1);
if (EC1 > 0) {
CurrentEntry = 1;
System.out.println("Все ОК, текущая запись - " + CurrentEntry);
} else {
System.out.println("Выскакивает обработчик ошибок");
}
con3.Ini();
con3.CRMQuery2(conn3, EC1 + 1);
StatusColumn = con3.CRMQueryStatus(conn3, StatusTableEntriesCount);
FromColumn = con3.CRMQueryFrom(conn3, StatusTableFromCount);
}
public class FirstConnect {
public void FirstEntry() {
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
if (LoginStatus != false) {
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
Name_textField.setText("-");
}
}
}
private void initialize() {
frame = new JFrame();
panel = new JPanel();
frame.setBounds(100, 100, 816, 649);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 250, 780, 361);
frame.getContentPane().add(tabbedPane);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("\u0412\u0445\u043E\u0434", null, panel_1, null);
btnNewButton = new JButton("\u0412\u0445\u043E\u0434");
btnNewButton.setBounds(263, 285, 226, 37);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ID;
ID = con3.CRMUserRequest(conn3, LoginField.getText(), PasswordField.getText());
if (ID == 0) {
} else {
MainTab();
FirstEntry3();
}
}
});
panel_1.setLayout(null);
panel_1.add(btnNewButton);
tabbedPane.addTab("\u041A\u043B\u0438\u0435\u043D\u0442", null, panel,
"\u041A\u043E\u043D\u0442\u0430\u043A\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u0430");
panel.setLayout(null);
// Name_textField = new JTextField();
Name_textField.setBounds(73, 11, 674, 20);
panel.add(Name_textField);
Name_textField.setHorizontalAlignment(SwingConstants.CENTER);
Name_textField.setColumns(10);
NextEntryButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (NextEntryButton.isEnabled() != false) {
if (CurrentEntry < EC1) {
CurrentEntry = CurrentEntry + 1;
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
}
}
}
});
}
public void MainTab() {
tabbedPane.addTab("1", null, panel,
"1");
tabbedPane.setEnabledAt(1, true);
panel.setLayout(null);
}
public void FirstEntry3() {
Name_textField.setText(F.GetName(CurrentEntry - 1));
}
}
I am having issues with getting a correct value from my random method I am using. Everything else in my code works, but when I hit the random message button, I get an output on null null null null null instead of a random value from each array. My code is below. Any help to solve this would be greatly appreciated.
package shoutbox;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
public class ShoutBox {
String subj, obj, verB, adJ, adV, cannedM, randomM, tempSubj, tempObj, tempAdj, tempVerb, tempAdverb;
private final String[] stringItems = {
"I was sent here by the king to slay you!",
"I will leave you to your slumber.",
"I heard you have a piece of treasure I am interested in.",
"I heard you know a way to save princess Layla from illness.",
"Might I say you look lovely in the moonight.",
"I love dragons!",
"I will slay you and take your treasure!",
"Are you a luck dragon?",
"I think I will turn around and go home now.",
"Go ahead and try to roast me with your fire! I am a wizard, I will prevail!"
};
private final String[] subject = {
"I", "You", "Everyone", "They", "The King", "The Queen", "My Brother",
"We", "The gold", "The book"
};
private final String[] object = {
"sword", "treasure", "dragon", "cave", "head", "friends", "fire",
"blood", "jewels", "magic"
};
private final String[] verb = {
"yells", "hits", "torches", "sings", "laughs", "loves", "dances",
"scouts", "hates", "wants"
};
private final String[] adjective = {
"beautiful", "outragious", "pretty", "scary", "lazy", "heavy", "enormous",
"hot", "scaly", "scary"
};
private final String[] adverb = {
"quickly", "slowly", "softly", "skillfully", "wickedly", "underground", "tomorrow",
"uneasily", "quickly", "abruptly"
};
public void setSubject(String tempSubj) {
tempSubj = subj;
}
public void setObject(String tempObj) {
tempObj = obj;
}
public void setVerb(String tempVerb) {
tempVerb = verB;
}
public void setAdjective(String tempAdj) {
tempAdj = adJ;
}
public void setAdverb(String tempAdverb) {
tempAdverb = adV;
}
public String getSubject() {
Random genSub = new Random();
int randomSub = genSub.nextInt(subject.length);
subj = subject[randomSub];
return subj;
}
public String getObject() {
Random genOb = new Random();
int randomOb = genOb.nextInt(object.length);
obj = object[randomOb];
return obj;
}
public String getVerb() {
Random genVerb = new Random();
int randomVerb = genVerb.nextInt(verb.length);
verB = subject[randomVerb];
return verB;
}
public String getAdjective() {
Random genAd = new Random();
int randomAd = genAd.nextInt(adjective.length);
adJ = adjective[randomAd];
return adJ;
}
public String getAdverb() {
Random genAdverb = new Random();
int randomAdverb = genAdverb.nextInt(adverb.length);
adV = subject[randomAdverb];
return adV;
}
public ShoutBox() {
JFrame frame = new JFrame(); //setting up Jframe components
// Setting width, height, and title of window
frame.setTitle("Shout Box");
frame.setSize(450, 400); // Size of frame window
frame.setLocation(360, 200); // Start location of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false); // So you cannot resize frame
JButton submitButton = new JButton("Submit");
JButton randomButton = new JButton("Random Message");
JLabel label = new JLabel("Pick a message and click submit or click random message");
JList JlistMap;
JTextArea textArearesult = new JTextArea(2, 21);
textArearesult.setEditable(false);
textArearesult.setLineWrap(true);
textArearesult.setWrapStyleWord(true);
JPanel panel = new JPanel();
JLabel label1 = new JLabel("");
label1.setForeground(Color.blue);
JLabel label2 = new JLabel(" Your Message you have chosen is: ");
label2.setForeground(Color.red);
JlistMap = new JList(stringItems);
JlistMap.setVisibleRowCount(10);
JlistMap.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//add(new JScrollPane(JlistMap)); //Not working as of now
panel.setBackground(Color.PINK); // Pink background color
frame.add(panel);
panel.add(label);
panel.add(JlistMap);
panel.add(submitButton);
panel.add(randomButton);
panel.add(label2);
panel.add(textArearesult);
// Action Listener for the submit button to get the message that will display in the JTextArea
submitButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutCannedMessage()); //using ShoutOutCannedMessage method to return cannedM
});
randomButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutRandomMessage()); //using ShoutOutCannedMessage method to return cannedM
});
// JList will get the selected Item and set the item to a string value t that will be set to cannedM
JlistMap.addListSelectionListener((ListSelectionEvent e) -> {
JList list = (JList) e.getSource();
String t = list.getSelectedValue().toString();
cannedM = t;
});
frame.setVisible(true); //set to be visible on panel
}
public String ShoutOutCannedMessage() {
return cannedM;
}
public String ShoutOutRandomMessage() {
randomM = tempSubj + " " + tempObj + " " + tempVerb + " " + tempAdj + " " + tempAdverb + ".";
return randomM;
}
}
package shoutbox;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
public class ShoutBox {
String cannedM, randomM, subJ, tempSubj, tempObj, tempAdj, tempVerb, tempAdverb;
private final String[] stringItems = {
"I was sent here by the king to slay you!",
"I will leave you to your slumber.",
"I heard you have a piece of treasure I am interested in.",
"I heard you know a way to save princess Layla from illness.",
"Might I say you look lovely in the moonight.",
"I love dragons!",
"I will slay you and take your treasure!",
"Are you a luck dragon?",
"I think I will turn around and go home now.",
"Go ahead and try to roast me with your fire! I am a wizard, I will prevail!"
};
private final String[] subject = {
"I", "You", "Everyone", "They", "The King", "The Queen", "My Brother",
"We", "The gold", "The book"
};
private final String[] object = {
"sword", "treasure", "dragon", "cave", "head", "friends", "fire",
"blood", "jewels", "magic"
};
private final String[] verb = {
"yells", "hits", "torches", "sings", "laughs", "loves", "dances",
"scouts", "hates", "wants"
};
private final String[] adjective = {
"beautiful", "outragious", "pretty", "scary", "lazy", "heavy", "enormous",
"hot", "scaly", "scary"
};
private final String[] adverb = {
"quickly", "slowly", "softly", "skillfully", "wickedly", "underground", "tomorrow",
"uneasily", "quickly", "abruptly"
};
public void setSubject() {
Random genSub = new Random();
int randomSub = genSub.nextInt(subject.length);
tempSubj = subject[randomSub];
}
public void setObject() {
Random genOb = new Random();
int randomOb = genOb.nextInt(object.length);
tempObj = object[randomOb];
}
public void setVerb() {
Random genVerb = new Random();
int randomVerb = genVerb.nextInt(verb.length);
tempVerb = verb[randomVerb];
}
public void setAdjective() {
Random genAd = new Random();
int randomAd = genAd.nextInt(adjective.length);
tempAdj = adjective[randomAd];
}
public void setAdverb() {
Random genAdverb = new Random();
int randomAdverb = genAdverb.nextInt(adverb.length);
tempAdverb = subject[randomAdverb];
}
public String getSubject() {
return tempSubj;
}
public String getObject() {
return tempObj;
}
public String getVerb() {
return tempVerb;
}
public String getAdjective() {
return tempAdj;
}
public String getAdverb() {
return tempAdverb;
}
public ShoutBox() {
JFrame frame = new JFrame(); //setting up Jframe components
// Setting width, height, and title of window
frame.setTitle("Shout Box");
frame.setSize(450, 400); // Size of frame window
frame.setLocation(360, 200); // Start location of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false); // So you cannot resize frame
JButton submitButton = new JButton("Submit");
JButton randomButton = new JButton("Random Message");
JLabel label = new JLabel("Pick a message and click submit or click random message");
JList JlistMap;
JTextArea textArearesult = new JTextArea(1, 30);
textArearesult.setEditable(false);
textArearesult.setLineWrap(true);
textArearesult.setWrapStyleWord(true);
JPanel panel = new JPanel();
JLabel label1 = new JLabel("");
label1.setForeground(Color.blue);
JLabel label2 = new JLabel(" Your Message you have chosen is: ");
label2.setForeground(Color.red);
JlistMap = new JList(stringItems);
JlistMap.setVisibleRowCount(10);
JlistMap.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//add(new JScrollPane(JlistMap)); //Not working as of now
panel.setBackground(Color.PINK); // Pink background color
frame.add(panel);
panel.add(label);
panel.add(JlistMap);
panel.add(submitButton);
panel.add(randomButton);
panel.add(label2);
panel.add(textArearesult);
// Action Listener for the submit button to get the message that will display in the JTextArea
submitButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutCannedMessage()); //using ShoutOutCannedMessage method to return cannedM
});
randomButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutRandomMessage()); //using ShoutOutCannedMessage method to return cannedM
});
// JList will get the selected Item and set the item to a string value t that will be set to cannedM
JlistMap.addListSelectionListener((ListSelectionEvent e) -> {
JList list = (JList) e.getSource();
String t = list.getSelectedValue().toString();
cannedM = t;
});
frame.setVisible(true); //set to be visible on panel
}
public String ShoutOutCannedMessage() {
return cannedM;
}
public String ShoutOutRandomMessage() {
randomM = getSubject() + " " + getObject() + " " + getVerb() + " " + getAdjective() + " " + getAdverb() + ".";
return randomM;
}
}
You have to set the values of your attributes tempSubj, tempObj, tempVerb, tempAdjand tempAdverb.
Notice that you've declare these attributes but you haven't affect them with any value. Therefore, they assume the value null.
In order to fix this, you have set them with some value explicitly or invoke their setters, which you've already created. Also you've to fix your setters because they're not properly setting your attributes:
public void setSubject(String subj) {
tempSubj = subj;
}
public void setObject(String obj) {
tempObj = obj;
}
public void setVerb(String verb) {
tempVerb = verb;
}
public void setAdjective(String adj) {
tempAdj = adj;
}
public void setAdverb(String adv) {
tempAdverb = adv;
}
EDIT
Other approach, is to use your getters, where you have the random code logic:
public String ShoutOutRandomMessage() {
randomM = getSubject() + " " + getObject() + " " + getVerb() + " " + getAdjective() + " " + getAdverb() + ".";
return randomM;
}
I am trying to plot values from a csv file into a graph, using Java, JFreeChart and using the MVC concept. At the minute, I have created a button, and when this button is clicked it adds a new plot to the graph, however instead of doing this, I would like it to read in the values from the csv file, which is read in by a csv file adapter and stored in the model. I wondering if anyone could help me with this. I would appreciate any help that could be given. Thank you
//Main Class
public class Main
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Model model = new Model(0);
Controller controller = new Controller(model);
View view = new View(controller, "-");
view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
view.setVisible(true);
}
});
}
}
//csv file adapter
public List<Double> readFile(final String filename)
{
List<Double> result = new ArrayList<Double>();
String csvFile = filename;
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null){
String[] test = line.split(splitBy);
System.out.println("csvFile [Value= " + test[0] + ", Value=" + test[1] + ", Value=" + test[2] + "]");
try
{
for (String val : test)
{
final Double valueToAdd = Double.parseDouble(val);
result.add(valueToAdd);
}
}
catch (NumberFormatException nfe)
{
System.out.println("Failed to parse line: " + line);
}
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
if (br != null){
try{
br.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
return result;
}
}
//model
public class Model {
private int x;
public Model(){
x = 0;
}
public Model(int x){
this.x = x;
}
public void incX(){
x++;
}
public int getX(){
return x;
}
public void addDataset(final List<Double> data)
{
System.out.println("Added data to model");
for (Double d : data)
{
System.out.println("Value: " + d.toString());
}
}
}
//view
public class View extends JFrame
{
private Controller controller;
private JFrame frame;
private JLabel label;
private JButton button;
private ChartDisplayWidget myChart;
public View(Controller c, String text){
this.controller = c;
getContentPane().setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000,1000);
//label = new JLabel(text);
//getContentPane().add(label, BorderLayout.CENTER);
button = new JButton("Button");
getContentPane().add(button, BorderLayout.SOUTH);
button.addActionListener(new Action());
myChart = new ChartDisplayWidget();
getContentPane().add(myChart, BorderLayout.CENTER);
}
public class Action implements ActionListener {
public void actionPerformed (ActionEvent e){
System.out.println("I was clicked");
controller.control();
myChart.addTimeSeriesPerformancePlot("NewPlot", new Double[] {60.0, 40.0, 500.0, 10.0});
/*this is where I would like to plot the values from the csv file*/
}
}
public JButton getButton(){
return button;
}
public void setText(String text){
label.setText(text);
}
}
//controller
public class Controller {
public Model model;
public ActionListener actionListener;
public Controller(Model model){
this.model = model;
}
public void control(){
CSVFileAdapter c = new CSVFileAdapter();
model.addDataset(c.readFile("C:/dstat.csv"));
}
}
//Chart Display Widget
public class ChartDisplayWidget extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
private TimeSeriesCollection chartData;
private JFreeChart chart;
public ChartDisplayWidget()
{
init();
}
public void init()
{
final XYDataset dataset = getSampleData();
chart = ChartFactory.createTimeSeriesChart(
"Our test chart",
"Time",
"Some Value",
dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
add(chartPanel);
}
public void addTimeSeriesPerformancePlot(final String plotName, final Double[] values)
{
final TimeSeries newSeries = new TimeSeries(plotName);
int arrLen = values.length;
int monthIndex = 2;
int yearIndex = 2001;
for (int index = 0; index < arrLen; index++)
{
newSeries.add(new Month(monthIndex++, yearIndex++), values[index]);
}
chartData.addSeries(newSeries);
}
private XYDataset getSampleData()
{
TimeSeries s1 = new TimeSeries("Max CPU");
s1.add(new Month(2, 2001), 181.5);
s1.add(new Month(3, 2001), 20.5);
s1.add(new Month(4, 2001), 1.1);
s1.add(new Month(5, 2001), 81.5);
s1.add(new Month(6, 2001), 1181.5);
s1.add(new Month(7, 2001), 1081.5);
TimeSeries s2 = new TimeSeries("Disk I/O");
s2.add(new Month(2, 2001), 50.0);
s2.add(new Month(3, 2001), 55.0);
s2.add(new Month(4, 2001), 60.6);
s2.add(new Month(5, 2001), 70.8);
s2.add(new Month(6, 2001), 1000.1);
s2.add(new Month(7, 2001), 1081.5);
chartData = new TimeSeriesCollection();
chartData.addSeries(s1);
chartData.addSeries(s2);
return chartData;
}
}
Use the observer pattern: update the model, an unspecified implementation XYDataset, and the listening view will update itself in response. Examples are seen here and here. Because file latency is inherently unpredictable, read the file in the background thread of a SwingWorker, publish() intermediate results, and update the model in process(); a JFreeChart example is shown here.
I am trying to get and set the price from my order form to the order summary. Will you take a look at my code and see what I am doing wrong?
My assignment requires me to use an arrayList and a JOptionPane to list out the orders and totals.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Subway extends JFrame {
private String[] breadNames = {"9-grain Wheat", "Italian", "Honey Oat", "Herbs and Cheese", "Flatbread"};
private String[] subTypes = {"Oven Roasted Chicken - $3.50", "Meatball Marinara - $4.50", "Cold Cut Combo - $4.00",
"BLT - $3.75", "Blackforest Ham - $4.00", "Veggie Delight - $2.50"};
private String[] cheesetypes = {"Cheddar", "American", "Provolone", "Pepperjack"};
private String[] size = {"6 inch", "Footlong"};
private String[] toasted = {"Yes", "No"};
private JTextField jtfname = new JTextField(10);
private JComboBox<String> jcbBread = new JComboBox<String>(breadNames);
private JComboBox<String> jcbtype = new JComboBox<String>(subTypes);
private JComboBox<String> jcbcheese = new JComboBox<String>(cheesetypes);
private JButton jbtExit = new JButton("EXIT");
private JButton jbtAnother = new JButton("Next Order");
private JButton jbtSubmit = new JButton("SUBMIT");
private JComboBox<String> jcbSize = new JComboBox<String>(size);
private JComboBox<String> jcbToasted = new JComboBox<String>(toasted);
private JCheckBox jcbLettuce = new JCheckBox("Lettuce");
private JCheckBox jcbSpinach = new JCheckBox("Spinach");
private JCheckBox jcbOnion = new JCheckBox("Onion");
private JCheckBox jcbPickles = new JCheckBox("Pickles");
private JCheckBox jcbTomatoes = new JCheckBox("Tomatoes");
private JCheckBox jcbPeppers = new JCheckBox("Peppers");
private JCheckBox jcbMayo = new JCheckBox("Mayo");
private JCheckBox jcbMustard = new JCheckBox("Mustard");
private JCheckBox jcbDressing = new JCheckBox("Italian Dressing");
public Subway() {
//name
JPanel p1 = new JPanel(new GridLayout(24, 1));
p1.add(new JLabel("Enter Name"));
p1.add(jtfname);
//size
p1.add(new JLabel("Select a size"));
p1.add(jcbSize);
//bread
p1.add(new JLabel("Select a Bread"));
p1.add(jcbBread);
//type
p1.add(new JLabel("What type of sub would you like?"));
p1.add(jcbtype);
//cheese
p1.add(new JLabel("Select a cheese"));
p1.add(jcbcheese);
//toasted
p1.add(new JLabel("Would you like it toasted?"));
p1.add(jcbToasted);
//toppings
p1.add(new JLabel("Select your toppings"));
p1.add(jcbLettuce);
p1.add(jcbSpinach);
p1.add(jcbPickles);
p1.add(jcbOnion);
p1.add(jcbTomatoes);
p1.add(jcbPeppers);
p1.add(jcbMayo);
p1.add(jcbMustard);
p1.add(jcbDressing);
// BUTTON PANEL
JPanel p5 = new JPanel();
p5.setLayout(new BoxLayout(p5, BoxLayout.LINE_AXIS));
p5.add(Box.createHorizontalGlue());// KEEPS THEM HORIZONTAL
p5.add(jbtExit);
p5.add(jbtAnother);
p5.add(jbtSubmit);
// ADDING PANELS AND WHERE THEY GO
add(p1, BorderLayout.NORTH);// TOP
add(p5, BorderLayout.SOUTH);// BOTTOM
// SETTING INVISIBLE BORDERS AROUND PANELS TO SPACE THEM OUT
p1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
p5.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// EXIT BUTTON LISTENER
jbtExit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
// Another order BUTTON LISTENER
jbtAnother.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
makeASandwich();
}
});
// SUBMIT BUTTON LISTENER
jbtSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
makeASandwich();
for (Sandwich s : Sandwich.order) {
String Order = " ";
Order = jtfname.getText() + "\n"
+ "\nSize: " + s.getSize()
+ "\nType of Sub: " + s.getName()
+ "\nBread: " + s.getBread()
+ "\nCheese: " + s.getCheese()
+ "\nToasted? " + s.getToasted() + "\nToppings: \n";
if (jcbLettuce.isSelected()) {
Order += jcbLettuce.getText();
}
if (jcbSpinach.isSelected()) {
Order += jcbSpinach.getText();
}
if (jcbPickles.isSelected()) {
Order += jcbPickles.getText();
}
if (jcbOnion.isSelected()) {
Order += jcbOnion.getText();
}
if (jcbTomatoes.isSelected()) {
Order += jcbTomatoes.getText();
}
if (jcbPeppers.isSelected()) {
Order += jcbPeppers.getText();
}
if (jcbMayo.isSelected()) {
Order += jcbMayo.getText();
}
if (jcbMustard.isSelected()) {
Order += jcbMustard.getText();
}
if (jcbDressing.isSelected()) {
Order += jcbDressing.getText();
}
Order +=
"\n Price: " + s.getPrice()
+ "\n\n---Next Order---";
JOptionPane.showMessageDialog(null, Order);
}
}
});
}
private void makeASandwich() {
double BLT_Price = 3.00;
Sandwich sandwich = new Sandwich(jcbtype.getItemAt(jcbtype.getSelectedIndex()));
sandwich.setBread(jcbBread.getItemAt(jcbBread.getSelectedIndex()));
sandwich.setCheese(jcbcheese.getItemAt(jcbcheese.getSelectedIndex()));
sandwich.setToasted(jcbToasted.getItemAt(jcbToasted.getSelectedIndex()));
sandwich.setSize(jcbSize.getItemAt(jcbSize.getSelectedIndex()));
//sandwich.setPrice(jcbtype.getItemAt(jcbtype.getSelectedIndex()));
if (jcbtype.getSelectedIndex() == 0) {
sandwich = new Sandwich(jcbtype.getItemAt(jcbtype.getSelectedIndex()), BLT_Price);
}
Sandwich.order.add(sandwich);
}
public static void main(String[] args) {
Subway frame = new Subway();
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("SUBWAY");
frame.setVisible(true);
frame.setSize(600, 750);
}// ENDOFMAIN
}// ENDOFCLASS
class HoldOrder {
public static List<Sandwich> order = new ArrayList<Sandwich>();
}
class Sandwich {
String bread = "";
String sandwichName = "";
String cheese = "";
String size = "";
String toasted = "";
String lettuce = "";
private String cost = " ";
public static List<Sandwich> order = new ArrayList<Sandwich>();
public Sandwich(String typeOfSandwich, double SubPrice) {
sandwichName = typeOfSandwich;
cost += SubPrice;
}
public String getPrice() {
return cost;
}
public String getName() {
return sandwichName;
}
public void setBread(String s) {
bread = s;
}
public String getBread() {
return bread;
}
public void setCheese(String s) {
cheese = s;
}
public String getCheese() {
return cheese;
}
public void setSize(String s) {
size = s;
}
public String getSize() {
return size;
}
public void setToasted(String s) {
toasted = s;
}
public String getToasted() {
return toasted;
}
//public void setPrice(double s) {
//total = 0;
//}
//public double getPrice() {
//return total;
//}
}
This is a difficult question to answer as it will depend on portions of code you've not shared, but the basic premise will be the same...
IF the combo box of prices contains String, you will need to parse the value as a double...
Object value = jcbtype.getSelectedItem();
double price = Double.parseDouble(value);
sandwich.setPrice(price);
Beware, this will throw an NumberFormatException if the value is not parsable.
IF the combo box contains double values (which it should and then be formatted with a CellRenderer), then you might need to cast...
Object value = jcbtype.getSelectedItem();
double price = (Double)value;
sandwich.setPrice(price);
(I say might, because if you are using Java 7, you can use generics to return the base type of the JComboBox using something like double price = jcbtype.getItemAt(jcbtype.getSelectedIndex()) for example)
in the source code window of the desired class.
Right click -> Source -> Generate setters and getters ... Eclipse will generate the setter and getter methods for you.