Java actionPerformed not applying to other methods - java

Here's the initialization of the controls.
public void init(){
...
c = new JComboBox();
....
c.addActionListener(this);
p2 = new JPanel();
vt = new Vector();
ChannelList cl = new ChannelList();
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
p2.add(jp);
p2.setBorder(new TitledBorder("Channel Titles Available"));
p2.setLayout(new GridLayout(1,1,10,10));
}
The part of actionPerformed() method is supposed to determine the selection from JCombobox, and put the correct objects to JList.
#Override
public void actionPerformed(ActionEvent e) {
JComboBox c = (JComboBox)e.getSource();
String genre = (String)c.getSelectedItem();
System.out.println(genre);
vt = new Vector();
ChannelList cl = new ChannelList();
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
switch(genre){
case "All Genres":
vt.add(cl.chList[i].getChTitle());
break;
case "Entertainment":
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
break;
}
}
}
Here's a part of ChannelList:
public void createList()
{
chList = new ChannelInfo[19];
chList[0] = new ChannelInfo("BBC Canada",3.99, 5.99,'e',"bbccan.jpg");
chList[1] = new ChannelInfo("Bloomberg TV",3.99, 5.99,'n',"bloom.jpg");
...
}
There is no error message while running the program. The first part of actionPerformed which prints the String is working properly (which is useless).
However, there's no result showing in JList.
In order to make it more clear, here's the whole file:
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.Vector;
import java.util.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
public class AS4Temp extends JApplet implements ItemListener, ActionListener{
JPanel p,p1,p2;
JComboBox c;
JList lchannels;
JScrollPane jp;
Vector vt;
Container con;
public void init(){
p = new JPanel();
p.setLayout(new GridLayout(3,3,10,10));
//Genre
p1 = new JPanel();
c = new JComboBox();
c.addItem("Please Select Genre of Channel");
c.addItem("All Genres");
c.addItem("Entertainment");
c.addItem("Movie");
c.addItem("News/Business");
c.addItem("Sci-Fi");
c.addItem("Sports");
c.addActionListener(this);
p1.add(c);
p1.setLayout(new FlowLayout());
p1.setBorder(new TitledBorder("Channel Genre"));
//Channels
p2 = new JPanel();
vt = new Vector();
ChannelList cl = new ChannelList();
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
/*
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
}*/
p2.add(jp);
p2.setBorder(new TitledBorder("Channel Titles Available"));
p2.setLayout(new GridLayout(1,1,10,10));
//all panels
p.add(p1);
p.add(p2);
con = getContentPane();
con.add(p);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox c = (JComboBox)e.getSource();
String genre = (String)c.getSelectedItem();
System.out.println(genre);
ChannelList cl = new ChannelList();
cl.createList();
switch(genre){
case "All Genres":
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
vt.add(cl.chList[i].getChTitle());
}
break;
case "Entertainment":
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
}
break;
}
/*
for(int i =0; i < cl.chList.length; i++){
char chGenre = cl.chList[i].getChGenre();
switch(genre){
case "All Genres":
vt.add(cl.chList[i].getChTitle());
break;
case "Entertainment":
if(chGenre == 'e')
vt.add(cl.chList[i].getChTitle());
break;
}
}*/
}
}

