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.
Related
So I am trying to highlight the keywords in java,which I have stored in a text file, as the user opens a .java file or writes to .java file. I think I know how to tell if the file is of the right type. However, I do not know how to change the color of certain keywords. If anyone could help out that would be great because right now it's pretty confusing. I was wondering if I could use my replace function somehow. I have tried to go about trying to do this with the few methods I have, yet it's still not clear. I have taken out he majority of the methods and listeners, just know they are there but kept out to make it easier to read.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import java.util.Scanner;
import java.io.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
import java.net.URI;
import java.util.*;
public class MyTextEditor extends JFrame implements ActionListener
{
private JPanel panel = new JPanel(new BorderLayout());
private JTextArea textArea = new JTextArea(0,0);
private static final Color TA_BKGRD_CL = Color.BLACK;
private static final Color TA_FRGRD_CL = Color.GREEN;
private static final Color TA_CARET_CL = Color.WHITE;
private JScrollPane scrollPane;
private MenuBar menuBar = new MenuBar();
public MyTextEditor()
{
this.setSize(750,800);
this.setTitle("Zenith");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setFont(new Font("Consolas", Font.BOLD, 14));
textArea.setForeground(TA_FRGRD_CL);
textArea.setBackground(TA_BKGRD_CL);
textArea.setCaretColor(TA_CARET_CL);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVisible(true);
textArea.add(scrollPane,BorderLayout.EAST);
final LineNumberingTextArea lineNTA = new LineNumberingTextArea(textArea);
DocumentListener documentListen = new DocumentListener()
{
public void insertUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void removeUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void changedUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
};
textArea.getDocument().addDocumentListener(documentListen);
// Line numbers
lineNTA.setBackground(Color.BLACK);
lineNTA.setForeground(Color.WHITE);
lineNTA.setFont(new Font("Consolas", Font.BOLD, 13));
lineNTA.setEditable(false);
lineNTA.setVisible(true);
textArea.add(lineNTA);
scrollPane.setVisible(true);
scrollPane.add(textArea);
getContentPane().add(scrollPane);
}
public void findKeyWords(String ext)
{
ArrayList<String> wordsInTA = new ArrayList<String>();
int index = 0;
if(ext == "java")
{
for(String line : textArea.getText().split(" "))
{
wordsInTA.add(line);
index++;
}
try
{
while(index>0)
{
String temp = wordsInTA.get(index);
boolean isKeyWord = binarySearch(temp);
if(isKeyWord)
{
//Code that has not yet been made
}
index--;
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
private ArrayList<String> loadJavaWords() throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
Scanner scan = new Scanner(new File("JavaKeyWords.txt"));
while(scan.hasNext())
{
javaWords.add(scan.next());
}
scan.close();
return javaWords;
}
private boolean binarySearch(String word) throws FileNotFoundException
{
ArrayList<String> javaWords = loadJavaWords();
int min = 0;
int max = javaWords.size()-1;
while(min <= max)
{
int index = (max + min)/2;
String guess = javaWords.get(index);
int result = word.compareTo(guess);
if(result == 0)
{
return true;
}
else if(result > 0)
{
min = index +1;
}
else if(result < 0)
{
max = index -1;
}
}
return false;
}
public void replace()
{
String wordToSearch = JOptionPane.showInputDialog(null, "Word to replace:");
String wordToReplace = JOptionPane.showInputDialog(null, "Replacement word:");
int m;
int total = 0;
int wordLength = wordToSearch.length();
for (String line : textArea.getText().split("\\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
total += line.length() + 1;
continue;
}
String newLine = line.replaceAll(wordToSearch, wordToReplace);
textArea.replaceRange(newLine, total, total + line.length());
total += newLine.length() + 1;
}
}
public static void main(String args[])
{
MyTextEditor textEditor = new MyTextEditor();
textEditor.setVisible(true);
}
}
My program generates random numbers from 0 to 12 but if the result is 12 it would set dash as the text of JLabel, instead of the number generated.
Now, I wanted to sort my JPanel in ascending order based on the JLabel contents. In case of similarities in numbers, the black JPanels are placed on the left. It works fine except when there are dashes included, in which it doesn't sort properly. I would like to insert the JPanels containing dashes anywhere but it's not working as expected.
Screencaps from a shorter version of my program:
Pure numbers:
Dash included:
Here's the shorter version of my code (using the logic of integer sorting):
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Comparator;
public class SortFrames extends JFrame
{
static ArrayList<JPanel> panels = new ArrayList<JPanel>();
JPanel panel = new JPanel();
JPanel sortPane = new JPanel();
int toWrite = 0;
int colorGen = 0;
int comparison = 0;
Random rand = new Random();
public SortFrames()
{
for(int i = 0; i<4;i++)
{
panels.add(new JPanel());
}
for(JPanel p: panels)
{
toWrite = rand.nextInt(13);
colorGen = rand.nextInt(2);
p.add(new JLabel());
JLabel lblToSet = (JLabel)p.getComponent(0);
if(colorGen == 0)
{
p.setBackground(Color.BLACK);
lblToSet.setForeground(Color.WHITE);
}
if(colorGen == 1)
{
p.setBackground(Color.WHITE);
lblToSet.setForeground(Color.BLACK);
}
if(toWrite != 12){lblToSet.setText("" +toWrite);}
if(toWrite == 12){lblToSet.setText("-");}
p.setPreferredSize(new Dimension(30, 30));
panel.add(p);
}
sortMethod();
for(JPanel p: panels)
{
panel.add(p);
panel.revalidate();
}
add(panel);
panel.setPreferredSize(new Dimension(300, 300));
setPreferredSize(new Dimension(300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
setLocationRelativeTo(null);
}
public void sortMethod()
{
for(int i = 0; i<(panels.size());i++)
{
for(int j = i+1; j<(panels.size());j++)
{
JLabel one = (JLabel)(panels.get(i)).getComponent(0);
JLabel two = (JLabel)(panels.get(j)).getComponent(0);
String lblOne = one.getText();
String lblTwo = two.getText();
if(!lblOne.equals("-") && !lblTwo.equals("-"))
{
int comp1 = Integer.parseInt(lblOne);
int comp2 = Integer.parseInt(lblTwo);
JPanel pnl1 = panels.get(i);
JPanel pnl2 = panels.get(j);
if(comp1 == comp2)
{
if(pnl1.getBackground() == Color.BLACK && pnl2.getBackground() == Color.WHITE)
{
panels.set(i, pnl1);
panels.set(j, pnl2);
}
if(pnl1.getBackground() == Color.WHITE && pnl2.getBackground() == Color.BLACK)
{
panels.set(i, pnl2);
panels.set(j, pnl1);
}
}
if(comp1 != comp2)
{
if(comp1>comp2)
{
panels.set(i, pnl2);
panels.set(j, pnl1);
}
}
}
if(lblOne.equals("-") && !lblTwo.equals("-"))
{
JPanel pnl1 = panels.get(i);
panels.set(rand.nextInt(panels.size()), pnl1);
}
if(!lblOne.equals("-") && lblTwo.equals("-"))
{
JPanel pnl2 = panels.get(j);
panels.set(rand.nextInt(panels.size()), pnl2);
}
}
}
}
public static void main(String args[])
{
new SortFrames();
}
}
I also have another method, which is by using Comparator class which also creates the same problem (this sorts equal numbers based on foreground but still the same as to sort equal numbers based on background so it has no effect on the said issue).
private static class JPanelSort implements Comparator<JPanel>
{
#Override
public int compare(JPanel arg0, JPanel arg1)
{
JLabel one = ((JLabel) arg0.getComponent(0));
JLabel two = ((JLabel) arg1.getComponent(0));
String firstContent = one.getText();
String secondContent = two.getText();
try
{
comparisonRes = Integer.compare(Integer.parseInt(firstContent), Integer.parseInt(secondContent));
if(comparisonRes == 0)
{
if(one.getForeground() == Color.BLACK && two.getForeground() == Color.WHITE)
{
comparisonRes = 1;
}
if(two.getForeground() == Color.BLACK && one.getForeground() == Color.WHITE)
{
comparisonRes = -1;
}
}
}
catch(NumberFormatException e)
{
comparisonRes = 0;
}
return comparisonRes;
}
}
Please tell me your ideas. Thank you.
It's much easier to sort data than to sort JPanels.
Here's mu GUI displaying your numbers.
So, lets create a Java object to hold the card data.
public class DataModel {
private final int number;
private final int colorNumber;
private final Color backgroundColor;
private final Color foregroundColor;
public DataModel(int number, int colorNumber, Color backgroundColor,
Color foregroundColor) {
this.number = number;
this.colorNumber = colorNumber;
this.backgroundColor = backgroundColor;
this.foregroundColor = foregroundColor;
}
public int getNumber() {
return number;
}
public int getColorNumber() {
return colorNumber;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public Color getForegroundColor() {
return foregroundColor;
}
}
Pretty straightforward. We have fields to hold the information and getters to retrieve the information. We can make all the fields final since we're not changing anything once we set the values.
The sort class is pretty simple as well.
public class DataModelComparator implements Comparator<DataModel> {
#Override
public int compare(DataModel o1, DataModel o2) {
if (o1.getNumber() < o2.getNumber()) {
return -1;
} else if (o1.getNumber() > o2.getNumber()) {
return 1;
} else {
if (o1.getColorNumber() < o2.getColorNumber()) {
return -1;
} else if (o1.getColorNumber() > o2.getColorNumber()) {
return 1;
} else {
return 0;
}
}
}
}
Since we keep the color number, sorting by color is as easy as sorting a number.
Now that we've moved the data to it's own List, we can concentrate on creating the GUI.
package com.ggl.testing;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SortFrames implements Runnable {
private List<DataModel> dataModels;
private JPanel[] panels;
private JLabel[] labels;
private Random random = new Random();
public SortFrames() {
this.dataModels = new ArrayList<>();
this.random = new Random();
for (int i = 0; i < 4; i++) {
int number = random.nextInt(13);
int colorNumber = random.nextInt(2);
Color backgroundColor = Color.BLACK;
Color foregroundColor = Color.WHITE;
if (colorNumber == 1) {
backgroundColor = Color.WHITE;
foregroundColor = Color.BLACK;
}
dataModels.add(new DataModel(number, colorNumber, backgroundColor,
foregroundColor));
}
Collections.sort(dataModels, new DataModelComparator());
}
#Override
public void run() {
JFrame frame = new JFrame("Sort Frames");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
panels = new JPanel[dataModels.size()];
labels = new JLabel[dataModels.size()];
for (int i = 0; i < dataModels.size(); i++) {
DataModel dataModel = dataModels.get(i);
panels[i] = new JPanel();
panels[i].setBackground(dataModel.getBackgroundColor());
labels[i] = new JLabel(getDisplayText(dataModel));
labels[i].setBackground(dataModel.getBackgroundColor());
labels[i].setForeground(dataModel.getForegroundColor());
panels[i].add(labels[i]);
mainPanel.add(panels[i]);
}
frame.add(mainPanel);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
private String getDisplayText(DataModel dataModel) {
if (dataModel.getNumber() == 12) {
return "-";
} else {
return Integer.toString(dataModel.getNumber());
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new SortFrames());
}
public class DataModel {
private final int number;
private final int colorNumber;
private final Color backgroundColor;
private final Color foregroundColor;
public DataModel(int number, int colorNumber, Color backgroundColor,
Color foregroundColor) {
this.number = number;
this.colorNumber = colorNumber;
this.backgroundColor = backgroundColor;
this.foregroundColor = foregroundColor;
}
public int getNumber() {
return number;
}
public int getColorNumber() {
return colorNumber;
}
public Color getBackgroundColor() {
return backgroundColor;
}
public Color getForegroundColor() {
return foregroundColor;
}
}
public class DataModelComparator implements Comparator<DataModel> {
#Override
public int compare(DataModel o1, DataModel o2) {
if (o1.getNumber() < o2.getNumber()) {
return -1;
} else if (o1.getNumber() > o2.getNumber()) {
return 1;
} else {
if (o1.getColorNumber() < o2.getColorNumber()) {
return -1;
} else if (o1.getColorNumber() > o2.getColorNumber()) {
return 1;
} else {
return 0;
}
}
}
}
}
The lessons to be learned here are:
Separate the data from the view.
Focus on one part of the problem at a time. Divide and conquer.
I managed to get a delete button on a JFileChooser. I figured out where to put the button. In the process, I figured out, by messing with the getComponents() method, where the JTextField where the file is searched for and replaced it with a JComboBox. The plan is to get it to list all the files that begin with the text in the first row, the only one that can be edited on the JComboBox, otherwise it's uneditable, and it could select an item in another row and it would set the text of the item at the first row to the text of that item. (And also update the JCombobBox, though I don't think I implemented that part yet, though a simple method call should do that, but, anyway, I tried posting this on Java Programming Forums.
It's showing the items in there, but it's not letting it update with the typing. It is, instead, showing all the items in the directory. Also, when I go to select an item, it removes the first row and sets the text of the first row to the item. However, it now makes the first row uneditable I think or does something wacky.
It is removing the first row because the brilliant people who developed the JComboBox class couldn't bother to make a setItmeAt(Object item, int index) method, only a getItemAt(int index). So I had to get the text of the item, put it in a variable, remove the item at the first row, and then readd at the first row an item that has the text of the selected item.
I fear that maybe my code was too long, so I made it shorter, though even doing that today got no results at the Java Programming Forums, as the issue is with the JComboBox and the File class and stuff.
package addressbook.gui;
import javax.swing.JFileChooser;
import java.io.File;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JComboBox;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Window;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.MutableComboBoxModel;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.swing.plaf.basic.BasicComboPopup;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class FileChooserWithDelete extends JFileChooser
{
private String textFieldString;
private JIntelligentComboBox comboBox;
private DefaultComboBoxModel dcm;
public FileChooserWithDelete()
{
super("./");
dcm = new DefaultComboBoxModel();
java.io.File f = getCurrentDirectory();
java.io.File[] files = f.listFiles();
for (int i =0; i < files.length; i++)
{
dcm.addElement(new Object[] {files[i].getName(), "", 0});
}
JButton delete = new JButton("Delete");
delete.setToolTipText("Delete file");
comboBox = new JIntelligentComboBox(dcm);
addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
java.io.File oldDir = (java.io.File) evt.getOldValue();
java.io.File newDir = (java.io.File) evt.getNewValue();
java.io.File curDir = chooser.getCurrentDirectory();
System.out.println(curDir.getName());
dcm.removeAllElements();
java.io.File[] moreFiles = curDir.listFiles();
System.out.println("Obama is a loser!");
for (int i =0; i < moreFiles.length; i++)
{
dcm.addElement(new Object[] {moreFiles[i].getName(), "", 0});
}
comboBox.init();
}
}
});
java.awt.Container cont = (java.awt.Container) (getComponents()[3]);
java.awt.Container cont2 = (java.awt.Container) (cont.getComponents()[3]);
java.awt.Container cont3 = (java.awt.Container) (cont.getComponents()[0]);
cont3.remove(1);
cont3.add(comboBox, 1);
delete.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
File f= getSelectedFile();
java.awt.Container cont = (java.awt.Container) (getComponents()[3]);
java.awt.Container cont2 = (java.awt.Container) (cont.getComponents()[3]);
java.awt.Container cont3 = (java.awt.Container) (cont.getComponents()[0]);
//javax.swing.JTextField jtf = (javax.swing.JTextField) (cont3.getComponents()[1]);
String text = (String) comboBox.getItemAt(0);
if (f == null)
f = new File("./" + text);
int option = JOptionPane.showConfirmDialog(null, "Are you sure you wnat to delete?", "Delete file " + f.getName() + "?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (option == JOptionPane.YES_OPTION)
{
if (!f.exists() || text == null)
{
JOptionPane.showMessageDialog(null, "File doesn't exist.", "Could not find file.", JOptionPane.ERROR_MESSAGE);
cancelSelection();
}
else
{
f.delete();
cancelSelection();
}
}
}});
cont2.setLayout(new java.awt.FlowLayout());
//((java.awt.Container) (getComponents()[3])).add(delete);
cont2.add(delete);
//cont2.add(delete);
}
protected class JIntelligentComboBox extends JComboBox {
private List<Object> itemBackup = new ArrayList<Object>();
public JIntelligentComboBox(MutableComboBoxModel aModel) {
super(aModel);
init();
}
private void init() {
this.setRenderer(new searchRenderer());
this.setEditor(new searchComboBoxEditor());
this.setEditable(true);
int size = this.getModel().getSize();
Object[] tmp = new Object[this.getModel().getSize()];
for (int i = 0; i < size; i++) {
tmp[i] = this.getModel().getElementAt(i);
itemBackup.add(tmp[i]);
}
this.removeAllItems();
this.getModel().addElement(new Object[]{"", "", 0});
for (int i = 0; i < tmp.length; i++) {
this.getModel().addElement(tmp[i]);
}
final JTextField jtf = (JTextField) this.getEditor().getEditorComponent();
jtf.addKeyListener(
new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
searchAndListEntries(jtf.getText());
}
});
}
#Override
public MutableComboBoxModel getModel() {
return (MutableComboBoxModel) super.getModel();
}
private void searchAndListEntries(Object searchFor) {
List<Object> found = new ArrayList<Object>();
for (int i = 0; i < this.itemBackup.size(); i++) {
Object tmp = this.itemBackup.get(i);
if (tmp == null || searchFor == null) {
continue;
}
Object[] o = (Object[]) tmp;
String s = (String) o[0];
/*
if (s.matches("(?i).*" + searchFor + ".*")) {
found.add(new Object[]{
((Object[]) tmp)[0], searchFor, ((Object[]) tmp)[2]
});
}
}
*/
if (s.startsWith((String) searchFor))
found.add(new Object[] {((Object[]) tmp) [0], searchFor, ((Object[]) tmp) [2]});}
this.removeAllItems();
this.getModel().addElement(new Object[]{searchFor, searchFor, 0});
for (int i = 0; i < found.size(); i++) {
this.getModel().addElement(found.get(i));
}
this.setPopupVisible(true);
// http://stackoverflow.com/questions/7605995
BasicComboPopup popup =
(BasicComboPopup) this.getAccessibleContext().getAccessibleChild(0);
Window popupWindow = SwingUtilities.windowForComponent(popup);
Window comboWindow = SwingUtilities.windowForComponent(this);
if (comboWindow.equals(popupWindow)) {
Component c = popup.getParent();
Dimension d = c.getPreferredSize();
c.setPreferredSize(d);
}
else {
popupWindow.pack();
}
}
class searchRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (index == 0) {
setText("");
return this;
}
Object[] v = (Object[]) value;
String s = (String) v[0];
String lowerS = s.toLowerCase();
String sf = (String) v[1];
String lowerSf = sf.toLowerCase();
List<String> notMatching = new ArrayList<String>();
if (!sf.equals("")) {
int fs = -1;
int lastFs = 0;
while ((fs = lowerS.indexOf(lowerSf, (lastFs == 0) ? -1 : lastFs)) > -1) {
notMatching.add(s.substring(lastFs, fs));
lastFs = fs + sf.length();
}
notMatching.add(s.substring(lastFs));
}
String html = "";
if (notMatching.size() > 1) {
html = notMatching.get(0);
int start = html.length();
int sfl = sf.length();
for (int i = 1; i < notMatching.size(); i++) {
String t = notMatching.get(i);
html += "<b style=\"color: black;\">"
+ s.substring(start, start + sfl) + "</b>" + t;
start += sfl + t.length();
}
}
this.setText("<html><head></head><body style=\"color: gray;\">"
+ html + "</body></head>");
return this;
}
}
class searchComboBoxEditor extends BasicComboBoxEditor {
public searchComboBoxEditor() {
super();
}
#Override
public void setItem(Object anObject) {
if (anObject == null) {
super.setItem(anObject);
}
else {
Object[] o = (Object[]) anObject;
super.setItem(o[0]);
}
}
#Override
public Object getItem() {
return new Object[]{super.getItem(), super.getItem(), 0};
}
}
}
public JTextField getComboBoxTextField()
{
final JTextField jtf = (JTextField) comboBox.getEditor().getEditorComponent();
return jtf;
}
public static void main(String[] args)
{
FileChooserWithDelete fcwd = new FileChooserWithDelete();
fcwd.showOpenDialog(null);
}
}
The link to the page at the java programming forum is here.
You may be able to adapt the approach examined here. For notification, you may be able to leverage an existing JFileChooser event, as shown here. Alternatively, you can define your own PropertyChangeEvent, as shown here.
I have got it to work. However, there is a problem. The following lines are causing it to make ALL of my popups (i.e. JPopupMenu, JMenu, etc), scrunched so that you can't really read the titles on them.
The following lines seem to be the culprit.
BasicComboPopup popup =
(BasicComboPopup) this.getAccessibleContext().getAccessibleChild(0);
Window popupWindow = SwingUtilities.windowForComponent(popup);
Window comboWindow = SwingUtilities.windowForComponent(this);
if (comboWindow.equals(popupWindow)) {
Component c = popup.getParent();
Dimension d = c.getPreferredSize();
c.setPreferredSize(d);
}
else {
popupWindow.pack();
}
What is that bit doing? When I take it out, it gets rid of the error.
package addressbook.gui;
import javax.swing.JFileChooser;
import java.io.File;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JComboBox;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Window;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.MutableComboBoxModel;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.swing.plaf.basic.BasicComboPopup;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.BorderFactory;
public class FileChooserWithDelete extends JFileChooser
{
private String textFieldString;
private JIntelligentComboBox comboBox;
private DefaultComboBoxModel dcm;
private JCheckBox read, write, execute;
public FileChooserWithDelete()
{
super("./");
dcm = new DefaultComboBoxModel();
java.io.File f = getCurrentDirectory();
java.io.File[] files = f.listFiles();
for (int i =0; i < files.length; i++)
{
dcm.addElement(new Object[] {files[i].getName(), "", 0});
}
JButton delete = new JButton("Delete");
delete.setToolTipText("Delete file");
comboBox = new JIntelligentComboBox(dcm);
addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
java.io.File oldDir = (java.io.File) evt.getOldValue();
java.io.File newDir = (java.io.File) evt.getNewValue();
java.io.File curDir = chooser.getCurrentDirectory();
System.out.println(curDir.getName());
/*
//dcm.removeAllElements();
comboBox.removeAllItems();
dcm.removeAllElements();
java.io.File[] moreFiles = curDir.listFiles();
System.out.println("Obama is a loser!");
for (int i =0; i < moreFiles.length; i++)
{
dcm.addElement(new Object[] {moreFiles[i].getName(), "", 0});
//comboBox.insertItemAt(moreFiles[i].getName(), i);
}
for (int i =0; i < comboBox.getItemCount(); i++)
{
System.out.println(java.util.Arrays.toString((Object[]) comboBox.getItemAt(i)));
}
// comboBox.init();
*/
comboBox.updateFiles();
}
}
});
java.awt.Container cont = (java.awt.Container) (getComponents()[3]);
java.awt.Container cont2 = (java.awt.Container) (cont.getComponents()[3]);
java.awt.Container cont3 = (java.awt.Container) (cont.getComponents()[0]);
read = new JCheckBox("Read");
write = new JCheckBox("Write");
execute = new JCheckBox("Execute");
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setBorder(BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
cont3.remove(1);
cont3.add(comboBox, 1);
checkBoxPanel.setLayout(new java.awt.FlowLayout());
checkBoxPanel.add(read);
checkBoxPanel.add(write);
checkBoxPanel.add(execute);
read.setEnabled(false);
write.setEnabled(false);
execute.setEnabled(false);
addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e2)
{
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
.equals(e2.getPropertyName())) {
JFileChooser chooser = (JFileChooser)e2.getSource();
File oldFile = (File)e2.getOldValue();
File newFile = (File)e2.getNewValue();
// The selected file should always be the same as newFile
File curFile = chooser.getSelectedFile();
try
{
if (curFile.canRead())
{
read.setSelected(true);
}
else
{
read.setSelected(false);
}
if (curFile.canWrite())
{
write.setSelected(true);
}
else
{
write.setSelected(false);
}
if (curFile.canExecute())
{
execute.setSelected(true);
}
else
{
execute.setSelected(false);
}
}
catch(NullPointerException npe)
{
return;
}
}
}
});
delete.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
File f= getSelectedFile();
java.awt.Container cont = (java.awt.Container) (getComponents()[3]);
java.awt.Container cont2 = (java.awt.Container) (cont.getComponents()[3]);
java.awt.Container cont3 = (java.awt.Container) (cont.getComponents()[0]);
//javax.swing.JTextField jtf = (javax.swing.JTextField) (cont3.getComponents()[1]);
String text = (String) comboBox.getItemAt(0);
if (f == null)
f = new File("./" + text);
int option = JOptionPane.showConfirmDialog(null, "Are you sure you wnat to delete?", "Delete file " + f.getName() + "?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (option == JOptionPane.YES_OPTION)
{
if (!f.exists() || text == null)
{
JOptionPane.showMessageDialog(null, "File doesn't exist.", "Could not find file.", JOptionPane.ERROR_MESSAGE);
cancelSelection();
}
else
{
f.delete();
cancelSelection();
}
}
}});
cont2.setLayout(new java.awt.FlowLayout());
//((java.awt.Container) (getComponents()[3])).add(delete);
cont2.add(delete);
cont2.add(checkBoxPanel);
}
protected class JIntelligentComboBox extends JComboBox {
private List<Object> itemBackup = new ArrayList<Object>();
public JIntelligentComboBox(MutableComboBoxModel aModel) {
super(aModel);
init();
}
private void init() {
this.setRenderer(new searchRenderer());
this.setEditor(new searchComboBoxEditor());
this.setEditable(true);
int size = this.getModel().getSize();
Object[] tmp = new Object[this.getModel().getSize()];
for (int i = 0; i < size; i++) {
tmp[i] = this.getModel().getElementAt(i);
itemBackup.add(tmp[i]);
}
this.removeAllItems();
this.getModel().addElement(new Object[]{"", "", 0});
for (int i = 0; i < tmp.length; i++) {
this.getModel().addElement(tmp[i]);
}
final JTextField jtf = (JTextField) this.getEditor().getEditorComponent();
jtf.addKeyListener(
new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
searchAndListEntries(jtf.getText());
}
});
}
#Override
public MutableComboBoxModel getModel() {
return (MutableComboBoxModel) super.getModel();
}
private void updateFiles()
{
itemBackup.clear();
java.io.File f = getCurrentDirectory();
java.io.File[] files = f.listFiles();
for (int i =0; i < files.length; i++)
{
itemBackup.add(new Object[] {files[i].getName(), "", 0});
}
}
private void searchAndListEntries(Object searchFor) {
List<Object> found = new ArrayList<Object>();
for (int i =0; i < itemBackup.size(); i++)
{
System.out.println(java.util.Arrays.toString((Object[])itemBackup.get(i)));
}
for (int i = 0; i < this.itemBackup.size(); i++) {
Object tmp = this.itemBackup.get(i);
if (tmp == null || searchFor == null) {
continue;
}
Object[] o = (Object[]) tmp;
String s = (String) o[0];
/*
if (s.matches("(?i).*" + searchFor + ".*")) {
found.add(new Object[]{
((Object[]) tmp)[0], searchFor, ((Object[]) tmp)[2]
});
}
}
*/
if (s.startsWith((String) searchFor))
found.add(new Object[] {((Object[]) tmp) [0], searchFor, ((Object[]) tmp) [2]});}
this.removeAllItems();
this.getModel().addElement(new Object[]{searchFor, searchFor, 0});
for (int i = 0; i < found.size(); i++) {
this.getModel().addElement(found.get(i));
}
this.setPopupVisible(true);
// http://stackoverflow.com/questions/7605995\
/*
BasicComboPopup popup =
(BasicComboPopup) this.getAccessibleContext().getAccessibleChild(0);
Window popupWindow = SwingUtilities.windowForComponent(popup);
Window comboWindow = SwingUtilities.windowForComponent(this);
if (comboWindow.equals(popupWindow)) {
Component c = popup.getParent();
Dimension d = c.getPreferredSize();
c.setPreferredSize(d);
}
else {
popupWindow.pack();
}
*/
System.out.println("break");
for (int i =0; i < found.size(); i++)
{
System.out.println(java.util.Arrays.toString((Object[]) found.get(i)));
}
}
class searchRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (index == 0) {
setText("");
return this;
}
Object[] v = (Object[]) value;
String s = (String) v[0];
String lowerS = s.toLowerCase();
String sf = (String) v[1];
String lowerSf = sf.toLowerCase();
List<String> notMatching = new ArrayList<String>();
if (!sf.equals("")) {
int fs = -1;
int lastFs = 0;
while ((fs = lowerS.indexOf(lowerSf, (lastFs == 0) ? -1 : lastFs)) > -1) {
notMatching.add(s.substring(lastFs, fs));
lastFs = fs + sf.length();
}
notMatching.add(s.substring(lastFs));
}
String html = "";
if (notMatching.size() > 1) {
html = notMatching.get(0);
int start = html.length();
int sfl = sf.length();
for (int i = 1; i < notMatching.size(); i++) {
String t = notMatching.get(i);
html += "<b style=\"color: black;\">"
+ s.substring(start, start + sfl) + "</b>" + t;
start += sfl + t.length();
}
}
this.setText("<html><head></head><body style=\"color: gray;\">"
+ html + "</body></head>");
return this;
}
}
class searchComboBoxEditor extends BasicComboBoxEditor {
public searchComboBoxEditor() {
super();
}
#Override
public void setItem(Object anObject) {
if (anObject == null) {
super.setItem(anObject);
}
else {
Object[] o = (Object[]) anObject;
super.setItem(o[0]);
}
}
#Override
public Object getItem() {
return new Object[]{super.getItem(), super.getItem(), 0};
}
}
}
public JTextField getComboBoxTextField()
{
final JTextField jtf = (JTextField) comboBox.getEditor().getEditorComponent();
return jtf;
}
}
I'm using the Swing library to ask a user for their zipcode, but all that is appearing is a box, without the text box, or any of the other elements that I've added in (see code). Also, you likely need to know that I'm trying to get the int AskZip() in my public static void main(String[] args) method.
private static int zip;
public static int AskZip() {
JFrame zaWindow = new JFrame("What Zipcode");
zaWindow.setSize(200, 300);
JPanel jp = new JPanel();
final JTextField tf = new JTextField("Enter Zip Here");
JLabel label = new JLabel();
JButton button = new JButton("Get Weather");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String sZip = tf.getText();
int rZip = 0;
try {
if (sZip.length() != 5) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
rZip = Integer.parseInt(sZip);
}
} catch (NumberFormatException arg) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
}
zip = rZip;
}
});
label.setText("What is your zipcode?");
jp.add(label);
jp.add(tf);
jp.add(button);
zaWindow.add(jp);
return zip;
}
JFrame zaWindow..
This should be a modal dialog or a JOptionPane. E.G. This country has 3 states, each with 10 postcodes.
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeListener;
class ZipQuery {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
ZipNumberModel znm = new ZipNumberModel();
JSpinner zip = new JSpinner(znm);
JOptionPane.showMessageDialog(null, zip, "Enter Zipcode", JOptionPane.QUESTION_MESSAGE);
System.out.println("User chose " + znm.getValue());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class ZipNumberModel extends SpinnerNumberModel {
private ArrayList<Integer> zipCodes;
private int index = 0;
ZipNumberModel() {
zipCodes = new ArrayList<Integer>();
int zip = 10000;
for (int jj = 1; jj < 4; jj++) {
for (int ii = jj * zip; ii < jj * zip + 10; ii++) {
zipCodes.add(new Integer(ii));
}
}
}
#Override
public Object getValue() {
return zipCodes.get(index);
}
#Override
public Object getNextValue() {
if (index < zipCodes.size()-1) {
index++;
} else {
index = 0;
}
return zipCodes.get(index);
}
#Override
public Object getPreviousValue() {
if (index > 0) {
index--;
} else {
index = zipCodes.size()-1;
}
return zipCodes.get(index);
}
}
I want to create a text field that will be for dates and will have dd.mm.YYYY format. Now what I want the user to type only the numbers, not the dots to. So the field would be like:
_ _. _ _ . _ _ _ _
So when the user wants to type the date: 15.05.2010 for example, he will only type the numbers in the sequence 15052010.
Also I would like, when he presses on left or right arrow, the cursor to go from one field (not JTextField, but field in the JTextField) to the next. So lets say I have JTextField with this text in it: 15.05.2010 If the user is on the beginning and he presses the right arrow, the cursor should go to the .05 field.
I hope you understand me because right now I don't have any idea how to make this, or at least how to look for it on google.
Well, here are 4 classes that solve your problem.
In my case its version control but IP address has the same structure and its easy to modify it.
package com.demo.textfield.version;
import javax.swing.text.Document;
/**
* create documents for text fields
*/
public class DocumentsFactory {
private DocumentsFactory() {}
public static Document createIntDocument() {
return createIntDocument(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
public static Document createIntDocument(int maxValue) {
return createIntDocument(maxValue, Integer.MAX_VALUE);
}
public static Document createIntDocument(int maxValue, int maxLength) {
IntDocument intDocument = new IntDocument();
intDocument.setMaxVal(maxValue);
intDocument.setMaxLength(maxLength);
return intDocument;
}
}
in the followed class we define view:
package com.demo.textfield.version;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JPanel;
public class GridbagPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final Insets NO_INSETS = new Insets(0, 0, 0, 0);
public GridBagConstraints constraints;
private GridBagLayout layout;
public GridbagPanel() {
layout = new GridBagLayout();
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = NO_INSETS;
setLayout(layout);
}
public void setHorizontalFill() {
constraints.fill = GridBagConstraints.HORIZONTAL;
}
public void setNoneFill() {
constraints.fill = GridBagConstraints.NONE;
}
public void add(Component component, int x, int y, int width, int
height, int weightX, int weightY) {
GridBagLayout gbl = (GridBagLayout) getLayout();
gbl.setConstraints(component, constraints);
add(component);
}
public void add(Component component, int x, int y, int width, int height) {
add(component, x, y, width, height, 0, 0);
}
public void setBothFill() {
constraints.fill = GridBagConstraints.BOTH;
}
public void setInsets(Insets insets) {
constraints.insets = insets;
}
}
We use a plain document that contains our main logic (your changes should be here):
package com.demo.textfield.version;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
/**
* a class for positive integers
*/
public class IntDocument extends PlainDocument {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String NUMERIC = "0123456789";
private int maxVal = -1;
private int maxLength = -1;
public IntDocument() {
this.maxVal = -1;
maxVal = Integer.MAX_VALUE;
maxLength = Integer.MAX_VALUE;
}
public void setMaxLength(int maxLength) {
if (maxLength < 0)
throw new IllegalArgumentException("maxLength<0");
this.maxLength = maxLength;
}
public void setMaxVal(int maxVal) {
this.maxVal = maxVal;
}
public void insertString
(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null)
return;
if (str.startsWith(" ") && offset == 0) {
beep();
str = "";
}
if (!isValidForAcceptedCharsPolicy(str))
return;
if (validateLength(offset, str) == false)
return;
if (!isValidForMaxVal(offset, str))
return;
super.insertString(offset, str, attr);
}
public boolean isValidForAcceptedCharsPolicy(String str) {
if (str.equals("")) {
beep();
return false;
}
for (int i = 0; i < str.length(); i++) {
if (NUMERIC.indexOf(String.valueOf(str.charAt(i))) == -1) {
beep();
return false;
}
}
return true;
}
public boolean isValidForMaxVal(int offset, String toAdd) {
String str_temp;
//String str_text = "";
String str1 = "";
String str2 = "";
try {
str1 = getText(0, offset);
str2 = getText(offset, getLength() - offset);
} catch (Exception e) {
e.printStackTrace();
}
int i_value;
str_temp = str1 + toAdd + str2;
//str_temp = str_temp.trim();
i_value = Integer.parseInt(str_temp);
if (i_value > maxVal) {
beep();
return false;
} else
return true;
}
private boolean validateLength(int offset, String toAdd) {
String str_temp;
//String str_text = "";
String str1 = "";
String str2 = "";
try {
str1 = getText(0, offset);
str2 = getText(offset, getLength() - offset);
} catch (Exception e) {
e.printStackTrace();
}
str_temp = str1 + toAdd + str2;
if (maxLength < str_temp.length()) {
beep();
return false;
} else
return true;
}
private void beep() {
//java.awt.Toolkit.getDefaultToolkit().beep();
}
}
And this is last one with main method that implements all above posted code and you get pretty good view. In my case I used list of 4 text fields separated by dot. You can jump from one "window" to another by using arrows or tab or dot or if your number length reached 4. It will work with implementation of FocusAdapter class:
package com.demo.textfield.version;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.FocusManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
/**
* diplays an version text field
*/
![enter image description here][1]public class VersionTextField extends GridbagPanel {
private static final long serialVersionUID = 1L;
/**
* a text field for each byte
*/
private JTextField[] textFields;
/**
* dots between text fields
*/
private JLabel[] dotsLabels;
/**
* used to calculate enable/disable color; never shown
*/
private static JTextField sampleTextField = new JTextField();
/**
* listen to changes in the byte fields
*/
private MyDocumentListener documentListener;
/**
* list of key listeners
*/
private List<KeyListener> keyListenersList;
/**
* List of Focus Adapter that select all data in JTextFiled during action
* */
private List<FocusAdapter> focusAdapterList;
/**
* list of key listeners
*/
private List<FocusListener> focusListenersList;
private int maxHeight = 0;
public VersionTextField() {
this(4);
}
/**
* #param byteCount
* number of bytes to display
*/
private VersionTextField(int byteCount) {
textFields = new JTextField[byteCount];
for (int i = 0; i < textFields.length; i++) {
textFields[i] = new JTextField(4);
}
//layout
//constraints.insets = new Insets(0, 0, 0, 0);
List<JLabel> dotsLabelsList = new ArrayList<JLabel>();
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.setHorizontalAlignment(JTextField.CENTER);
Document document = DocumentsFactory.createIntDocument(9999);
textField.setDocument(document);
if (i < textFields.length-1) {
add(textField, i * 2, 0, 1, 1);
if (textField.getPreferredSize().height > maxHeight)
maxHeight = textField.getPreferredSize().height;
JLabel label = new JLabel(".");
add(label, (i * 2) + 1, 0, 1, 1);
if (label.getPreferredSize().height > maxHeight)
maxHeight = label.getPreferredSize().height;
dotsLabelsList.add(label);
} else
add(textField, i * 2, 0, 1, 1);
}
//dotsLabels = new JLabel[dotsLabelsList.size()];
dotsLabels = new JLabel[dotsLabelsList.size()];
dotsLabels = dotsLabelsList.toArray(dotsLabels);
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.setBorder(BorderFactory.createEmptyBorder());
}
//init
Color backgroundColor = UIManager.getColor("TextField.background");
setBackground(backgroundColor);
Border border = UIManager.getBorder("TextField.border");
setBorder(border);
//register listeners
for (int i = 1; i < textFields.length; i++) {
JTextField field = textFields[i];
field.addKeyListener(new BackKeyAdapter());
}
documentListener = new MyDocumentListener();
for (int i = 0; i < textFields.length - 1; i++) {
JTextField field = textFields[i];
field.getDocument().addDocumentListener(documentListener);
field.addKeyListener(new ForwardKeyAdapter());
}
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.addKeyListener(new MyKeyListener());
}
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.addFocusListener(new MyFocusAdapter());
}
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.addFocusListener(new MyFocusAdapter());
}
keyListenersList = new ArrayList<KeyListener>();
focusListenersList = new ArrayList<FocusListener>();
focusAdapterList = new ArrayList<FocusAdapter>();
}
public synchronized void addKeyListener(KeyListener l) {
super.addKeyListener(l);
keyListenersList.add(l);
}
public synchronized void addFocusListener(FocusListener l) {
super.addFocusListener(l);
if (focusListenersList != null)
focusListenersList.add(l);
}
public synchronized void removeKeyListener(KeyListener l) {
super.removeKeyListener(l);
if (focusListenersList != null)
keyListenersList.remove(l);
}
public synchronized void removeFocusListener(FocusListener l) {
super.removeFocusListener(l);
keyListenersList.remove(l);
}
public void setEnabled(boolean b) {
super.setEnabled(b);
sampleTextField.setEnabled(b);
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.setEnabled(b);
}
for (int i = 0; i < dotsLabels.length; i++) {
JLabel dotsLabel = dotsLabels[i];
dotsLabel.setEnabled(b);
}
setBackground(sampleTextField.getBackground());
setForeground(sampleTextField.getForeground());
setBorder(sampleTextField.getBorder());
}
public void requestFocus() {
super.requestFocus();
textFields[0].requestFocus();
}
public void setEditable(boolean b) {
sampleTextField.setEditable(b);
setBackground(sampleTextField.getBackground());
setForeground(sampleTextField.getForeground());
setBorder(sampleTextField.getBorder());
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.setEditable(b);
}
for (int i = 0; i < dotsLabels.length; i++) {
JLabel dotsLabel = dotsLabels[i];
dotsLabel.setForeground(sampleTextField.getForeground());
}
}
public boolean isFieldEmpty() {
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
String sCell = textField.getText().trim();
if (!(sCell.equals("")))
return false;
}
return true;
}
public Dimension getPreferredSize() {
if (super.getPreferredSize().height > maxHeight)
maxHeight = super.getPreferredSize().height;
return new Dimension(super.getPreferredSize().width, maxHeight);
}
/**
* clears current text in text fiekd
*/
private void reset() {
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.getDocument().removeDocumentListener(documentListener);
textField.setText("");
textField.getDocument().addDocumentListener(documentListener);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("test");
VersionTextField ipTextField = new VersionTextField();
ipTextField.setText("9.1.23.1479");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(ipTextField);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void setText(String version) {
if (version == null || "".equals(version) || "null".equals(version))
reset();
else {
setVer(version.split("[.]"));
}
}
private void setVer(String[] ver) {
if (ver == null) {
reset();
return;
}
Enumeration<String> enumeration = Collections.enumeration(Arrays.asList(ver));
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
String s = (String) enumeration.nextElement();
textField.getDocument().removeDocumentListener(documentListener);
textField.setText(s);
textField.getDocument().addDocumentListener(documentListener);
}
}
public void setToolTipText(String toolTipText) {
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
textField.setToolTipText(toolTipText);
}
}
private class MyDocumentListener implements DocumentListener {
#Override
public void insertUpdate(DocumentEvent e) {
Document document = e.getDocument();
try {
JTextField textField = (JTextField) FocusManager.getCurrentManager().getFocusOwner();
String s = document.getText(0, document.getLength());
if (s.length() == 4){ // && textField.getCaretPosition() == 2) {
textField.transferFocus();
}
} catch (BadLocationException e1) {
e1.printStackTrace();
return;
}
}
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
// Document document = e.getDocument();
// try {
// Component component = FocusManager.getCurrentManager().getFocusOwner();
// String s = document.getText(0, document.getLength());
//
// // get selected integer
// int valueInt = Integer.parseInt(s);
//
// if (valueInt > 25) {
// component.transferFocus();
// }
//
// } catch (BadLocationException e1) {
// e1.printStackTrace();
// return;
// }
}
}
private class BackKeyAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
JTextField textField = (JTextField) e.getComponent();
if (textField.getCaretPosition() == 0
&& KeyEvent.VK_LEFT == e.getKeyCode()
&& e.getModifiers() == 0)
textField.transferFocusBackward();
if (textField.getCaretPosition() == 0
&& KeyEvent.VK_BACK_SPACE == e.getKeyCode()
&& e.getModifiers() == 0) {
textField.transferFocusBackward();
}
}
}
private class ForwardKeyAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
JTextField textField = (JTextField) e.getComponent();
if (KeyEvent.VK_RIGHT == e.getKeyCode() && e.getModifiers() == 0) {
int length = textField.getText().length();
int caretPosition = textField.getCaretPosition();
if (caretPosition == length) {
textField.transferFocus();
e.consume();
}
}
if (e.getKeyChar() == '.' &&
textField.getText().trim().length() != 0) {
textField.setText(textField.getText().trim());
textField.transferFocus();
e.consume();
}
}
}
/**
* #return current text in ip text field
*/
public String getText() {
StringBuffer buffer = new StringBuffer();
String ipResult;
for (int i = 0; i < textFields.length; i++) {
JTextField textField = textFields[i];
if(textField.getText().trim().equals("")){
return "";
}
buffer.append(Integer.parseInt(textField.getText()));
if (i < textFields.length - 1){
buffer.append('.');
}
}
ipResult = buffer.toString();
return ipResult;
}
/**
* general purpose key listener
*/
private class MyKeyListener implements KeyListener {
public void keyPressed(KeyEvent e) {
for (int i = 0; i < keyListenersList.size(); i++) {
KeyListener keyListener = keyListenersList.get(i);
keyListener.keyPressed(new KeyEvent(VersionTextField.this,
e.getID(), e.getWhen(), e.getModifiers(), e
.getKeyCode(), e.getKeyChar(), e
.getKeyLocation()));
}
}
public void keyReleased(KeyEvent e) {
for (int i = 0; i < keyListenersList.size(); i++) {
KeyListener keyListener = keyListenersList.get(i);
keyListener.keyReleased(new KeyEvent(VersionTextField.this, e
.getID(), e.getWhen(), e.getModifiers(),
e.getKeyCode(), e.getKeyChar(), e.getKeyLocation()));
}
}
public void keyTyped(KeyEvent e) {
for (int i = 0; i < keyListenersList.size(); i++) {
KeyListener keyListener = keyListenersList.get(i);
keyListener.keyTyped(new KeyEvent(VersionTextField.this, e.getID(),
e.getWhen(), e.getModifiers(), e.getKeyCode(), e
.getKeyChar(), e.getKeyLocation()));
}
}
}
private class MyFocusAdapter extends FocusAdapter {
public void focusGained(FocusEvent e) {
for (int i = 0; i < focusListenersList.size(); i++) {
FocusListener focusListener = focusListenersList.get(i);
focusListener.focusGained(new FocusEvent(
VersionTextField.this,
e.getID(),
e.isTemporary(),
e.getOppositeComponent()
));
}
if(e.getComponent() instanceof javax.swing.JTextField){
highlightText((JTextField)e.getSource());
}
}
public void focusLost(FocusEvent e) {
for (int i = 0; i < focusListenersList.size(); i++) {
FocusListener focusListener = focusListenersList.get(i);
focusListener.focusLost(new FocusEvent(
VersionTextField.this,
e.getID(),
e.isTemporary(),
e.getOppositeComponent()
));
}
}
public void highlightText(javax.swing.JTextField ctr){
//ctr.setSelectionColor(Color.BLUE);
//ctr.setSelectedTextColor(Color.WHITE);
ctr.setSelectionStart(0);
ctr.setSelectionEnd(ctr.getText().length());
System.out.println(ctr.getText());
}
}
}
here a view what we got:
here you go
JFormattedTextField