Related
I have a JLabel array that contains many words. I am trying to get the first character of the words. In fact I am trying to get all the character, but if I see how to get the first, I will get the others.
I tried this
mport java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class WordSearchFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static final int COLS_IN_WORDLIST = 1;
private static final int FRAME_WIDTH = 640;
private static final int FRAME_HEIGHT = 480;
private JLabel[][] wordSearch;
private JLabel[] wordListLabels;
private JPanel wordListPanel;
private JPanel wordsearchPanel;
private JPanel rightSidePanel;
private JPanel leftSidePanel;
private JPanel searchButtonPanel;
private JButton searchButton;
private int numRows;
private int numCols;
private ActionListener searchButtonListener;
private ArrayList<String> wordList;
class SearchListener implements ActionListener {
private int x = 0;
public void actionPerformed(ActionEvent event) {
wordListLabels[0].setForeground(Color.BLACK);
if (x == 0) {
findword(x);
x++;
} else {
wordListLabels[x - 1].setForeground(Color.BLACK);
findword(x);
x++;
}
}
private void findword(int x) {
wordListLabels[x].setForeground(Color.RED);
findword2(x);
}
private void findword2(int x) {
for (int i = 0; i < 7; i++)
wordSearch[x + i][x].setForeground(Color.RED);
}
}
private void buildLeftSidePanel() throws WordSearchException, IOException {
leftSidePanel = new JPanel();
leftSidePanel.setLayout(new BorderLayout());
leftSidePanel.setBorder(new TitledBorder(new EtchedBorder(), "Word Search"));
wordsearchPanel = new JPanel();
wordsearchPanel.setLayout(new GridLayout(numRows, numCols));
leftSidePanel.add(wordsearchPanel, BorderLayout.CENTER);
this.getContentPane().add(leftSidePanel, BorderLayout.CENTER);
}
private void initGridFromFile(String wordSearchFilename) throws WordSearchException, IOException {
this.numRows = 0;
this.numCols = 0;
BufferedReader reader = new BufferedReader(new FileReader(wordSearchFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (this.numCols == 0) {
this.numCols = tokenizer.countTokens();
} else {
if (tokenizer.countTokens() != this.numCols) {
throw new WordSearchException("Invalid number of columns in word search");
}
}
line = reader.readLine();
this.numRows++;
}
reader.close();
this.wordSearch = new JLabel[numRows][numCols];
}
protected void loadGridFromFile(String wordSearchFilename) throws IOException {
int row = 0;
BufferedReader reader = new BufferedReader(new FileReader(wordSearchFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
int col = 0;
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
wordSearch[row][col] = new JLabel(tok);
wordSearch[row][col].setForeground(Color.BLACK);
wordSearch[row][col].setHorizontalAlignment(SwingConstants.CENTER);
wordsearchPanel.add(wordSearch[row][col]);
col++;
}
line = reader.readLine();
row++;
}
reader.close();
}
private void buildRightSidePanel() {
rightSidePanel = new JPanel();
rightSidePanel.setBorder(new TitledBorder(new EtchedBorder(), "Word List"));
rightSidePanel.setLayout(new BorderLayout());
wordListLabels = new JLabel[wordList.size()];
wordListPanel = new JPanel();
wordListPanel.setLayout(new GridLayout(wordList.size(), 1));
for (int i = 0; i < this.wordList.size(); i++) {
// If the line below won't compile in Java 1.4.2, make it
// String word = (String)this.wordList.get(i);
String word = this.wordList.get(i);
wordListLabels[i] = new JLabel(word);
wordListLabels[i].setForeground(Color.BLUE);
wordListLabels[i].setHorizontalAlignment(SwingConstants.CENTER);
wordListPanel.add(wordListLabels[i]);
}
rightSidePanel.add(wordListPanel, BorderLayout.CENTER);
searchButton = new JButton("Search");
searchButtonListener = new SearchListener();
searchButton.addActionListener(searchButtonListener);
searchButtonPanel = new JPanel();
searchButtonPanel.add(searchButton);
rightSidePanel.add(searchButtonPanel, BorderLayout.SOUTH);
this.getContentPane().add(rightSidePanel, BorderLayout.EAST);
}
private void loadWordList(String wordListFilename) throws WordSearchException, IOException {
int row = 0;
wordList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(wordListFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() != COLS_IN_WORDLIST) {
throw new WordSearchException("Error: only one word per line allowed in the word list");
}
String tok = tokenizer.nextToken();
wordList.add(tok);
line = reader.readLine();
row++;
}
reader.close();
}
public WordSearchFrame(String wordSearchFilename, String wordListFilename) throws IOException, WordSearchException {
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.getContentPane().setLayout(new BorderLayout());
this.initGridFromFile(wordSearchFilename);
buildLeftSidePanel();
this.loadGridFromFile(wordSearchFilename);
loadWordList(wordListFilename);
buildRightSidePanel();
}
public WordSearchFrame(String[][] wordSearch, String[] wordList) throws IOException, WordSearchException {
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.getContentPane().setLayout(new BorderLayout());
this.numRows = wordSearch.length;
this.numCols = wordSearch[0].length;
this.wordSearch = new JLabel[this.numRows][this.numCols];
buildLeftSidePanel();
for (int row = 0; row < this.numRows; row++) {
for (int col = 0; col < this.numCols; col++) {
this.wordSearch[row][col] = new JLabel(wordSearch[row][col]);
this.wordSearch[row][col].setForeground(Color.BLACK);
this.wordSearch[row][col].setHorizontalAlignment(SwingConstants.CENTER);
this.wordsearchPanel.add(this.wordSearch[row][col]);
}
}
this.wordList = new ArrayList<String>();
for (int i = 0; i < wordList.length; i++) {
this.wordList.add(wordList[i]);
}
buildRightSidePanel();
}
public static void main(String[] args) {
try {
if (args.length != 2) {
System.out.println("Command line arguments: <word search file> <word list>");
} else {
WordSearchFrame frame = new WordSearchFrame(args[0], args[1]);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I have all the next:
the panel on the left hand side, which consists of the word search
the contents of the word search into the JLabels of the word search grid in the GUI
Now I just need the jlabe[index].charAt(0). That does not work.
I tried jlabe[index].getText().charAt(0). That does not work.
What I tried above works fine, but not for what I want it.
Also the other class
public class WordSearchException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WordSearchException() {
}
public WordSearchException(String reason) {
super(reason);
}
}
The best way to do that is to gettext().charat(index)
These Threee Classes are what I got so far.
package ex;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
class ATable extends AbstractTableModel {
private String title[] = { "Name", "Size", "Type", "Modified Date" };
private String val[][] = new String[1][4];
public void setValueArr(int i) {
val = new String[i][4];
}
public int getRowCount() {
return val.length;
}
public int getColumnCount() {
return val[0].length;
}
public String getColumnName(int column) {
return title[column];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == 0)
return true;
else
return false;
}
public Object getValueAt(int row, int column) {
return val[row][column];
}
public void setValueAt(String aValue, int rowIndex, int columnIndex) {
val[rowIndex][columnIndex] = aValue;
}
}
package ex;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
class FileViewer implements TreeWillExpandListener, TreeSelectionListener {
private JFrame frame = new JFrame("Explorer");
private Container con = null;
private JSplitPane pMain = new JSplitPane();
private JScrollPane pLeft = null;
private JPanel pRight = new JPanel(new BorderLayout());
private DefaultMutableTreeNode root = new DefaultMutableTreeNode("My Computer");
private JTree tree;
private JPanel pNorth = new JPanel();
private JPanel northText = new JPanel();
private JLabel northLabel0 = new JLabel("Path");
private JTextField pathText = new JTextField();
private JLabel northLabel1 = new JLabel("Search");
private JTextField searchText = new JTextField();
private Dimension dim, dim1;
private int xpos, ypos;
FileViewer() {
init();
start();
frame.setSize(800, 600);
dim = Toolkit.getDefaultToolkit().getScreenSize();
dim1 = frame.getSize();
xpos = (int) (dim.getWidth() / 2 - dim1.getWidth() / 2);
ypos = (int) (dim.getHeight() / 2 - dim1.getHeight() / 2);
frame.setLocation(xpos, ypos);
frame.setVisible(true);
}
void init() {
pMain.setResizeWeight(1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con = frame.getContentPane();
con.setLayout(new BorderLayout());
pathText.setPreferredSize(new Dimension(300, 20));
searchText.setPreferredSize(new Dimension(300, 20));
northText.add(northLabel0);
northText.add(pathText);
northText.add(northLabel1);
northText.add(searchText);
pNorth.add(northText);
con.add(pNorth, "North");
File file = new File("C:/");
File list[] = file.listFiles();
DefaultMutableTreeNode temp;
for (int i = 0; i < list.length; ++i) {
temp = new DefaultMutableTreeNode(list[i].getPath());
temp.add(new DefaultMutableTreeNode("None"));
root.add(temp);
}
tree = new JTree(root);
pLeft = new JScrollPane(tree);
pMain.setDividerLocation(150);
pMain.setLeftComponent(pLeft);
pMain.setRightComponent(pRight);
con.add(pMain);
}
void start() {
tree.addTreeWillExpandListener(this);
tree.addTreeSelectionListener(this);
}
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
new FileViewer();
}
String getPath(TreeExpansionEvent e) {
StringBuffer path = new StringBuffer();
TreePath temp = e.getPath();
Object list[] = temp.getPath();
for (int i = 0; i < list.length; ++i) {
if (i > 0) {
path.append(((DefaultMutableTreeNode) list[i]).getUserObject() + "\\");
}
}
return path.toString();
}
String getPath(TreeSelectionEvent e) {
StringBuffer path = new StringBuffer();
TreePath temp = e.getPath();
Object list[] = temp.getPath();
for (int i = 0; i < list.length; ++i) {
if (i > 0) {
path.append(((DefaultMutableTreeNode) list[i]).getUserObject() + "\\");
}
}
return path.toString();
}
public void getSearch(){
}
public void treeWillCollapse(TreeExpansionEvent event) {
}
public void treeWillExpand(TreeExpansionEvent e) {
if (((String) ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject()).equals("My Computer")) {
} else {
try {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
File tempFile = new File(getPath(e));
File list[] = tempFile.listFiles();
DefaultMutableTreeNode tempChild;
for (File temp : list) {
if (temp.isDirectory() && !temp.isHidden()) {
tempChild = new DefaultMutableTreeNode(temp.getName());
if (true) {
File inFile = new File(getPath(e) + temp.getName() + "\\");
File inFileList[] = inFile.listFiles();
for (File inTemp : inFileList) {
if (inTemp.isDirectory() && !inTemp.isHidden()) {
tempChild.add(new DefaultMutableTreeNode("None"));
break;
}
}
}
parent.add(tempChild);
}
}
parent.remove(0);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Can't Find a File");
}
}
}
public void valueChanged(TreeSelectionEvent e) {
if (((String) ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject()).equals("My Computer")) {
pathText.setText("My Computer");
} else {
try {
pathText.setText(getPath(e));
pRight = new FView(getPath(e), null).getTablePanel();
pMain.setRightComponent(pRight);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Can't Find a File");
}
}
}
}
package ex;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
class FView {
private ATable at = new ATable();
private JTable jt = new JTable(at);
private JPanel pMain = new JPanel(new BorderLayout());
private JScrollPane pCenter = new JScrollPane(jt);
private File file;
private File list[];
private long size = 0, time = 0;
FView(String str, String searchKey) {
init();
if (searchKey!=null){
search(str, searchKey);
}
start(str);
}
void init() {
pMain.add(pCenter, "Center");
}
void start(String strPath) {
file = new File(strPath);
list = file.listFiles();
at.setValueArr(list.length);
for (int i = 0; i < list.length; ++i) {
size = list[i].length();
time = list[i].lastModified();
for (int j = 0; j < 4; ++j) {
switch (j) {
case 0:
at.setValueAt(list[i].getName(), i, j);
break;
case 1:
if (list[i].isFile())
at.setValueAt(Long.toString((long) Math.round(size / 1024.0)) + "Kb", i, j);
break;
case 2:
if (list[i].isFile()) {
at.setValueAt(getLastName(list[i].getName()), i, j);
} else
at.setValueAt("νμΌν΄λ", i, j);
break;
case 3:
at.setValueAt(getFormatString(time), i, j);
break;
}
}
}
jt.repaint();
pCenter.setVisible(false);
pCenter.setVisible(true);
}
void search(String strPath, String searchKey){
file = new File(strPath);
list = file.listFiles();
at.setValueArr(list.length);
for (int i = 0; i < list.length; ++i) {
size = list[i].length();
time = list[i].lastModified();
for (int j = 0; j < 4; ++j) {
switch (j) {
case 0:
at.setValueAt("zzzzzzzzz", i, j);
break;
case 1:
if (list[i].isFile())
at.setValueAt(Long.toString((long) Math.round(size / 1024.0)) + "Kb", i, j);
break;
case 2:
if (list[i].isFile()) {
at.setValueAt(getLastName(list[i].getName()), i, j);
} else
at.setValueAt("File Folder", i, j);
break;
case 3:
at.setValueAt(getFormatString(time), i, j);
break;
}
}
}
jt.repaint();
pCenter.setVisible(false);
pCenter.setVisible(true);
}
String getLastName(String name) {
int pos = name.lastIndexOf(".");
String result = name.substring(pos + 1, name.length());
return result;
}
String getFormatString(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
Date d = new Date(time);
String temp = sdf.format(d);
return temp;
}
JPanel getTablePanel() {
return pMain;
}
}
What I want is 'searching a file' function on the right side of path textfield.
The location of search textfield is fine now, but i have no clue how to add function on it.
It should show a file that contains a word which the user type on search text field. (The file that is in current directory ONLY. Don't need to show a file in subdirectory)
And when the search textfield is blank, it should show all the files in current directory as usual.
Please help me on this.
con.add(pNorth, "North");
Don't use magic strings. The API will have variables you can use:
con.add(pNorth, BorderLayout.NORTH);
It should show a file that contains a word which the user type on search text field
You need to add a DocumentListener to the Document of the JTextField. An event will be fired whenever text is added or removed and you can then do your search.
Read the section from the Swing tutorial on How to Write a DocumentListener for more information and examples.
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.
So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Assignment8 extends JApplet implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_DIGITS = 30;
private JTextArea operand, result;
private double answer = 0.0;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;
/** public static void main(String[] args)
{
Assignment8 aCalculator = new Assignment8( );
aCalculator.setVisible(true);
}**/
public void init( )
{
setup_layout();
}
private void setup_layout() {
setSize(WIDTH, HEIGHT);
JPanel MainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel calcPanel = new JPanel();
JPanel textPanel = new JPanel ();
buttonPanel.setLayout(new GridLayout(3, 4));
calcPanel.setLayout(new GridLayout(3, 3));
textPanel.setLayout(new FlowLayout());
MainPanel.setLayout(new BorderLayout());
MainPanel.setBackground(Color.red);
operand = new JTextArea();
result = new JTextArea();
operand.setEditable(false);
result.setEditable(false);
textPanel.add(operand);
textPanel.add(result);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
addB = new JButton("+");
resetB = new JButton("Reset");
clearB = new JButton("Clear");
sqrtB = new JButton("Sqrt");
absB = new JButton("Abs");
expB = new JButton("Exp");
sevenB.addActionListener(this);
eightB.addActionListener(this);
nineB.addActionListener(this);
divideB.addActionListener(this);
fourB.addActionListener(this);
fiveB.addActionListener(this);
sixB.addActionListener(this);
multiplyB.addActionListener(this);
oneB.addActionListener(this);
twoB.addActionListener(this);
threeB.addActionListener(this);
subtractB.addActionListener(this);
zeroB.addActionListener(this);
dotB.addActionListener(this);
addB.addActionListener(this);
resetB.addActionListener(this);
clearB.addActionListener(this);
absB.addActionListener(this);
expB.addActionListener(this);
sqrtB.addActionListener(this);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
calcPanel.add(subtractB);
calcPanel.add(multiplyB);
calcPanel.add(divideB);
calcPanel.add(sqrtB);
calcPanel.add(absB);
calcPanel.add(expB);
calcPanel.add(addB);
calcPanel.add(resetB);
calcPanel.add(clearB);
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
assumingCorrectNumberFormats(e);
}
catch (NumberFormatException e2)
{
result.setText("Error: Reenter Number.");
}
catch (DivideByZeroException e1) {
result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
}
}
//Throws NumberFormatException.
public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("1"))
{
int num = 1;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("2"))
{
int num = 2;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("3"))
{
int num = 3;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("4"))
{
int num = 4;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("5"))
{
int num = 5;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("6"))
{
int num = 6;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("7"))
{
int num = 7;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("8"))
{
int num = 8;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("9"))
{
int num = 9;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("0"))
{
int num = 0;
String text = operand.getText();
//double check = stringToDouble(text);
if(text.isEmpty()||text.contains(".")) {
operand.append(Integer.toString(num));
}
}
else if (actionCommand.equals("."))
{
String text = operand.getText();
if(!text.contains(".")) {
operand.append(".");
}
}
else if (actionCommand.equals("+"))
{
answer = answer + stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("-"))
{
answer = answer - stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("*"))
{
answer = answer * stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("/"))
{
double check = stringToDouble(operand.getText());
if(check >= -1.0e-10 && check <= 1.0e-10 ) {
throw new DivideByZeroException();
}
else {
answer = answer / stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Sqrt"))
{
double check = stringToDouble(result.getText());
if(check < 0 ) {
throw new NumberFormatException();
}
else {
answer = Math.sqrt(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Abs"))
{
answer = Math.abs(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Exp"))
{
answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Reset"))
{
answer = 0.0;
result.setText("");
operand.setText("");
}
else if (actionCommand.equals("Clear"))
{
operand.setText("");
}
else
result.setText("Unexpected error.");
}
//Throws NumberFormatException.
private static double stringToDouble(String stringObject)
{
return Double.parseDouble(stringObject.trim( ));
}
//Divide by Zero Exception Class
public class DivideByZeroException extends Exception {
DivideByZeroException() {
}
}
}
You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);
Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
to:
MainPanel.add(buttonPanel, BorderLayout.CENTER);
MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
MainPanel.add(textPanel, BorderLayout.PAGE_START);
Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
throws DivideByZeroException {
String actionCommand = e.getActionCommand();
String numbers = "1234567890";
if (numbers.contains(actionCommand)) {
operand.append(actionCommand);
// if you need to work with it as a number
int num = Integer.parseInt(actionCommand);
}
Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Ok this is my code. Now I have it set up so far to display the correct pattern for 3 seconds, go to an input screen for the user to input, when the user clicks the screen 6 times it takes the pattern the user inputs and stores it into the array input, then checks if the input array and pattern array are the same. Now the problem is that when it checks for the arrays to be the same that it works correctly for the percent pattern but it doesn't work correctly for any other pattern.
How can I compare the two 2D arrays?
package game;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InputGame implements Properties,Listeners{
public static JFrame gf = new JFrame();
public static JButton a1,a2,a3,a4;
public static JButton b1,b2,b3,b4;
public static JButton c1,c2,c3,c4;
public static JButton d1,d2,d3,d4;
public static int height = 800;
public static int width = 600;
public static int gsize = 4;
public static int order =1;
public static Dimension size = new Dimension(height,width);
public static menu Menu = new menu();
public static GridLayout Ggrid = new GridLayout(gsize,gsize);
public static int numOfClicks =0;
public static int numCorrect=0;
public static int[][] input = new int[][]{
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}
};
//public static Thread d;
public static void clear()
{
gf.dispose();
}
public static void setup() {
gf.dispose();
gf = new JFrame();
gf.setLocation(300,100);
gf.setSize(size);
gf.setResizable(false);
gf.setLayout(Ggrid);
gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PatternGame.clear();
blank();
gf.setVisible(true);
System.out.print(numOfClicks);
}
public static void blank()
{
{
a1 = new JButton("");
a2 = new JButton("");
a3 = new JButton("");
a4 = new JButton("");
a1.addActionListener(new input());
a2.addActionListener(new input());
a3.addActionListener(new input());
a4.addActionListener(new input());
gf.add(a1);
gf.add(a2);
gf.add(a3);
gf.add(a4);
}
{
b1 = new JButton("");
b2 = new JButton("");
b3 = new JButton("");
b4 = new JButton("");
b1.addActionListener(new input());
b2.addActionListener(new input());
b3.addActionListener(new input());
b4.addActionListener(new input());
gf.add(b1);
gf.add(b2);
gf.add(b3);
gf.add(b4);
}
{
c1 = new JButton("");
c2 = new JButton("");
c3 = new JButton("");
c4 = new JButton("");
c1.addActionListener(new input());
c2.addActionListener(new input());
c3.addActionListener(new input());
c4.addActionListener(new input());
gf.add(c1);
gf.add(c2);
gf.add(c3);
gf.add(c4);
}
{
d1 = new JButton("");
d2 = new JButton("");
d3 = new JButton("");
d4 = new JButton("");
d1.addActionListener(new input());
d2.addActionListener(new input());
d3.addActionListener(new input());
d4.addActionListener(new input());
gf.add(d1);
gf.add(d2);
gf.add(d3);
gf.add(d4);
}
}
public static void input()
{
{
String x = a1.getText();
if (x.equals("X"))
{
input[0][0] = 1;
}
x = a2.getText();
if (x.equals("X"))
{
input[0][1] = 1;
}
x = a3.getText();
if (x.equals("X"))
{
input[0][2] = 1;
}
x = a4.getText();
if (x.equals("X"))
{
input[0][3] = 1;
}
}
{
String x = b1.getText();
if (x.equals("X"))
{
input[1][0] = 1;
}
x = b2.getText();
if (x.equals("X"))
{
input[1][1] = 1;
}
x = b3.getText();
if (x.equals("X"))
{
input[1][2] = 1;
}
x = b4.getText();
if (x.equals("X"))
{
input[1][3] = 1;
}
}
{
String x = c1.getText();
if (x.equals("X"))
{
input[2][0] = 1;
}
x = c2.getText();
if (x.equals("X"))
{
input[2][1] = 1;
}
x = c3.getText();
if (x.equals("X"))
{
input[2][2] = 1;
}
x = c4.getText();
if (x.equals("X"))
{
input[2][3] = 1;
}
}
{
String x = d1.getText();
if (x.equals("X"))
{
input[3][0] = 1;
}
x = d2.getText();
if (x.equals("X"))
{
input[3][1] = 1;
}
x = d3.getText();
if (x.equals("X"))
{
input[3][2] = 1;
}
x = d4.getText();
if (x.equals("X"))
{
input[3][3] = 1;
}
}
}
public static boolean checkCorrect()
{
input();
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (order == 1)
{
if (handlebars[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 2)
{
if (ys[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 3)
{
if (spaceShip[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 4)
{
if (flock[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 5)
{
if (percent[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 6)
{
if (square[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
}
}
System.out.println(numCorrect);
for (int a =0;a<4;a++)
{
System.out.println();
for(int b=0;b<4;b++)
{
System.out.print(input[a][b]);
}
}
for (int a =0;a<4;a++)
{
System.out.println();
for(int b=0;b<4;b++)
{
System.out.print(ys[a][b]);
}
}
if (numCorrect == 16)
{
return true;
}
else
{
return false;
}
}
}
package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public interface Listeners
{
static PatternGame game = new PatternGame();
InputGame game2 = new InputGame();
static class inst implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("inst".equals(e.getActionCommand()))
{
}
}
}
static class play implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("play".equals(e.getActionCommand()))
{
menu.mf.dispose();
PatternGame.gameStart();
}
}
}
static class exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("exit".equals(e.getActionCommand()))
{
System.exit(0);
}
}
}
static class input implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (InputGame.numOfClicks !=1)
{
JButton x = (JButton) e.getSource();
x.setText("X");
InputGame.numOfClicks--;
}
else if (InputGame.numOfClicks ==1)
{
JButton x = (JButton) e.getSource();
x.setText("X");
InputGame.numOfClicks--;
if (InputGame.checkCorrect())
{
int yesno = JOptionPane.showConfirmDialog(null, "<html> Correct!" +"<br>Would you like another pattern?");
if (yesno == JOptionPane.YES_OPTION)
{
PatternGame.order++;
InputGame.clear();
PatternGame.gameStart();
}
else
{
InputGame.clear();
menu.start();
}
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect!");
InputGame.clear();
menu.start();
}
}
}
}
}
package game;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PatternGame implements Properties
{
public static JFrame df = new JFrame();
public static int height = 800;
public static int width = 600;
public static int gsize = 4;
public static int order =1;
public static Dimension size = new Dimension(height,width);
public static menu Menu = new menu();
public static GridLayout Ggrid = new GridLayout(gsize,gsize);
public static void DisplayPat()
{
df.dispose();
df = new JFrame();
df.setLocation(300,100);
df.setSize(size);
df.setResizable(false);
df.setLayout(Ggrid);
df.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
df.setVisible(true);
}
public static boolean StayIn = true;
public static InputGame game = new InputGame();
public static int flag =0;
public static void clear()
{
df.dispose();
}
public static void gameStart()
{
DisplayPat();
getpattern();
schedule(3);
//notifyAll();
}
public static void blank()
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
JButton button = new JButton(" ");
df.add(button);
}
}
}
public static void getpattern()
{
InputGame.numOfClicks=0;
if (order == 1)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (handlebars[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
flag =1;
}
}
}
if (order == 2)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (ys[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
}
if (order == 3)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (spaceShip[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
} if (order == 4)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (flock[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
} if (order == 5)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (percent[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
}
if (order == 6)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (square[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
}
df.setVisible(true);
}
public static Timer timer = new Timer(); //timer object
public static void schedule(int seconds) {
timer.schedule(new ScheduleTask(), seconds*1000);
}
static class ScheduleTask extends TimerTask {
public void run() {
InputGame.setup();
// timer.cancel(); //Terminate Timer thread
}
}
}
package game;
public interface Properties
{
int[][] percent = new int[][]{
{1,0,0,1},
{0,0,1,0},
{0,1,0,0},
{1,0,0,1}
};
int[][] spaceShip = new int[][]{
{0,1,1,0},
{0,0,0,0},
{0,1,1,0},
{1,0,0,1}
};
int[][] flock = new int[][]{
{0,0,0,0},
{1,0,1,0},
{0,1,0,1},
{1,0,1,0}
};
int[][] ys = new int[][]{
{0,0,1,0},
{1,0,1,0},
{0,1,0,1},
{0,1,0,0}
};
int[][] handlebars = new int[][]{
{1,0,0,0},
{0,1,1,0},
{0,1,1,0},
{0,0,0,1}
};
int[][] square = new int[][]{
{0,1,0,1},
{1,0,0,0},
{0,0,0,1},
{1,0,1,0}
};
}
Try using:
Arrays.equals(); // <---- One Dimensional Arrays
or
ArrayUtils.isEquals(); // <---- Multi Dimensional Arrays
These methods will compare the actual contents of the two arrays (not if they are the same reference or same object) and you wont have to step through each element individually.
Hope it helps!