I'm guessing here based on partial information, but I see you creating new components including a new JList and a new JScrollPane:
lchannels = new JList(vt);
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
But I don't see that JScrollPane being added to anything, and so it would make sense that none of that would display.
It seems that you may want to go about this very differently, that rather than creating a new JList() and new JScrollPane(...) you probably want to create a new JList model and set the existing JList with this new model, either that or simply change the data held by the existing JList model.
Consider creating a DefaultListModelField object inside of your actionPerformed method, say called listModel, callingaddElement(...)` on it to fill it with data, and then call
myList.setModel(listModel);
on your existing and displayed JList.
For example, here is my minimal example program, or MCVE:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Mcve extends JPanel {
private static final String[] DATA = {"One", "Two", "Three", "Four", "Five"};
private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
private JComboBox<String> comboBox = new JComboBox<>(comboModel);
private DefaultListModel<String> listModel = new DefaultListModel<>();
private JList<String> list = new JList<>(listModel);
public Mcve() {
list.setPrototypeCellValue(String.format("%30s", " "));
list.setVisibleRowCount(10);;
// fill combo box's model with a bunch of junk
for (int i = 0; i < 10; i++) {
for (int j = 0; j < DATA.length; j++) {
String text = DATA[j] + " " + i;
comboModel.addElement(text);
}
}
Action buttonAction = new ButtonAction("Transfer Data");
comboBox.addActionListener(buttonAction);
add(comboBox);
add(new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
add(new JButton(buttonAction));
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Object selection = comboBox.getSelectedItem();
if (selection != null) {
listModel.addElement(selection.toString());
}
}
}
private static void createAndShowGui() {
Mcve mainPanel = new Mcve();
JFrame frame = new JFrame("Mcve");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You're using a Vector in place of list model, and you seem to be assuming that changing the Vector later on in your program will change the JList -- but it won't. Instead get rid of that Vector, vt, and again please do what I recommend -- use a DefaultListModel in its place. For example, please see changes to code below. Changes are marked with // !! comments:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class AS4Temp extends JApplet implements ActionListener {
JPanel p, p1, p2;
JComboBox c;
JList lchannels;
JScrollPane jp;
// !! Vector vt;
private DefaultListModel<String> listModel = new DefaultListModel<>(); // !!
Container con;
public void init() {
p = new JPanel();
p.setLayout(new GridLayout(3, 3, 10, 10));
// Genre
p1 = new JPanel();
c = new JComboBox();
c.addItem("Please Select Genre of Channel");
c.addItem("All Genres");
c.addItem("Entertainment");
c.addItem("Movie");
c.addItem("News/Business");
c.addItem("Sci-Fi");
c.addItem("Sports");
c.addActionListener(this);
p1.add(c);
p1.setLayout(new FlowLayout());
p1.setBorder(new TitledBorder("Channel Genre"));
// Channels
p2 = new JPanel();
// !! vt = new Vector();
ChannelList cl = new ChannelList();
// !! lchannels = new JList(vt);
lchannels = new JList<>(listModel); // !!
lchannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp = new JScrollPane(lchannels);
cl.createList();
/*
* for(int i =0; i < cl.chList.length; i++){ char chGenre =
* cl.chList[i].getChGenre(); if(chGenre == 'e')
* vt.add(cl.chList[i].getChTitle()); }
*/
p2.add(jp);
p2.setBorder(new TitledBorder("Channel Titles Available"));
p2.setLayout(new GridLayout(1, 1, 10, 10));
// price
// all panels
p.add(p1);
p.add(p2);
con = getContentPane();
con.add(p);
}
#Override
public void actionPerformed(ActionEvent e) {
JComboBox c = (JComboBox) e.getSource();
String genre = (String) c.getSelectedItem();
System.out.println(genre);
ChannelList cl = new ChannelList();
cl.createList();
switch (genre) {
case "All Genres":
for (int i = 0; i < cl.chList.length; i++) {
char chGenre = cl.chList[i].getChGenre();
// !! vt.add(cl.chList[i].getChTitle());
listModel.addElement(cl.chList[i].getChTitle()); // !!
}
break;
case "Entertainment":
for (int i = 0; i < cl.chList.length; i++) {
char chGenre = cl.chList[i].getChGenre();
if (chGenre == 'e')
// !! vt.add(cl.chList[i].getChTitle());
listModel.addElement(cl.chList[i].getChTitle()); // !!
}
break;
}
}
}
// !! added to make your code compilable
// !! in the future, please don't force us to do this kludge
class ChannelList {
public Channel[] chList;
public ChannelList() {
createList();
}
public void createList() {
chList = new Channel[5];
chList[0] = new Channel("Foobar1", 'e');
chList[1] = new Channel("Foobar2", 'e');
chList[2] = new Channel("Foobar3", 'e');
chList[3] = new Channel("Foobar4", 'e');
chList[4] = new Channel("Foobar5", 'e');
}
}
// !! added to make your code compilable
// !! in the future, please don't force us to do this kludge
class Channel {
private String title;
private char genre;
public Channel(String title, char genre) {
this.title = title;
this.genre = genre;
}
public char getChGenre() {
return genre;
}
public String getChTitle() {
return title;
}
#Override
public String toString() {
return "Channel [title=" + title + ", genre=" + genre + "]";
}
}

Problem is you are adding a new JList on actionPerformed() and you have not added the list to the container.
lchannels = new JList(vt);
Well you don't need to add a new list on selection, all you need is to update the list model itself on selection.

Related

How do I add an ActionListener to a JCheckBox?

Problem
So my program takes in a .csv file and loads the data and displays it. When data is loaded in, it creates a new JCheckBox for every column header there is in the data. How do I add an ActionListener such that when the user ticks/unticks any of the boxes, it should do a certain function?
When data is loaded in, it updates the JPanel by the code:
public void updateChecklistPanel(){
checklistPanel.removeAll();
checklistPanel.setLayout(new GridLayout(currentData.getColumnNames().length, 1, 10, 0));
for (String columnName : currentData.getColumnNames()){
JCheckBox checkBox = new JCheckBox();
checkBox.setText(columnName);
checklistPanel.add(checkBox);
}
checklistPanel.revalidate();
checklistPanel.repaint();
}
I also have the following at the bottom:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newDataFrameItem){
newFile();
System.out.println("New DataFrame Loaded in");
}
if (e.getSource() == loadDataFrameItem){
loadFile();
System.out.println(".csv Data loaded into DataFrame.");
}
if (e.getSource() == saveDataFrameItem){
System.out.println("Saved the data to a .csv file");
}
}
What I'm trying to do is that when a checkbox is unticked, it should hide a column in the JTable and when ticked, it should redisplay the column.
Current Solution
The solution that I have come up with is to make a variable allColumnHeaders that is an ArrayList of Strings. I then also have a variable shownColumnHeaders that is an ArrayList of Booleans. When the user wants to show/hide a column, the showColumn(String columnName) and hideColumn(String columnName) function finds the index of the column Name in allColumnHeaders and sets the Boolean value of the index in shownColumnHeaders to either true/false.
It the proceeds to create a new table model where the columns are only added if the Boolean value for that column is true. It will then set the model for the table to the new table model.
The code for the following is show below:
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class MRE extends JPanel {
private static JTable table;
private static ArrayList<String> allColumnHeaders = new ArrayList<>();
private static ArrayList<Boolean> shownColumnHeaders = new ArrayList<>();
private static void createAndShowGUI()
{
table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
for (int i = 0; i < table.getColumnCount(); i++) {
String column = table.getColumnName(i);
allColumnHeaders.add(column);
JCheckBox checkBox = new JCheckBox(column);
checkBox.addActionListener(event -> {
JCheckBox cb = (JCheckBox) event.getSource();
if (cb.isSelected()) {
System.out.println(checkBox.getText() + " is now being displayed");
showColumn(checkBox.getText());
} else {
System.out.println(checkBox.getText() + " is now being hidden");
hideColumn(checkBox.getText());
}
table.setModel(createTableModel());
});
checkBox.setSelected( true );
buttons.add( checkBox );
shownColumnHeaders.add(true);
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static DefaultTableModel createTableModel(){
DefaultTableModel tableModel = new DefaultTableModel(0, 0);
String[] columnValues = new String[1];
for (int i = 0; i < shownColumnHeaders.size(); i++){
if (shownColumnHeaders.get(i)){
tableModel.addColumn(allColumnHeaders.get(i), columnValues);
}
}
return tableModel;
}
public static void showColumn(String columnName){
for (int i = 0; i < allColumnHeaders.size(); i++) {
if (allColumnHeaders.get(i).equals(columnName)){
shownColumnHeaders.set(i, true);
}
}
}
public static void hideColumn(String columnName){
for (int i = 0; i < allColumnHeaders.size(); i++) {
if (allColumnHeaders.get(i).equals(columnName)){
shownColumnHeaders.set(i, false);
}
}
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
Introduction
It took me a while, but I came up with the following JTable GUI. Here's the starting display.
Here's the GUI after I remove the item description.
Here's the GUI after I remove the item price.
Here's the GUI after I add the columns back.
Explanation
I created an Item class to hold one item.
I created an Inventory class to hold a List of Item instances and a String array of the column headers.
I created the JFrame and two JPanels. One JPanel holds the JTable and the other holds the JCheckBoxes. I used Swing layout managers to create the JPanels.
So far, so basic. Creating the JTable took a bit of effort. I wanted to display the item price as currency, but that wasn't important for this example GUI.
I created an ActionListener to add and remove columns from the JTable. I had to experiment a bit. The TableColumnModel addColumn method appends the column to the table.
I had to create a DisplayTableColumn class to hold a TableColumn and a boolean that tells me whether or not to display the TableColumn. I wound up removing all the columns from the JTable and adding all the columns back to the JTable so that I could maintain the column sequence. I probably ran 100 tests before I could get this code to work.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class JCheckBoxTableGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JCheckBoxTableGUI());
}
private final Inventory inventory;
private final InventoryTableModel tableModel;
private JFrame frame;
private JTable table;
public JCheckBoxTableGUI() {
this.tableModel = new InventoryTableModel();
this.inventory = new Inventory();
String[] columns = inventory.getTableHeader();
for (String column : columns) {
tableModel.addColumn(column);
}
List<Item> items = inventory.getInventory();
for (Item item : items) {
Object[] object = new Object[5];
object[0] = item.getItemNumber();
object[1] = item.getItemName();
object[2] = item.getItemDescription();
object[3] = item.getItemQuantity();
object[4] = item.getItemPrice();
tableModel.addRow(object);
}
}
#Override
public void run() {
frame = new JFrame("JCheckBox Table GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTablePanel(), BorderLayout.CENTER);
frame.add(createSelectionPanel(), BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTablePanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(2).setPreferredWidth(150);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(100);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(620, 300));
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private JPanel createSelectionPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel innerPanel = new JPanel(new GridLayout(0, 1, 5, 5));
ColumnListener listener = new ColumnListener(this);
String[] columns = inventory.getTableHeader();
for (String column : columns) {
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.addActionListener(listener);
checkBox.setActionCommand(column);
checkBox.setSelected(true);
innerPanel.add(checkBox);
}
panel.add(innerPanel);
return panel;
}
public JTable getTable() {
return table;
}
public JFrame getFrame() {
return frame;
}
public class ColumnListener implements ActionListener {
private final JCheckBoxTableGUI frame;
private final List<DisplayTableColumn> displayColumns;
public ColumnListener(JCheckBoxTableGUI frame) {
this.frame = frame;
this.displayColumns = new ArrayList<>();
TableColumnModel tcm = frame.getTable().getColumnModel();
for (int index = 0; index < tcm.getColumnCount(); index++) {
TableColumn tc = tcm.getColumn(index);
displayColumns.add(new DisplayTableColumn(tc, true));
}
}
#Override
public void actionPerformed(ActionEvent event) {
JCheckBox checkBox = (JCheckBox) event.getSource();
String column = event.getActionCommand();
TableColumnModel tcm = frame.getTable().getColumnModel();
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (dtc.isShowTableColumn()) {
tcm.removeColumn(dtc.getTableColumn());
}
}
int columnIndex = getColumnIndex(column);
displayColumns.get(columnIndex).setShowTableColumn(
checkBox.isSelected());
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (dtc.isShowTableColumn()) {
tcm.addColumn(dtc.getTableColumn());
}
}
frame.getFrame().pack();
}
private int getColumnIndex(String column) {
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (column.equals(dtc.getTableColumn().getHeaderValue())) {
return index;
}
}
return -1;
}
}
public class DisplayTableColumn {
private boolean showTableColumn;
private final TableColumn tableColumn;
public DisplayTableColumn(TableColumn tableColumn, boolean showTableColumn) {
this.tableColumn = tableColumn;
this.showTableColumn = showTableColumn;
}
public boolean isShowTableColumn() {
return showTableColumn;
}
public void setShowTableColumn(boolean showTableColumn) {
this.showTableColumn = showTableColumn;
}
public TableColumn getTableColumn() {
return tableColumn;
}
}
public class InventoryTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex <= 2) {
return String.class;
} else if (columnIndex == 3) {
return Integer.class;
} else {
return Integer.class;
}
}
}
public class Inventory {
private final List<Item> inventory;
private final String[] tableHeader;
public Inventory() {
this.tableHeader = new String[] { "Item Number", "Item Name",
"Item Description", "Item Quantity",
"Item Price" };
this.inventory = new ArrayList<>();
inventory.add(new Item("X101111", "Samsung Camera", " ", 20, 69.99));
inventory.add(new Item("X101112", "Samsung Monitor", " ", 10, 279.99));
inventory.add(new Item("X101113", "Samsung Smartphone", " ", 110, 599.99));
inventory.add(new Item("X101114", "Apple Watch", " ", 20, 1259.99));
inventory.add(new Item("X101115", "Sony Playstation 5", " ", 0, 399.99));
}
public String[] getTableHeader() {
return tableHeader;
}
public List<Item> getInventory() {
return inventory;
}
}
public class Item {
private int itemPrice;
private int itemQuantity;
private final String itemNumber;
private final String itemName;
private final String itemDescription;
public Item(String itemNumber, String itemName,
String itemDescription, int itemQuantity, double itemPrice) {
this.itemNumber = itemNumber;
this.itemName = itemName;
this.itemDescription = itemDescription;
this.itemQuantity = itemQuantity;
setItemPrice(itemPrice);
}
public int getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = (int) Math.round(itemPrice * 100.0);
}
public int getItemQuantity() {
return itemQuantity;
}
public void setItemQuantity(int itemQuantity) {
this.itemQuantity = itemQuantity;
}
public String getItemNumber() {
return itemNumber;
}
public String getItemName() {
return itemName;
}
public String getItemDescription() {
return itemDescription;
}
}
}
This only demonstrates how to create a basic MRE:
the csv file is irrelevant.
data in the model is irrelevant.
your loadFile, newFile and saveFile buttons are irrelevant.
the TableModel is irrelevant
Your question is about adding an ActionListener to dynamically created checkboxes based on the columns of the table.
So all you need is a table with some columns and the resulting checkboxes.
import java.awt.*;
import javax.swing.*;
public class MRE extends JPanel
{
private static void createAndShowGUI()
{
JTable table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
for (int i = 0; i < table.getColumnCount(); i++)
{
String column = table.getColumnName(i);
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.setSelected( true );
buttons.add( checkBox );
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
If you can modify this to demonstrate how to use your "reusable class" to manage column visibility, then I will update the above code to use my reusable class with 4 additional lines of code.
Edit:
Suggested improvements to your code:
Make the code reusable and self contained
Don't use static methods
Don't change the data.
Your original question was:
How do I add an ActionListener to a JCheckBox?
So to do that you need a class that:
implements an ActionListener
is self contained to implement the functionality you require.
So the basic structure could be like the following:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SomeFunction implements ActionListener
{
private JTable table;
public SomeFunction(JTable table)
{
this.table = table;
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() instanceof AbstractButton)
{
String command = e.getActionCommand();
AbstractButton button = (AbstractButton)e.getSource();
if (button.isSelected())
doSelected( command );
else
doUnselected( command );
}
}
private void doSelected(String command)
{
System.out.println(command + " selected");
}
private void doUnselected(String command)
{
System.out.println(command + " unselected");
}
private static void createAndShowGUI()
{
JTable table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
SomeFunction listener = new SomeFunction( table ); // added
// TableColumnManager listener = new TableColumnManager(table, false);
// ColumnListener listener = new ColumnListener();
for (int i = 0; i < table.getColumnCount(); i++)
{
String column = table.getColumnName(i);
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.setSelected( true );
checkBox.setActionCommand( column ); // added
checkBox.addActionListener( listener ); // added
buttons.add( checkBox );
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
Whatever your function does it only needs to know about the table it should act upon.
So try to restructure your code into a reusable class.
If you want to use Gilberts code, then you need to restructure the ColumnListener class into a separate reusable self contained class.
Finally you can also try my reusable class. Check out Table Column Manager for the class to download.
Whatever reusable class you decide to use, you will only need to change a single line of code from the above example (once your functionality is contained in a reusable class).
Note the static methods would not be part of the final class. They are only there so simplify testing and posting of an MRE in a single class file.
Hope this helps with future design considerations.

JTable not updating/refreshing when new model is set with data

Hey so I have a problem with my JTable where it is not updating the table when I set its model to a new one with data within it. I have checked and all the arrays have data values within them, coming from another class. The cData array has all the right strings and values. But it doesnt seem to update. Here is the code, I commented where I think it is going wrong:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class DetentionStats extends JPanel
{
private JLabel title, houseTitle;
private JPanel leftPanel, rightPanel, dormPanel, housePanel, dormButtonPanel, dormStatsPanel, ADormPanel, BDormPanel, CDormPanel, DDormPanel;
private JButton ADorm, BDorm, CDorm, DDorm, Update;
private JTable statsList, houseList;
private JScrollPane statsListScroll, houseListScroll;
private final int numberOfColumns = 4;
private String[] statsColumnNames = {"Name", "Reason"};
private String[] houseColumnNames = {"Name","Reason","Dorm","Completed"};
private ArrayList<Detention> completedDetentions;
private DefaultTableModel statsTable, updateCompleted, houseTable, aDormModel, bDormModel, cDormModel, dDormModel;
public DetentionStats()
{
completedDetentions = new ArrayList<Detention>();
title = new JLabel("Statistics");
title.setFont(new Font("Arial", Font.BOLD, 24));
title.setHorizontalAlignment(JLabel.CENTER);
title.setVerticalAlignment(JLabel.CENTER);
setLayout(new BorderLayout());
ADorm = new JButton("A Dorm");
DormListener aDormListener = new DormListener();
ADorm.addActionListener(aDormListener);
aDormModel = new DefaultTableModel(statsColumnNames, 0);
ADormPanel = new JPanel();
ADormPanel.add(ADorm);
ADormPanel.setPreferredSize(new Dimension(100, 50));
ADormPanel.setBackground(Color.lightGray);
BDorm = new JButton("B Dorm");
DormListener bDormListener = new DormListener();
BDorm.addActionListener(bDormListener);
bDormModel = new DefaultTableModel(statsColumnNames, 0);
BDormPanel = new JPanel();
BDormPanel.add(BDorm);
BDormPanel.setPreferredSize(new Dimension(100, 50));
BDormPanel.setBackground(Color.lightGray);
CDorm = new JButton("C Dorm");
DormListener cDormListener = new DormListener();
CDorm.addActionListener(cDormListener);
cDormModel = new DefaultTableModel(statsColumnNames, 0);
CDormPanel = new JPanel();
CDormPanel.add(CDorm);
CDormPanel.setPreferredSize(new Dimension(100, 50));
CDormPanel.setBackground(Color.lightGray);
DDorm = new JButton("D Dorm");
DormListener dDormListener = new DormListener();
DDorm.addActionListener(dDormListener);
dDormModel = new DefaultTableModel(statsColumnNames, 0);
DDormPanel = new JPanel();
DDormPanel.add(DDorm);
DDormPanel.setPreferredSize(new Dimension(100, 50));
DDormPanel.setBackground(Color.lightGray);
dormButtonPanel = new JPanel();
dormButtonPanel.setLayout(new GridLayout(2,2));
dormButtonPanel.add(ADormPanel);
dormButtonPanel.add(BDormPanel);
dormButtonPanel.add(CDormPanel);
dormButtonPanel.add(DDormPanel);
dormButtonPanel.setBackground(Color.lightGray);
//--------------------------------------------------------------------------------------------------------------------------
statsTable = new DefaultTableModel(statsColumnNames, 0);
statsList = new JTable(statsTable);
statsListScroll = new JScrollPane(statsList);
statsList.setPreferredScrollableViewportSize(new Dimension(470,260));
dormStatsPanel = new JPanel();
dormStatsPanel.add(statsListScroll);
dormStatsPanel.setBackground(Color.lightGray);
dormPanel = new JPanel();
dormPanel.setLayout(new GridLayout(2,1));
dormPanel.add(dormButtonPanel);
dormPanel.add(dormStatsPanel);
//---------------------------------------------------------------------------------------------------------------------------
houseTitle = new JLabel("Completed Detentions");
houseTitle.setFont(new Font("Arial", Font.BOLD, 14));
houseTitle.setHorizontalAlignment(JLabel.CENTER);
houseTitle.setVerticalAlignment(JLabel.CENTER);
Update = new JButton("Update");
UpdateListener uListener = new UpdateListener();
Update.addActionListener(uListener);
houseTable = new DefaultTableModel(houseColumnNames, 0);
houseList = new JTable(houseTable);
houseListScroll = new JScrollPane(houseList);
houseList.setPreferredScrollableViewportSize(new Dimension(470,540));
housePanel = new JPanel();
housePanel.setLayout(new BorderLayout());
housePanel.setBackground(Color.lightGray);
housePanel.add(Update, BorderLayout.EAST);
housePanel.add(houseTitle, BorderLayout.CENTER);
housePanel.add(houseListScroll, BorderLayout.SOUTH);
leftPanel = new JPanel();
leftPanel.add(dormPanel);
leftPanel.setBackground(Color.lightGray);
rightPanel = new JPanel();
rightPanel.add(housePanel);
rightPanel.setBackground(Color.lightGray);
add(title, BorderLayout.NORTH);
add(leftPanel, BorderLayout.WEST);
add(rightPanel, BorderLayout.EAST);
setPreferredSize(new Dimension(1050,670));
setBackground(Color.lightGray);
setVisible(true);
}
public void completeDetention(Detention d)
{
completedDetentions.add(d);
updateCompletedDetentions();
dormSort();
}
private void dormSort()
{
Object[][] dData = new Object[completedDetentions.size()][numberOfColumns];
for(int i = 0; i < completedDetentions.size(); i++)
{
Detention d = completedDetentions.get(i);
if(d.getDorm() == Detention.Dorm.aDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
aDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.bDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
bDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.cDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
cDormModel = new DefaultTableModel(dData, statsColumnNames);
}
else if(d.getDorm() == Detention.Dorm.dDorm)
{
dData[i][0] = d.getName();
dData[i][0] = d.getReason();
dDormModel = new DefaultTableModel(dData, statsColumnNames);
}
}
}
private void updateCompletedDetentions()
{
Object[][] cData = new Object[completedDetentions.size()][numberOfColumns];
for(int i = 0; i < completedDetentions.size(); i++)
{
Detention d = completedDetentions.get(i);
//-------------------------------------------
cData[i][0] = d.getName();
//-------------------------------------------
cData[i][1] = d.getReason();
//-------------------------------------------
if(d.getDorm() == Detention.Dorm.aDorm)
{
cData[i][2] = "A Dorm";
}
else if(d.getDorm() == Detention.Dorm.bDorm)
{
cData[i][2] = "B Dorm";
}
else if(d.getDorm() == Detention.Dorm.cDorm)
{
cData[i][2] = "C Dorm";
}
else if(d.getDorm() == Detention.Dorm.dDorm)
{
cData[i][2] = "D Dorm";
}
else
{
cData[i][2] = "No Dorm Selected";
}
//-------------------------------------------
cData[i][3] = new Boolean(true);
}
//this is where it is going wrong (i think)
updateCompleted = new DefaultTableModel(cData, houseColumnNames);
houseList.setModel(updateCompleted);
}
private class UpdateListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
updateCompletedDetentions();
dormSort();
}
}
private class DormListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == ADorm)
{
statsList.setModel(aDormModel);
}
else if(source == BDorm)
{
statsList.setModel(bDormModel);
}
else if(source == CDorm)
{
statsList.setModel(cDormModel);
}
else if(source == DDorm)
{
statsList.setModel(dDormModel);
}
}
}
}
Runnable example:
public class Table extends JPanel
{
private DefaultTableModel updateTable;
private String[] columnNames = {"Name","Last Name","Location"};
private JTable table;
public Table()
{
defaultTable = new JTable(columnNames, 0);
table = new JTable(defaultTable);
}
public void update()
{
Object[][] data = new Object[array.size()][numberOfColumns];
for(int i = 0; i < array.size(); i++)
{
Detention c = detentionArray.get(i)
data[i][0] = c.getFirstName();
data[i][1] = c.getLastName();
data[i][2] = c.getLocation();
}
updateTable = new DefaultTableModel(data, columnNames);
table.setModel(updateTable);
}
}
You might need to use this as last line in updateCompletedDetentions() method.
fireTableDataChanged();

How to use ActionListener in ComboBox

package mainpanel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class MainPanel extends JFrame implements ActionListener {
String[] deck = null;
String[] discard = null;
Player p1;
Player p2;
Player p3;
public String[] playerList = new String[3];
JPanel panes = new JPanel();
JPanel playerStatPane = new JPanel();
public MainPanel() throws FileNotFoundException {
File masterList = new File("H:/mainPanel/masterList.txt");
File deckFile = new File("H:/mainPanel/deck.txt");
File discardFile = new File("H:/mainPanel/discard.txt");
File player1 = new File("H:/mainPanel/Chip.txt");
File player2 = new File("H:/mainPanel/Dale.txt");
File player3 = new File("H:/mainPanel/Caleb.txt");
deck = extractCards(deckFile);
if (deck.length == 0) {
deck = randomCards(extractCards(masterList));
}
discard = extractCards(discardFile);
p1 = new Player(player1);
p2 = new Player(player2);
p3 = new Player(player3);
setTitle("Bang!");
getContentPane().add(panes);
JLabel label1 = new JLabel();
playerList[0] = p1.name;
playerList[1] = p2.name;
playerList[2] = p3.name;
JComboBox comboBox = new JComboBox(playerList);
panes.add(comboBox);
comboBox.setSelectedIndex(2);
comboBox.addActionListener(this);
playerStatPane = createStats(p1);
panes.add(playerStatPane);
}
public static void main(String[] args) throws FileNotFoundException {
MainPanel mainScreen = new MainPanel();
mainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainScreen.pack();
mainScreen.setVisible(true);
}
/**public static String[] randomCards(String[] unshuffledCards) {
int[] tempInts = randomInts(unshuffledCards.length);
String[] shuffledCards = new String[unshuffledCards.length];
for (int i = 0; i < tempInts.length; i++) {
shuffledCards[i] = unshuffledCards[tempInts[i] - 1];
}
return shuffledCards;
}
public static int[] randomInts(int x) {
Random numGen = new Random();
int index = 0;
boolean repeat = false;
int[] numberList = new int[x];
numberList[numberList.length - 1] = 0;
while (numberList[numberList.length - 1] == 0) {
int newInt = numGen.nextInt(x) + 1;
for (int i = 0; i < numberList.length; i++) {
if (newInt == numberList[i]) {
repeat = true;
}
}
if (repeat == false) {
numberList[index] = newInt;
index++;
}
repeat = false;
}
return numberList;
}
public String[] extractCards(File a) throws FileNotFoundException {
ArrayList < String > cardsInHand = new ArrayList < String > ();
Scanner scanner = new Scanner(a);
while (scanner.hasNextLine()) {
cardsInHand.add(scanner.nextLine());
}
return cardsInHand.toArray(new String[cardsInHand.size()]);
}
public void draw(Player a) {
a.addCard(deck[0]);
if (deck.length == 1) {
deck = discard;
discard = new String[0];
} else {
String[] tempDeck = deck;
deck = new String[deck.length - 1];
for (int i = 1; i < deck.length; i++) {
deck[i - 1] = tempDeck[i];
}
}
}*/
public JPanel createStats(Player a) {
JPanel stat = new JPanel(new FlowLayout());
JComboBox comboBox = new JComboBox(a.cardsInHand);
JLabel label1 = new JLabel("Select card:");
JButton discardButton = new JButton("discard");
JButton drawButton = new JButton("draw");
stat.add(label1);
stat.add(comboBox);
stat.add(drawButton);
stat.add(discardButton);
return stat;
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String name = (String) cb.getSelectedItem();
if (name == "Chip") {
playerStatPane = createStats(p1);
} else if (name == "Dale") {
playerStatPane = createStats(p2);
} else {
playerStatPane = createStats(p3);
}
}
}
Errr, I'm trying to use ActionListener for the first time. I read a couple other question and answers, but I don't understand.
Help would be very appreciated. I'm trying to switch information of players by switching player name in the combo box.
Then I'm trying to get the discard and draw button to work. I have the discard and draw method already, I just need to learn the actionListener thing. Thanks!
You are reassiging the playerStatPane variable, but that does not mean the old value is replaced in panes. Try this:
public void actionPerformed(ActionEvent e) {
panes.remove(playerStatPane);
JComboBox cb = (JComboBox) e.getSource();
String name = (String) cb.getSelectedItem();
if (name.equals("Chip")) {
playerStatPane = createStats(p1);
} else if (name.equals("Dale")) {
playerStatPane = createStats(p2);
} else {
playerStatPane = createStats(p3);
}
panes.add(playerStatPane);
}

implementing actionListener with multiple classes?

I'm creating a program for my Java class and I'm having a hard time implementing a actionListener in conjunction to my main class.
This is an example of my main class, I am using other classes to create the components for the tabs. Where I'm running into trouble is when I try to implement action listeners in the other class. I keep running into errors regarding abstract classes. This is probably a simple solution, but I'm still fairly new to programming.
'
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import javax.swing.plaf.ColorUIResource;
public class TaikunStudyResource extends JFrame {
private static final int FRAME_WIDTH = 700;
private static final int FRAME_HIEGHT = 500;
private JPanel searchTab,addTab, grammerTab,testTab,homeTab;
public static void main(String[] args)throws UnsupportedOperationException {
TaikunStudyResource tsr = new TaikunStudyResource();
tsr.setVisible(true);
}
public TaikunStudyResource(){
//set basic features
setTitle("Taikun-Japanese Study Resource!");
setSize(FRAME_WIDTH,FRAME_HIEGHT);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(new Color(226,199,255));
addComponents(getContentPane());
}
public void addComponents(Container contentPane){
//add overlaying panel
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
contentPane.add(topPanel);
//create tabs
contentPane.add(createTabs());
}
public JTabbedPane createTabs(){
//UIManager.put("TabbedPane.contentAreaColor",ColorUIResource.getHSBColor(153,153,255));
//create tabs
JTabbedPane tabs = new JTabbedPane();
SearchPanel sp = new SearchPanel();
tabs.addTab("Search", sp);
addPanel ap = new addPanel();
tabs.addTab("Add",ap);
return tabs;
}
}
'
Here is a example of my my addPanel class
'
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
/**
*
* #author tyler.stanley.4937
*/
public abstract class addPanel extends JPanel{
//variables
private JPanel mainPanel, eastPanel,westPanel, checkboxPanel, radioPanel, typePanel, adjectivePanel, verbPanel, kanjiPanel;
private JLabel kanaKanjiLabel, romanjiLabel;
private JTextField kanaKanjiField, romanjiField,exampleInput, defInput, tagInput;
private JButton radicalButton, addDefButton, addExampleButton, addButton, addTagButton
,clearexButton,clearDefButton,clearTagButton;
private ButtonGroup commonGroup;
private JRadioButton[] commonButton;
private String[] commonTypeArray = {"very-common", "common", "Uncommon", "Out-dated"};
private JCheckBox[] typeCheckBox;
private String[] typeofWordArray = {"Noun", "Pronoun", "Verb","Adjective","Idiom"};
private JComboBox adjectiveTypeCombo;
private String[] adjectivetypeArray ={"Na","i"};
private JComboBox verbTypeCombo;
//private String[] verbTypetext = {"Suru","Kuru","da","desu","iku","-masu"};//these may not make it
private String[] verbTypeArray ={"-u","-ku","-gu","-su","-tsu","-nu","-bu","-mu","-ru"};
private JTextArea definitionArea, exampleArea, tagArea;
private List<String>definitionList, exampleList, tagList, radicalList,typeList;
private String kanjiKana,romanji;
private ActionListener a;
public static void main(String[] arg)throws UnsupportedOperationException{
}
public addPanel(){
setLayout(new BorderLayout());
//setBackground(Color.blue);
addComponents();
}
public void addComponents(){
fillSouthPanel();
fillEastPanel();
}
}
public void fillEastPanel(){
eastPanel = new JPanel(new BorderLayout());
//add definition pane
JPanel definitionPanel = new JPanel(new FlowLayout());
definitionPanel.setBorder(BorderFactory.createTitledBorder("Defintion"));
definitionArea = new JTextArea();
definitionArea.setColumns(22);
definitionArea.setRows(8);
definitionArea.setBorder(BorderFactory.createLineBorder(Color.black));
definitionArea.setEditable(false);
//add scroll pane
JScrollPane scrollPane = new JScrollPane(definitionArea);
scrollPane.setSize(200,135);
definitionPanel.add(scrollPane);
//add input and button
defInput = new JTextField(50);
definitionPanel.add(defInput);
addDefButton = new JButton("Add");
definitionPanel.add(addDefButton);
//addDefButton.addActionListener(al);
clearDefButton = new JButton("Clear");
definitionPanel.add(clearDefButton);
//clearDefButton.addActionListener(al);
//add tags
JPanel tagPanel = new JPanel(new FlowLayout());
tagPanel.setBorder(BorderFactory.createTitledBorder("Tags"));
tagArea = new JTextArea();
tagArea.setColumns(22);
tagArea.setRows(1);
tagArea.setBorder(BorderFactory.createLineBorder(Color.black));
tagArea.setEditable(false);
JScrollPane tagScrollPane = new JScrollPane(tagArea);
tagScrollPane.setSize(200,133);
tagPanel.add(tagScrollPane);
tagInput = new JTextField(22);
tagPanel.add(tagInput);
addTagButton = new JButton("Add Tag");
clearTagButton = new JButton("Clear Tag");
tagPanel.add(addTagButton);
tagPanel.add(clearTagButton);
//clearTagButton.addActionListener(al);
//addTagButton.addActionListener(al);
//examples
JPanel examplePanel = new JPanel(new FlowLayout());
examplePanel.setBorder(BorderFactory.createTitledBorder("example"));
exampleArea = new JTextArea();
exampleArea.setColumns(22);
exampleArea.setRows(8);
exampleArea.setBorder(BorderFactory.createLineBorder(Color.black));
exampleArea.setEditable(false);
JScrollPane exampleScrollPane = new JScrollPane(exampleArea);
exampleScrollPane.setSize(200,135);
examplePanel.add(exampleScrollPane);
exampleInput = new JTextField(30);
examplePanel.add(exampleInput);
addExampleButton = new JButton("Add");
examplePanel.add(addExampleButton);
//addExampleButton.addActionListener(this);
JButton clearExampleButton = new JButton("Clear");
examplePanel.add(clearExampleButton);
//clearExampleButton.addActionListener(this);
add(eastPanel, BorderLayout.EAST);
}
public void fillSouthPanel(){
JPanel southPanel = new JPanel(new FlowLayout());
addButton = new JButton("Add");
southPanel.add(addButton);
addButton.addActionListener(new Action() {
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
add(southPanel, BorderLayout.SOUTH);
}
public void addEntry(int buttonNumber){
switch(buttonNumber){
case 1:
tagList.add(tagInput.getText());
tagArea.append("/n"+tagInput.getText());
break;
case 2:
exampleList.add(exampleInput.getText());
exampleArea.append("/n"+exampleInput.getText());
break;
case 3:
definitionList.add(defInput.getText());
definitionArea.append("/n"+defInput.getText());
break;
}
}
public void clearEntry(int buttonNumber){
switch(buttonNumber){
case 0:
case 1:
case 2:
}
}
//public List radicalList(){
//RadicalFrame rf = new RadicalFrame();
//List<String>radicalList = rf.getRadicals();
//return
//}
public boolean getFieldEntries(){
boolean romaji,kanji, passable;
if(kanaKanjiField.getText()!= null){
kanjiKana = kanaKanjiField.getText();
kanji = true;
}else{
JOptionPane.showMessageDialog(null, "Please entry a vaild Japanese word");
kanaKanjiField.setText(null);
kanji = false;
}
//test if it's english
if(romanjiField.getText() !=null){
romanji = romanjiField.getText();
romaji = true;
}else{
JOptionPane.showMessageDialog(null, "please enter a vaild romaji entry");
romanjiField.setText(null);
romaji = false;
}
if(romaji == true && kanji == true){
passable =true;
}else{
passable = false;
}
return passable;
}
public boolean getTextArea(){
boolean defText, exText, tagText,passable;
if(tagList.size()!=0){
tagText = true;
}else{
JOptionPane.showMessageDialog(null, "Please enter tags to indentify the word");
tagText = false;
}
if(definitionList.size()!=0){
defText = true;
}else{
JOptionPane.showMessageDialog(null,"Please Enter defintion of the word");
defText = false;
}
if(exampleList.size()!=0){
exText = true;
}else{
JOptionPane.showMessageDialog(null, "Please Enter an Example of the word usage");
exText = false;
}
if(exText == true&&defText== true&& tagText == true){
passable = true;
}else{
passable = false;
}
return passable;
}
public void addWord() throws FileNotFoundException, IOException{
boolean vaild = getFieldEntries();
boolean vaild2 = getTextArea();
if(vaild == true&& vaild2 == true){
//Word word = new Word(KanjiKanaEntry, RomanjiEntry, CommonIndex, radicalList,typeentry, adjectiveIndex,VerbIndex);
File outFile = new File("dictionary.dat","UTF-8");
//Writer unicodeFileWriter = new OutputStreamWriter( new FileOutputStream("dictionary.dat)."UTF-8");//can't use writer
//fileOutputStream("dictionary.dat"),"UTF-8");
FileOutputStream outFileStream = new FileOutputStream(outFile,true);
ObjectOutputStream oos = new ObjectOutputStream(outFileStream);//append to a file
//oos.WriteObject(word);//store word
}
}
public void actionPermored(ActionEvent event) throws FileNotFoundException, IOException{
System.out.println("action");
//get even source
if(event.getSource() instanceof JButton){
JButton clickedButton = (JButton)event.getSource();
if(clickedButton == radicalButton){
//radicalList = radicalFrame();
}else if(clickedButton ==addButton){
addWord();
}else if(clickedButton == addTagButton){
addEntry(1);
}else if(clickedButton == addExampleButton){
addEntry(2);
}else if(clickedButton == addDefButton){
addEntry(3);
}else if(clickedButton == clearTagButton){
clearEntry(1);
}else if(clickedButton == clearDefButton){
clearEntry(0);
}else if(clickedButton == clearexButton){
clearEntry(2);
}
}
//get combo box entries
if(event.getSource() instanceof JComboBox){
JComboBox selectedComboBox = (JComboBox)event.getSource();
if(selectedComboBox == adjectiveTypeCombo){
int adjectiveform = selectedComboBox.getSelectedIndex();
}else if(selectedComboBox == verbTypeCombo){
int VerbForm = selectedComboBox.getSelectedIndex();
}
if(event.getSource() instanceof JCheckBox){
for(int i = 0;i<typeCheckBox.length;i++){
if(typeCheckBox[i].isSelected()){
typeList.add(typeCheckBox[i].getText()); //some how assign index numbers
}
}
}
}
}
}'
This is just a piece of code, so sorry if it seems a little jumbled, I'm trying to condense it as much as possible.
I've tried to create a internal class to handle the action listener, but I can't seem to get it to work. Also I know I can create actionlisteners for every button, but I would like to condense all the actionevents to one class or method.
The errors are due to unimplemented methods of the Action class anonymous instance.
Any instance of the Action interface requires that all the its methods be implemented. However using Action as an anonymous instance if neither practical or good practice. Rather create a single concrete instance of a class that extends AbstractAction and set the Action for for each component.
button.setAction(mySingleAction);
where
class SingleAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
// do stuff
}
}

JComboBox is throwing a NullPointerException when told to addItemListener()

I am getting a NullPointerException on line 27 (listOfWindTurbines.addItemListener(new dropDownListener());) when I try to run my program. Please Help!
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class PlannerMain {
JFrame frame;
JButton makeMap;
JPanel panel;
JLabel outcome;
JComboBox listOfWindTurbines;
String[] windTurbineSpace = new String[10];
Integer[] windTurbineLengths = new Integer[10];
Integer[] windTurbineWidths = new Integer[10];
JTextField lengthOfRoom, widthOfRoom, widthObjectNeeds, lengthObjectNeeds;
int lengthOfRoomInt, widthOfRoomInt, widthObjectNeedsInt, lengthObjectNeedsInt, largerObjectMeasurement, numberOfItems, numberOfItemsShort;
public static void main(String[] args){
PlannerMain p = new PlannerMain();
}
public PlannerMain(){
windTurbineLengths[0] = 1;
windTurbineWidths[0] = 1;
for(int i = 0;i<=9;i++){
int wNum = i + 1;
windTurbineSpace[i] = "Windturbine "+ wNum;
}
listOfWindTurbines.addItemListener(new dropDownListener());
frame = new JFrame("Minecraft Land Planner");
outcome = new JLabel();
panel = new JPanel();
makeMap = new JButton("Make Map");
lengthOfRoom = new JTextField("Length of Room");
widthOfRoom = new JTextField("Width of Room");
widthObjectNeeds = new JTextField("Width Object Needs");
lengthObjectNeeds = new JTextField("Length Object Needs");
listOfWindTurbines = new JComboBox(windTurbineSpace);
makeMap.addActionListener(new makeMapListener());
frame.setSize(580,550);
frame.add(panel);
panel.add(makeMap);
panel.add(lengthOfRoom);
panel.add(widthOfRoom);
panel.add(lengthObjectNeeds);
panel.add(widthObjectNeeds);
panel.add(listOfWindTurbines);
panel.add(outcome);
frame.setVisible(true);
}
class makeMapListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
lengthOfRoomInt = Integer.parseInt(lengthOfRoom.getText());
widthOfRoomInt = Integer.parseInt(widthOfRoom.getText());
lengthObjectNeedsInt = Integer.parseInt(lengthObjectNeeds.getText());
widthObjectNeedsInt = Integer.parseInt(widthObjectNeeds.getText());
if(lengthObjectNeedsInt<=widthObjectNeedsInt){
largerObjectMeasurement = widthObjectNeedsInt;
}
if(widthObjectNeedsInt<=lengthObjectNeedsInt){
largerObjectMeasurement = lengthObjectNeedsInt;
}
numberOfItems = (lengthOfRoomInt/lengthObjectNeedsInt)*(widthOfRoomInt/widthObjectNeedsInt);
outcome.setText(String.valueOf(numberOfItems));
lengthOfRoom.setSize(30, 20);
widthOfRoom.setSize(30, 20);
widthObjectNeeds.setSize(30, 10);
lengthObjectNeeds.setSize(100, 20);
}
}
class dropDownListener implements ItemListener{
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED){
lengthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
widthObjectNeeds.setText(Integer.toString(windTurbineLengths[listOfWindTurbines.getSelectedIndex()]));
}
}
}
}
You need to initialize the listOfWindTurbines variable, for example:
JComboBox listOfWindTurbines = new JComboBox();

Categories