I've been trying to get a running total price of all the elements within my Jlist as they are being added however just can't seem to get it to work. I've tried to provide the classes necessary to be able to reproduce my problem for greater clarity on what I'm trying to do. Thank you.
-Main GUI
public class PaymentSystemGUI extends javax.swing.JFrame {
private JLabel priceLabel;
private JLabel totalLabel;
private JTextField totalField;
private JButton scanBtn;
private JList checkoutList;
private JScrollPane jScrollCheckout;
private JLabel jLabel1;
private JButton removeBtn;
private JButton addBtn;
private JTextField priceField;
private JTextField barcodeField;
private JLabel barcodeLabel;
private JTextField itemNameField;
private JLabel jItemName;
private JLabel editorLabel;
private JScrollPane checkScrollPane;
private JScrollPane jScrollPane1;
private JMenuItem exitButton;
private JMenu StartButton;
private JMenuBar MainMenBar;
private DefaultListModel Inventory = new DefaultListModel();
private DefaultListModel checkoutBasket = new DefaultListModel();
private JList productList;
private InventoryList stockInst;
private JFileChooser chooser;
private File saveFile;
private boolean changesMade;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
PaymentSystemGUI inst = new PaymentSystemGUI();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public PaymentSystemGUI() {
super();
initGUI();
stockInst = new InventoryList();
productList.setModel(stockInst);
checkoutList.setModel(checkoutBasket);
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(new java.awt.Color(245, 245, 245));
this.setEnabled(true);
{
MainMenBar = new JMenuBar();
setJMenuBar(MainMenBar);
{
StartButton = new JMenu();
MainMenBar.add(StartButton);
StartButton.setText("File");
{
exitButton = new JMenuItem();
StartButton.add(exitButton);
exitButton.setText("Exit");
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
}
);
}
}
{
jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(31, 84, 275, 323);
jScrollPane1.setAlignmentY(0.4f);
{
ListModel stockListModel = new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
productList = new JList();
jScrollPane1.setViewportView(productList);
BorderLayout stockListLayout = new BorderLayout();
productList.setLayout(stockListLayout);
productList.setBounds(25, 92, 269, 330);
productList.setAlignmentX(0.4f);
productList.setModel(stockListModel);
}
}
{
editorLabel = new JLabel();
getContentPane().add(editorLabel);
editorLabel.setText("INVENTORY");
editorLabel.setBounds(121, 56, 88, 16);
}
{
jItemName = new JLabel();
getContentPane().add(jItemName);
jItemName.setText("Item Name");
jItemName.setBounds(31, 432, 61, 16);
}
{
itemNameField = new JTextField();
getContentPane().add(itemNameField);
itemNameField.setBounds(127, 426, 130, 28);
}
{
barcodeLabel = new JLabel();
getContentPane().add(barcodeLabel);
barcodeLabel.setText("Barcode Number");
barcodeLabel.setBounds(27, 476, 94, 16);
}
{
barcodeField = new JTextField();
getContentPane().add(barcodeField);
barcodeField.setBounds(127, 470, 130, 28);
}
{
priceLabel = new JLabel();
getContentPane().add(priceLabel);
priceLabel.setText("Price of Item");
priceLabel.setBounds(33, 521, 68, 16);
}
{
priceField = new JTextField();
getContentPane().add(priceField);
priceField.setBounds(127, 515, 130, 28);
}
{
addBtn = new JButton();
getContentPane().add(addBtn);
addBtn.setText("Add");
addBtn.setBounds(53, 560, 83, 28);
}
addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evta) {
addButtonPressed();
}
});
{
removeBtn = new JButton();
getContentPane().add(removeBtn);
removeBtn.setText("Remove");
removeBtn.setBounds(148, 560, 83, 28);
removeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
removeButtonPressed();
}
});
}
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("CHECKOUT");
jLabel1.setBounds(480, 79, 68, 16);
}
{
jScrollCheckout = new JScrollPane();
getContentPane().add(jScrollCheckout);
jScrollCheckout.setBounds(395, 107, 248, 323);
{
ListModel checkoutListModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
checkoutList = new JList();
jScrollCheckout.setViewportView(checkoutList);
checkoutList.setModel(checkoutListModel);
}
}
{
scanBtn = new JButton();
getContentPane().add(scanBtn);
scanBtn.setText("Scan Item into Checkout");
scanBtn.setBounds(59, 613, 161, 28);
scanBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
checkoutBasket.addElement(productList.getSelectedValue());
double totalAddedValue = 0.00;
double oldCheckoutValue = 0.00;
//Iterate to get the price of the new items.
for (int i = 1; i < productList.getModel().getSize(); i++) {
InventItem item = (InventItem) productList.getModel().getElementAt(i);
totalAddedValue += Double.parseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
String checkoutField = totalField.getText();
//Check that cartTextField already contains a value.
if(checkoutField != null && !checkoutField.isEmpty())
{
oldCheckoutValue = Double.parseDouble(checkoutField);
}
totalField.setText(String.valueOf(oldCheckoutValue + totalAddedValue));
checkoutBasket.addElement(productList);
}
});
}
{
totalField = new JTextField();
getContentPane().add(totalField);
totalField.setBounds(503, 442, 115, 28);
totalField.setEditable(false);
}
{
totalLabel = new JLabel();
getContentPane().add(totalLabel);
totalLabel.setText("Total Cost of Items");
totalLabel.setBounds(367, 448, 124, 16);
}
pack();
this.setSize(818, 730);
}
} catch (Exception e) {
// add your error handling code here
e.printStackTrace();
}
}
private void loadMenuItemAction() {
try {
FileInputStream in = new FileInputStream("itemdata.dat");
ObjectInputStream oIn = new ObjectInputStream(in);
stockInst = (InventoryList)oIn.readObject();
productList.setModel(stockInst);
oIn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Failed to read file");
System.out.println("Error : " + e);
}
}
private void clearAllTextFields() {
barcodeField.setText("");
itemNameField.setText("");
priceField.setText("");
}
private void removeButtonPressed() {
int selectedIndex = productList.getSelectedIndex();
if (selectedIndex == -1) {
JOptionPane.showMessageDialog(this, "Select An Item to Remove");
} else {
InventItem toGo = (InventItem)stockInst.getElementAt(selectedIndex);
if (JOptionPane.showConfirmDialog(this, "Do you really want to remove the item from the cart ? : " + toGo,
"Delete Confirmation", JOptionPane.YES_NO_OPTION)
== JOptionPane.YES_OPTION) {
stockInst.removeItem(toGo.getID());
clearAllTextFields();
productList.clearSelection();
}
}
}
private void addButtonPressed() {
String newbarcode = barcodeField.getText();
String newitemName = itemNameField.getText();
String newprice = priceField.getText();
if (newbarcode.equals("") || newitemName.equals("") || newprice.equals("")) {
JOptionPane.showMessageDialog(this, "Please Enter Full Details");
} else {
stockInst.addInventItem(newbarcode, newitemName, newprice);
InventItem newBasket = stockInst.findItemByName(newbarcode);
productList.setSelectedValue(newBasket, true);
clearAllTextFields();
}
}
}
-InventoryList
import javax.swing.DefaultListModel;
public class InventoryList extends DefaultListModel {
public InventoryList(){
super();
}
public void addInventItem(String idNo, String itemName, String total){
super.addElement(new InventItem(idNo, itemName, total));
}
public InventItem findItemByName(String name){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public InventItem findItemByBarcode(String id){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getID().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public void removeItem(String id){
InventItem empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
InventoryItem
import java.io.Serializable;
public class InventItem implements Serializable {
private String idnum;
private String itemName;
private String cost;
public InventItem() {
}
public InventItem (String barno, String in, String price) {
idnum = barno;
itemName = in;
cost = price;
}
public String getID(){
return idnum;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return cost;
}
public String toString(){
return idnum + ": " + itemName + ", £ " + cost;
}
}
I'm a beginner and don't quite know how to change my code to add a single element from the list.
Read the List API and you will find methods like:
size()
get(...)
So you create a loop that loops from 0 to the number of elements. Inside the loop you get the element from the List and add it to the model of the checkoutBasket JList.
Here is the basics of an MCVE to get you started. All you need to do is add the code for the actionPerformed() method to copy the selected item(s):
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
JList<String> left;
JList<String> right;
JLabel total;
public SSCCE()
{
setLayout( new BorderLayout() );
// change this to store Integer objects
String[] data = { "one", "two", "three", "four", "five", "four", "six", "seven" };
left = new JList<String>(data);
add(new JScrollPane(left), BorderLayout.WEST);
right = new JList<String>( new DefaultListModel<String>() );
add(new JScrollPane(right), BorderLayout.EAST);
JButton button = new JButton( "Copy" );
add(button, BorderLayout.CENTER);
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
DefaultListModel<String> model = (DefaultListModel<String>)right.getModel();
List<String> selected = left.getSelectedValuesList();
for (String item: selected)
model.addElement( item );
// add code here to loop through right list and total the Integer items
total.setText("Selected total is ?");
}
});
total = new JLabel("Selected total is 0");
add(total, BorderLayout.SOUTH);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If you have a problem then delete your original code and post the MCVE showing what you have tried based on the information in this answer. Don't create a new posting.
Edit:
My original answer talked about copying the data from the DefaultListModel. However, your code is using the JList.getSelectedValuesList() method to get a List of selected items. Each of these items needs to be copied from the List to the ListModel of the JList. I updated my answer to reflect this part of your code. I even wrote the code to show you how to copy the items from the list.
So now your next step is to calculate the a total of the items in the "right" JLIst (ie, your checkout basked). In order to do this, you need to change the data in the "left" list to be "Integer" Objects. So now when you copy the Integer objects yo9u can then iterate through the JList and calculate a total value. If you have problems, then any code you post should be based on this MVCE and NOT your real program.
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) {
}
}
When I click the button called Enrolled Subjects, a table showing enrolled subjects is invoked. The data is loaded from a text file. But when I go to another page of the application and go back to the Enrolled Subjects or when I click the Enrolled Subjects Button again, a new table loads and adds to the previously loaded table. This makes the table grow longer every time I click Enrolled Subjects. I have added a removeAll() method which clears the content of the pane before loading the table again, but the previously loaded table, for some reason, does not go away.
Here's the code of the panel where the table is attached.
public class EnrolledSubjectsPanel extends JPanel
{
public EnrolledSubjectsPanel(String path)
{
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
LoadTable table = new LoadTable(path);
table.setBounds(0,60,1129,600);
add(table);
JLabel lblEnrolledSubjects = new JLabel("Enrolled Subjects");
lblEnrolledSubjects.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblEnrolledSubjects.setBounds(446, 0, 292, 43);
add(lblEnrolledSubjects);
setVisible(true);
}
}
The class that creates the table
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
The main class where the panel is attached to
public class LaunchPage extends JFrame
{ public LaunchPage(String path)
{
getContentPane().setBackground(Color.white);
getContentPane().setLayout(null);
StudentBasicInformationPanel studentBasicInfo = new StudentBasicInformationPanel(path);
getContentPane().add(studentBasicInfo);
JLabel universityTitleL = new JLabel("Evil Genuises University");
universityTitleL.setFont(new Font("Edwardian Script ITC", Font.ITALIC, 42));
universityTitleL.setBounds(514, 11, 343, 65);
getContentPane().add(universityTitleL);
JPanel panelToAttach = new JPanel();
panelToAttach.setBounds(173, 280, 1129, 404);
getContentPane().add(panelToAttach);
setSize(1366, 768);
JButton enrollmentButton = new JButton("Enrollment");
enrollmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrollmentPanel ep = new EnrollmentPanel();
ep.setBackground(Color.LIGHT_GRAY);
ep.setBounds(0, 0, 1129, 401);
panelToAttach.add(ep);
repaint();
}
});
enrollmentButton.setBounds(10, 280, 157, 58);
getContentPane().add(enrollmentButton);
JButton viewEnrolledSubjectsButton = new JButton("Enrolled Subjects");
viewEnrolledSubjectsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrolledSubjectsPanel es = new EnrolledSubjectsPanel(path);
es.setBackground(Color.LIGHT_GRAY);
es.setBounds(0, 0, 1129, 401);
panelToAttach.add(es);
repaint();
}
});
viewEnrolledSubjectsButton.setBounds(10, 349, 157, 58);
getContentPane().add(viewEnrolledSubjectsButton);
JButton viewGradesButton = new JButton("View Grades");
viewGradesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
GradesPanel gp = new GradesPanel();
gp.setBackground(Color.LIGHT_GRAY);
gp.setBounds(0, 0, 1129, 401);
panelToAttach.add(gp);
repaint();
}
});
viewGradesButton.setBounds(10, 418, 157, 58);
getContentPane().add(viewGradesButton);
JButton clearanceButton = new JButton("Clearance");
clearanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
ClearancePanel cp = new ClearancePanel();
cp.setBackground(Color.LIGHT_GRAY);
cp.setBounds(0, 0, 1129, 401);
panelToAttach.add(cp);
repaint();
}
});
clearanceButton.setBounds(10, 487, 157, 58);
getContentPane().add(clearanceButton);
JButton viewAccountButton = new JButton("View Account");
viewAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
AccountPanel ap = new AccountPanel();
ap.setBackground(Color.LIGHT_GRAY);
ap.setBounds(0, 0, 1129, 401);
panelToAttach.add(ap);
repaint();
}
});
viewAccountButton.setBounds(10, 556, 157, 58);
getContentPane().add(viewAccountButton);
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
closeButton.setBounds(10, 626, 157, 58);
getContentPane().add(closeButton);
setVisible(true);
}
}
Thanks in advance!
Try using below code in your LoadTable class before you adding the rows to the table. It will clear the rows in the table model.
dtm.setRowCount(0);
So your new LoadTable class should look like this:
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
dtm.setRowCount(0); //THIS WILL CLEAR THE ROWS IN YOUR STATIC TABLEMODEL
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
I am having trouble with one part of my code. I have been working for so long on this and I am exhausted and missing something easy. I need to have a text box to enter a new title for the JFrame, a button that says "Set New Name" and an "Exit Button.
Can someone look at this code and give me some info so I can go to bed.
Thank you
//Good One
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Pool {
public static void main(String[] args) {
new poolCalc();
}
}
class poolCalc extends JFrame {
private static final long serialVersionUID = 1L;
public static final double MILLIMETER = 1;
public static final double METER = 1000 * MILLIMETER;
public static final double INCH = 25.4 * MILLIMETER;
public static final double FOOT = 304.8 * MILLIMETER;
public static final double YARD = 914.4 * MILLIMETER;
private static final DecimalFormat df = new DecimalFormat("#,##0.###");
private JTabbedPane tabs;
private JPanel generalPanel;
private JPanel optionsPanel;
private JPanel customerPanel;
private JPanel contractorPanel;
private JPanel poolPanel;
private JPanel hotTubPanel;
private JPanel tempCalPanel;
private JPanel lengthCalPanel;
public poolCalc() {
super("The Pool Calculator");
setSize(340, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
initializeComponents();
setLocationRelativeTo(null);
setVisible(true);
}
private void initializeComponents() {
Container pane = getContentPane();
tabs = new JTabbedPane();
generalTab();
optionsTab();
customerTab();
contractorTab();
poolsTab();
hotTubsTab();
tempCalTab();
lengthCalTab();
tabs.add("General", generalPanel);
tabs.add("Options", optionsPanel);
tabs.add("Customers", customerPanel);
tabs.add("Contractors", contractorPanel);
tabs.add("Pools", poolPanel);
tabs.add("Hot Tubs", hotTubPanel);
tabs.add("Temp Calc", tempCalPanel);
tabs.add("Length Calc", lengthCalPanel);
pane.add(tabs);
}
private JButton createExitButton() {
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic('x');
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return exitButton;
}
private void generalTab() {
generalPanel = new JPanel(new FlowLayout());
String currentTime = SimpleDateFormat.getInstance().format(
Calendar.getInstance().getTime());
generalPanel.add(new JLabel("Today's Date: " + currentTime));
generalPanel.add(createExitButton());
}
private JTextField createTitleField(String text, int length) {
JTextField tf = new JTextField(length);
tf.setEditable(false);
tf.setFocusable(false);
tf.setText(text);
return tf;
}
// FIX
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
private void customerTab() {
customerPanel = createContactPanel("Customer", "customer.txt");
}
private void contractorTab() {
contractorPanel = createContactPanel("Contractor", "contractor.txt");
}
private void poolsTab() {
poolPanel = new JPanel(new FlowLayout());
final JRadioButton roundPool = new JRadioButton("Round Pool");
final JRadioButton ovalPool = new JRadioButton("Oval Pool");
final JRadioButton rectangularPool = new JRadioButton("Rectangle Pool");
roundPool.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundPool);
group.add(rectangularPool);
poolPanel.add(roundPool);
poolPanel.add(rectangularPool);
poolPanel.add(new JLabel("Enter the pool's length (ft): "));
final JTextField lengthField = new JTextField(10);
poolPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the pool's width (ft): ");
widthLabel.setEnabled(false);
poolPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
poolPanel.add(widthField);
poolPanel.add(new JLabel("Enter the pool's depth (ft): "));
final JTextField depthField = new JTextField(10);
poolPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
poolPanel.add(calculateVolume);
poolPanel.add(createExitButton());
poolPanel.add(new JLabel("The pool's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
poolPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(2, 20, "");
poolPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundPool.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundPool.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
}
if (rectangularPool.isSelected()) {
volume = length * width * depth * 5.9;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener poolsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundPool) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == rectangularPool) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
roundPool.addActionListener(poolsListener);
ovalPool.addActionListener(poolsListener);
rectangularPool.addActionListener(poolsListener);
}
private void hotTubsTab() {
hotTubPanel = new JPanel(new FlowLayout());
final JRadioButton roundTub = new JRadioButton("Round Tub");
final JRadioButton ovalTub = new JRadioButton("Oval Tub");
roundTub.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundTub);
group.add(ovalTub);
hotTubPanel.add(roundTub);
hotTubPanel.add(ovalTub);
hotTubPanel.add(new JLabel("Enter the tub's length (ft): "));
final JTextField lengthField = new JTextField(10);
hotTubPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the tub's width (ft): ");
widthLabel.setEnabled(false);
hotTubPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
hotTubPanel.add(widthField);
hotTubPanel.add(new JLabel("Enter the tub's depth (ft): "));
final JTextField depthField = new JTextField(10);
hotTubPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
hotTubPanel.add(calculateVolume);
hotTubPanel.add(createExitButton());
hotTubPanel.add(new JLabel("The tub's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
hotTubPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(1, 25,
"Width will be set to the same value as length");
hotTubPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundTub.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundTub.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0,2) * depth;
}
if (ovalTub.isSelected()) {
volume = Math.PI * ((length * width)*2) * depth;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener tubsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundTub) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == ovalTub) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);}
}
};
roundTub.addActionListener(tubsListener);
ovalTub.addActionListener(tubsListener);}
private void tempCalTab() {
tempCalPanel = new JPanel(new FlowLayout());
tempCalPanel.add(new JLabel("Enter temperature: "));
final JTextField temperatureField = new JTextField(10);
tempCalPanel.add(temperatureField);
final JComboBox optionComboBox = new JComboBox(
new String[] { "C", "F" });
tempCalPanel.add(optionComboBox);
tempCalPanel.add(new JLabel("Result: "));
final JTextField resultField = new JTextField(18);
resultField.setEditable(false);
tempCalPanel.add(resultField);
final JLabel oppositeLabel = new JLabel("F");
tempCalPanel.add(oppositeLabel);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
tempCalPanel.add(convertButton);
tempCalPanel.add(createExitButton());
final JTextArea messageArea = createMessageArea(1, 20,
"System Messages");
tempCalPanel.add(messageArea);
optionComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if ("F".equals(e.getItem())) {
oppositeLabel.setText("C");}
else {
oppositeLabel.setText("F");}}}
});
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidationResult result = validateFields(new JTextField[] { temperatureField });
String errors = "";
if (result.filled != 1 || result.valid != 1) {
errors += "Value set to zero";}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
temperatureField.setText("0");}
else {
messageArea.setVisible(false);}
double temperature = Double.parseDouble(temperatureField
.getText());
double resultValue = 0;
if (oppositeLabel.getText().equals("C")) {
resultValue = (temperature - 32.0) / 9.0 * 5.0;}
else if (oppositeLabel.getText().equals("F")) {
resultValue = ((temperature * 9.0) / 5.0) + 32.0;}
resultField.setText(df.format(resultValue));}
});
}
private void lengthCalTab() {
lengthCalPanel = new JPanel(new FlowLayout());
lengthCalPanel.add(createTitleField("Millimeters", 6));
lengthCalPanel.add(createTitleField("Meters", 4));
lengthCalPanel.add(createTitleField("Yards", 4));
lengthCalPanel.add(createTitleField("Feet", 3));
lengthCalPanel.add(createTitleField("Inches", 6));
final JTextField millimetersField = new JTextField(6);
final JTextField metersField = new JTextField(4);
final JTextField yardsField = new JTextField(4);
final JTextField feetField = new JTextField(3);
final JTextField inchesField = new JTextField(6);
lengthCalPanel.add(millimetersField);
lengthCalPanel.add(metersField);
lengthCalPanel.add(yardsField);
lengthCalPanel.add(feetField);
lengthCalPanel.add(inchesField);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double millimeters = convertToDouble(millimetersField.getText());
double meters = convertToDouble(metersField.getText());
double yards = convertToDouble(yardsField.getText());
double feet = convertToDouble(feetField.getText());
double inches = convertToDouble(inchesField.getText());
double value = 0;
if (millimeters != 0) {
value = millimeters * MILLIMETER;}
else if (meters != 0) {
value = meters * METER;}
else if (yards != 0) {
value = yards * YARD;}
else if (feet != 0) {
value = feet * FOOT;}
else if (inches != 0) {
value = inches * INCH;}
millimeters = value / MILLIMETER;
meters = value / METER;
yards = value / YARD;
feet = value / FOOT;
inches = value / INCH;
millimetersField.setText(df.format(millimeters));
metersField.setText(df.format(meters));
yardsField.setText(df.format(yards));
feetField.setText(df.format(feet));
inchesField.setText(df.format(inches));}
private double convertToDouble(String s) {
try {
return Double.parseDouble(s);}
catch (Exception e) {
return 0;}}
});
JButton clearButton = new JButton("Clear");
clearButton.setMnemonic('l');
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
millimetersField.setText(null);
metersField.setText(null);
yardsField.setText(null);
feetField.setText(null);
inchesField.setText(null);}
});
lengthCalPanel.add(convertButton);
lengthCalPanel.add(clearButton);
lengthCalPanel.add(createExitButton());}
private String loadDataFromFile(String fileName) {
String data = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
data += reader.readLine() + "\n";}
reader.close();}
catch (IOException e){
}
return data;}
private JPanel createContactPanel(final String contactName,
final String fileName) {
JPanel pane = new JPanel(new FlowLayout());
final JTextArea customerDisplay = new JTextArea(8, 25);
customerDisplay.setLineWrap(true);
customerDisplay.setEditable(false);
pane.add(new JScrollPane(customerDisplay));
pane.add(createExitButton());
JButton addCustomerButton = new JButton("Add " + contactName);
addCustomerButton.setMnemonic('A');
pane.add(addCustomerButton);
JButton refreshButton = new JButton("Refresh");
refreshButton.setMnemonic('R');
pane.add(refreshButton);
final JTextArea messageArea = createMessageArea(2, 25, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
addCustomerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new EditContact(contactName, fileName);}
});
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = loadDataFromFile(fileName);
if (data != "") {
customerDisplay.setText(data);
customerDisplay.setEnabled(true);
messageArea.setText("File " + fileName
+ " can be read from!");
}
else {
customerDisplay.setText("Click Add "
+ contactName
+ " button to add "
+ contactName.toLowerCase()
+ ". And click Refresh button to update this pane.");
customerDisplay.setEnabled(false);
messageArea.setText("File " + fileName + " is not "
+ "there yet! It will be created "
+ "when you add " + contactName.toLowerCase()
+ "s!");
}
}
});
refreshButton.doClick();
return pane;
}
private JTextArea createMessageArea(int rows, int cols, String text) {
final JTextArea messageArea = new JTextArea(rows, cols);
messageArea.setBorder(BorderFactory.createEmptyBorder());
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setFont(new Font("System", Font.PLAIN, 12));
messageArea.setText(text);
messageArea.setBackground(null);
messageArea.setForeground(Color.GRAY);
messageArea.setEnabled(true);
messageArea.setFocusable(false);
return messageArea;
}
private class ValidationResult {
int filled;
int valid;
}
private ValidationResult validateFields(JTextField[] fields) {
ValidationResult result = new ValidationResult();
for (int i = 0; i < fields.length; i++) {
JTextField field = fields[i];
if ((field.getText() != null) && (field.getText().length() > 0)) {
result.filled++;
}
try {
Double.parseDouble(field.getText());
field.setBackground(Color.white);
result.valid++;
}
catch (Exception e) {
field.setBackground(Color.orange);
}
}
return result;
}
private class EditContact extends JDialog {
private static final long serialVersionUID = 1L;
private final String contactName;
private final String fileName;
private File file;
private JTextField nameField;
private JTextField addressField;
private JTextField cityField;
private JComboBox stateComboBox;
private JTextField zipField;
private JTextField phoneField;
private JTextArea messageArea;
public EditContact(String contactName, String fileName) {
super(poolCalc.this, contactName + "s");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(418, 300);
this.contactName = contactName;
this.fileName = fileName;
initializeComponents();
if (openFile()) {
displayMessage(null);
}
else {
displayMessage("File " + fileName + " does not exist yet! "
+ "Will be created when you add a "
+ contactName.toLowerCase() + "!");
}
setLocationRelativeTo(null);
setVisible(true);
}
private void displayMessage(String message) {
if (message != null) {
messageArea.setVisible(true);
messageArea.setText(message);
}
else {
messageArea.setVisible(false);
}
}
private boolean openFile() {
file = new File(fileName);
return file.exists();
}
private boolean deleteFile() {
return file.exists() && file.delete();
}
private boolean saveToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file,
true));
writer.write("Name: " + nameField.getText() + "\n");
writer.write("Address: " + addressField.getText() + "\n");
writer.write("City: " + cityField.getText() + "\n");
writer.write("State: "
+ stateComboBox.getSelectedItem().toString() + "\n");
writer.write("ZIP: " + zipField.getText() + "\n");
writer.write("Phone: " + phoneField.getText() + "\n");
writer.write("\n");
writer.close();
return true;
}
catch (IOException e) {
return false;
}
}
private void initializeComponents() {
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
pane.add(new JLabel(contactName + " Name "));
nameField = new JTextField(25);
pane.add(nameField);
pane.add(new JLabel("Address "));
addressField = new JTextField(28);
pane.add(addressField);
pane.add(new JLabel("City "));
cityField = new JTextField(32);
pane.add(cityField);
pane.add(new JLabel("State "));
stateComboBox = new JComboBox(new String[] { "AL", "AK", "AZ",
"AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX",
"UT", "VT", "VA", "WA", "WV", "WI", "WY" });
pane.add(stateComboBox);
pane.add(new JLabel("ZIP "));
zipField = new JTextField(5);
pane.add(zipField);
pane.add(new JLabel("Phone "));
phoneField = new JTextField(10);
pane.add(phoneField);
JButton addContactButton = new JButton("Add " + this.contactName);
addContactButton.setMnemonic('A');
addContactButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveToFile()) {
displayMessage(contactName + " added");
}
else {
displayMessage("File saving error!");
}
}
});
pane.add(addContactButton);
JButton closeButton = new JButton("Close");
closeButton.setMnemonic('C');
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
pane.add(closeButton);
JButton deleteFileButton = new JButton("Delete File");
deleteFileButton.setMnemonic('D');
deleteFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (deleteFile()) {
displayMessage("File " + fileName + " deleted!");
}
}
});
pane.add(deleteFileButton);
messageArea = createMessageArea(2, 30, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
}
}
}
Let's start with this (which I assume is where you create the details)...
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
The newTitle field is a local variable, so once the method exists, you will not be able to access the field (easily)...
You seem to have tried adding a actionListener to the newName button, which isn't a bad idea, but because you can't actually access the newTitle field, isn't going to help...
The use of setBounds is not only ill advised, but probably won't result in the results you are expecting, because the optionsPane is under the control a layout manager...
And while I was digging around, I noticed this if (errors != "") {...This is not how String comparison is done in Java. This is comparing the memory references of both Strings which will never be true, instead you should if (!"".equals(errors)) {...
But back to the problem at hand...
You are really close to having a solution. You could make the newTitle field a class instance variable, which would allow you to access the field within other parts of your program, but because you've made it final, there's something else you can try...
You can use an anonymous inner class instead...
newName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
Which should get a good nights sleep :D
It is a little unclear what you want, but if I understand you right you want the JButton newName to set the title of the JFrame to the text in some textbox?
In that case you would write
setTitle(someTextbox.getText());
inside the function of the button.
First, you need to create a JTextField that has public access. Then, create a JButton that implements ActionListener. After that you must implement the abstract method actionPerformed() in the JButton Subclass. Then in the run method say JFrame.setTitle(JTextfield.getText()).
Subclass Method:
public class main extends JFrame{
// Construct and setVisible()
}
class textfield extends JTextField{
// create field then add to JFrame
}
class button extends JButton implements ActionListener{
// create button
public void actionPerformed(ActionEvent e){
main.setTitle(textfield.getText());
}
Instance Method:
public class main implements ActionListener{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField field = new JTextField();
JButton button = new JButtone();
button.addActionListener(this);
panel.add(field);
panel.add(button);
frame.add(panel);
public void actionPerformed(ActionEvent e){
frame.setTitle(field.getText);
}
}
Try This
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
// optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
// newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
Hello guys would someone please help me with my program? I have a JComboBox and it has several items inside it. What I want to happen is that whenever the user will click a certain item inside the combobox it should display its item quantity. For example, I clicked on PM1 twice it should display 2 in quantity, if i clicked on PM4 five times then it should display 5 in quantity. I have two classes involved in my program the and the codes are below. By the way I also want to display the quantities beside the item displayed in class CopyShowOrder. Any help will be extremely appreciated Thanks in advance and more power!
Codes of CopyShow:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CopyShow{
private static String z = "";
private static String w = "";
private static String x = "";
JComboBox combo;
private static String a = "";
public CopyShow(){
String mgaPagkainTo[] = {"PM1 (Paa/ Spicy Paa with Thigh part)","PM2 (Pecho)","PM3 (Pork Barbeque 4 pcs.)","PM4 (Bangus Sisig)","PM5 (Pork Sisig)","PM6 (Bangus Inihaw)","SM1 (Paa)","SM2 (Pork Barbeque 2 pcs.)","Pancit Bihon","Dinuguan at Puto","Puto","Ensaladang Talong","Softdrinks","Iced Tea","Halo-Halo","Leche Flan","Turon Split"};
JFrame frame = new JFrame("Mang Inasal Ordering System");
JPanel panel = new JPanel();
combo = new JComboBox(mgaPagkainTo);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
panel.add(combo);
frame.add(panel);
combo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String str = (String)combo.getSelectedItem();
a = str;
CopyShowOrder messageOrder1 = new CopyShowOrder();
messageOrder1.ShowOrderPo();
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,250);
frame.setVisible(true);
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
boolean ulitinMoPows = true;
boolean tryAgain = true;
System.out.print("\nInput Customer Name: ");
String customerName = inp.nextLine();
w = customerName;
System.out.print("\nInput Cashier Name: ");
String user = inp.nextLine();
z = user;
do{
System.out.print("\nInput either Dine In or Take Out: ");
String dInDOut = inp.nextLine();
x = dInDOut;
if (x.equals("Dine In") || x.equals("Take Out")){
System.out.print("");
ulitinMoPows = false;
}
else{
JOptionPane.showMessageDialog(null, "Try again! Please input Dine In or Take Out only!","Error", JOptionPane.ERROR_MESSAGE);
ulitinMoPows = true;
System.out.print ("\f");
}
}while(ulitinMoPows);
do{
System.out.print("\nInput password: ");
String pass = inp.nextLine();
if(pass.equals("admin")){
CopyShowOrder messageShowMenu = new CopyShowOrder();
messageShowMenu.ShowMo();
tryAgain = false;
}
if(!pass.equals("admin")){
JOptionPane.showMessageDialog(null, "Try again! Invalid password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
tryAgain = true;
System.out.print ("\f");
}
}while(tryAgain);
CopyShow j = new CopyShow();
}
public static String kuhaOrder()
{
return a;
}
public static String kuhaUserName()
{
return z;
}
public static String kuhaCustomerName()
{
return w;
}
public static String kuhaSanKainPagkain()
{
return x;
}
}
Codes of CopyShowOrder:
public class CopyShowOrder {
public void ShowMo(){
String user = CopyShow.kuhaUserName();
System.out.print("\n\n\t\tCashier: " +user);
String dInDOut = CopyShow.kuhaSanKainPagkain();
System.out.print(" "+dInDOut);
String customerName = CopyShow.kuhaCustomerName();
System.out.print("\n\t\tCustomer Name: " +customerName);
}
public void ShowOrderPo() {
String order = CopyShow.kuhaOrder();
System.out.print("\t\t\t\t\n " +order);
}
}
I'm not sure if is that what you want, but here it goes..
You can have an idea..
import java.awt.BorderLayout;
public class StackOverflow extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTable table;
private JComboBox comboBox = new JComboBox();
private JButton button = new JButton("+");
private JButton button_1 = new JButton("-");
private JScrollPane scrollPane = new JScrollPane();
private List<String> list = new ArrayList<String>();
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
StackOverflow dialog = new StackOverflow();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public StackOverflow() {
setTitle("StackOverflow");
setBounds(100, 100, 339, 228);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"ITEM 1", "ITEM 2", "ITEM 3", "ITEM 4", "ITEM 5", "ITEM 6"}));
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
scrollPane.setBounds(10, 43, 303, 131);
contentPanel.add(scrollPane);
{
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Item", "Count"
}
));
scrollPane.setViewportView(table);
}
}
//Gets the table model and clear it
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
//Add comboBox items to table
for (int i = 0; i < comboBox.getItemCount(); i++)
model.addRow(new Object[] { comboBox.getItemAt(i) , 0 });
comboBox.setBounds(10, 12, 203, 20);
contentPanel.add(comboBox);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String selectedItem = (String) comboBox.getSelectedItem();
for (int i = 0; i < table.getRowCount(); i++) {
String tableItem = (String) table.getValueAt(i, 0);
int count = (Integer) table.getValueAt(i, 1)+1;
if (selectedItem.equals(tableItem)) {
table.setValueAt(count, i, 1);
}
}
}
});
button.setBounds(223, 11, 41, 23);
contentPanel.add(button);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String selectedItem = (String) comboBox.getSelectedItem();
for (int i = 0; i < table.getRowCount(); i++) {
String tableItem = (String) table.getValueAt(i, 0);
int count = (Integer) table.getValueAt(i, 1)-1;
if (selectedItem.equals(tableItem)) {
table.setValueAt(count, i, 1);
}
}
}
});
button_1.setBounds(272, 11, 41, 23);
contentPanel.add(button_1);
}
}
I'm adding a string to a JList with DefaultListModel and it takes seconds to appear. Sometimes, I may have to click on the JList to have the list appear.
I'm using Eclipse Indigo. When I set a breakpoint after adding the element to JList, execution is fast.
I searched the web and SO for JList slow and they all talk about adding many items to the list. I'm adding the first element to the list.
Here's my code fragments:
private DefaultListModel function_list_model = new DefaultListModel();
private JList list_functions = new JList(function_list_model);
//...
// Initialization code:
JPanel panel_function_list = new JPanel();
panel_function_list.setBounds(10, 53, 541, 220);
panel_functions.add(panel_function_list);
panel_function_list.setLayout(null);
JLabel lblFunctions = new JLabel("Functions");
lblFunctions.setHorizontalAlignment(SwingConstants.CENTER);
lblFunctions.setBounds(235, 11, 99, 14);
panel_function_list.add(lblFunctions);
list_functions.setBorder(new LineBorder(new Color(0, 0, 0)));
list_functions.setBounds(10, 42, 492, 177);
list_functions.setFont(new Font("Courier New", Font.PLAIN, 12));
list_functions.setPreferredSize(new Dimension(0, 150));
list_functions.setMinimumSize(new Dimension(32767, 100));
list_functions.setMaximumSize(new Dimension(32767, 100));
JScrollPane scrollPane_functions = new JScrollPane(list_functions);
scrollPane_functions.setBounds(10, 79, 541, 183);
panel_functions.add(scrollPane_functions);
// Code to add a string:
String burger = new String("burger");
function_list_model.addElement(burger);
I'm also using WindowBuilder with Eclipse.
So how do I improve the performance of JList?
if you want I can to generating new Item from Char[] and to call doClick() for JButton("Fire")
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.*;
public class ListDemo extends JPanel implements ListSelectionListener {
private JList list;
private DefaultListModel listModel;
private static final String hireString = "Hire";
private static final String fireString = "Fire";
private JButton fireButton;
private JTextField employeeName;
private javax.swing.Timer timer = null;
private int delay = 3;
private int count = 0;
public ListDemo() {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
list.setVisibleRowCount(5);
JScrollPane listScrollPane = new JScrollPane(list);
JButton hireButton = new JButton(hireString);
HireListener hireListener = new HireListener(hireButton);
hireButton.setActionCommand(hireString);
hireButton.addActionListener(hireListener);
hireButton.setEnabled(false);
fireButton = new JButton(fireString);
fireButton.setActionCommand(fireString);
fireButton.addActionListener(new FireListener());
employeeName = new JTextField(10);
employeeName.addActionListener(hireListener);
employeeName.getDocument().addDocumentListener(hireListener);
String name = listModel.getElementAt(list.getSelectedIndex()).toString();
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(fireButton);
buttonPane.add(Box.createHorizontalStrut(5));
buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
buttonPane.add(Box.createHorizontalStrut(5));
buttonPane.add(employeeName);
buttonPane.add(hireButton);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
add(listScrollPane, BorderLayout.CENTER);
add(buttonPane, BorderLayout.PAGE_END);
start();
System.out.println(new Date());
}
private void start() {
timer = new javax.swing.Timer(delay * 10, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
list.ensureIndexIsVisible(listModel.getSize()-1);
count++;
if (count >= 500) {
timer.stop();
System.out.println("update cycle completed");
System.out.println(new Date());
}
}
};
}
class FireListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int index = list.getSelectedIndex();
listModel.remove(index);
int size = listModel.getSize();
if (size == 0) { //Nobody's left, disable firing.
fireButton.setEnabled(false);
} else { //Select an index.
if (index == listModel.getSize()) {
index--;
}
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
}
}
class HireListener implements ActionListener, DocumentListener {
private boolean alreadyEnabled = false;
private JButton button;
HireListener(JButton button) {
this.button = button;
}
#Override
public void actionPerformed(ActionEvent e) {
String name = employeeName.getText();
if (name.isEmpty() || alreadyInList(name)) {
Toolkit.getDefaultToolkit().beep();
employeeName.requestFocusInWindow();
employeeName.selectAll();
return;
}
int index = list.getSelectedIndex(); //get selected index
if (index == -1) { //no selection, so insert at beginning
index = 0;
} else { //add after the selected item
index++;
}
listModel.insertElementAt(employeeName.getText(), index);
//listModel.addElement(employeeName.getText());
employeeName.requestFocusInWindow();
employeeName.setText("");
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
protected boolean alreadyInList(String name) {
return listModel.contains(name);
}
#Override
public void insertUpdate(DocumentEvent e) {
enableButton();
}
#Override
public void removeUpdate(DocumentEvent e) {
handleEmptyTextField(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
if (!handleEmptyTextField(e)) {
enableButton();
}
}
private void enableButton() {
if (!alreadyEnabled) {
button.setEnabled(true);
}
}
private boolean handleEmptyTextField(DocumentEvent e) {
if (e.getDocument().getLength() <= 0) {
button.setEnabled(false);
alreadyEnabled = false;
return true;
}
return false;
}
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
fireButton.setEnabled(false);
} else {
fireButton.setEnabled(true);
}
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ListDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ListDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}