I got 5 JTextareas that stand for output for the sorting I need help regarding displaying or appending iteration in each JTextArea to show the algorithm of sorting.
I have got values of { 5,3,9,7,1,8 }
JTextArea1 |3, 5, 7, 1, 8, 9|
JTextArea2 |3, 5, 1, 7, 8, 9|
JTextArea3 |3, 5, 1, 7, 8, 9|
JTextArea4 |1, 3, 5, 7, 8, 9|
JTextArea5 |1, 3, 5, 7, 8, 9|
My problem is how can I append those values in each textarea.
My code is too long, I'm sorry for that.
My code is not finished yet. I just ended on the button of ascbubble but it can run.
//importing needed packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Sorting extends JPanel
{
// String needed to contain the values then convert into int
int int1,int2,int3,int4,int5,temp;
String str1,str2,str3,str4,str5;
//Buttons needed
JButton ascbubble,descbubble,
ascballoon,descballoon,
clear;
//Output Area of the result sorting
JTextArea output1,output2,
output3,output4,
output5;
//Text Field for user to input numbers
JTextField input1,input2,
input3,input4,
input5;
Sorting()
{
//set color of the background
setBackground(Color.black);
//initialize JButton,JTextArea and JTextField
//JButton
ascbubble = new JButton("Ascending Bubble");
descbubble = new JButton("Descending Bubble");
ascballoon = new JButton("Ascending Balloon");
descballoon = new JButton("Descending Balloon");
clear = new JButton("Clear");
//JTextArea
output1 = new JTextArea(" ");
output2 = new JTextArea(" ");
output3 = new JTextArea(" ");
output4 = new JTextArea(" ");
output5 = new JTextArea(" ");
//JTextField
input1 = new JTextField("00");
input2 = new JTextField("00");
input3 = new JTextField("00");
input4 = new JTextField("00");
input5 = new JTextField("00");
//SetBounds
setLayout(null);
input1.setBounds(120, 50, 30, 20);
input2.setBounds(170, 50, 30, 20);
input3.setBounds(220, 50, 30, 20);
input4.setBounds(270, 50, 30, 20);
input5.setBounds(320, 50, 30, 20);
ascbubble.setBounds(50, 120, 150, 40);
descbubble.setBounds(50, 180, 150, 40);
clear.setBounds(210, 140, 100, 50);
ascballoon.setBounds(320, 120, 150, 40);
descballoon.setBounds(320, 180, 150, 40);
output1.setBounds(20, 300, 80, 100);
output2.setBounds(120, 300, 80, 100);
output3.setBounds(220, 300, 80, 100);
output4.setBounds(320, 300, 80, 100);
output5.setBounds(420, 300, 80, 100);
//add function to the buttons
thehandler handler = new thehandler();
ascbubble.addActionListener(handler);
descbubble.addActionListener(handler);
ascballoon.addActionListener(handler);
descballoon.addActionListener(handler);
//add to the frame
add(input1);
add(input2);
add(input3);
add(input4);
add(input5);
add(output1);
add(output2);
add(output3);
add(output4);
add(output5);
add(ascbubble);
add(descbubble);
add(ascballoon);
add(descballoon);
add(clear);
}
private class thehandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ascbubble)
{
//input1
str1=input1.getText();
int1=Integer.parseInt(str1);
//input2
str2=input2.getText();
int2=Integer.parseInt(str2);
//input3
str3=input3.getText();
int3=Integer.parseInt(str3);
//input4
str4=input4.getText();
int4=Integer.parseInt(str4);
//input5
str5=input5.getText();
int5=Integer.parseInt(str5);
int contain[]={int1,int2,int3,int4,int5};
//formula for Buble Sort Ascending Order
for ( int pass = 1; pass < contain.length; pass++ )
{
for ( int i = 0; i < contain.length - pass; i++ )
{
if ( contain[ i ] > contain[ i + 1 ] )
{
temp = contain[ i ];
contain[ i ] = contain[ i + 1 ];
contain[ i + 1 ] = temp;
}
}
}
}
}
}
public static void main(String[]args)
{
JFrame frame = new JFrame("Sorting");
frame.add(new Sorting());
frame.setSize(550, 500);
frame.setVisible(true);
}
}
First of all, JTextArea has a simple append method, so you only need one. On each pass, you simply need to generate a new String which represents the current state of the array
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringJoiner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Sort {
public static void main(String[] args) {
new Sort();
}
public Sort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField fieldValues;
private JTextArea fieldResults;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
fieldValues = new JTextField(20);
fieldResults = new JTextArea(10, 20);
add(fieldValues, gbc);
JButton btn = new JButton("Sort");
add(btn, gbc);
add(new JScrollPane(fieldResults), gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] values = fieldValues.getText().split(",");
int[] contain = new int[values.length];
for (int index = 0; index < values.length; index++) {
contain[index] = Integer.parseInt(values[index].trim());
}
for (int pass = 1; pass < contain.length; pass++) {
for (int i = 0; i < contain.length - pass; i++) {
if (contain[i] > contain[i + 1]) {
int temp = contain[i];
contain[i] = contain[i + 1];
contain[i + 1] = temp;
StringJoiner sj = new StringJoiner(", ", "", "\n");
for (int value : contain) {
sj.add(Integer.toString(value));
}
fieldResults.append(sj.toString());
}
}
}
}
});
}
}
}
Now, the problem with this is, the larger the dataset, the more time it will take to sort, this will mean the UI will pause until the sort is completed
One solution would be to use a SwingWorker, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.StringJoiner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Sort {
public static void main(String[] args) {
new Sort();
}
public Sort() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField fieldValues;
private JTextArea fieldResults;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(2, 2, 2, 2);
fieldValues = new JTextField(20);
fieldResults = new JTextArea(10, 20);
add(fieldValues, gbc);
JButton btn = new JButton("Sort");
add(btn, gbc);
add(new JScrollPane(fieldResults), gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
String text = fieldValues.getText();
SortWorker worker = new SortWorker(text);
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
if ("state".equals(name)) {
if (worker.getState() == SwingWorker.StateValue.DONE) {
btn.setEnabled(true);
}
}
}
});
worker.execute();
}
});
}
public class SortWorker extends SwingWorker<int[], String> {
private String text;
public SortWorker(String text) {
this.text = text;
}
#Override
protected void process(List<String> chunks) {
for (String value : chunks) {
fieldResults.append(value);
}
}
#Override
protected int[] doInBackground() throws Exception {
String[] values = text.split(",");
int[] contain = new int[values.length];
for (int index = 0; index < values.length; index++) {
contain[index] = Integer.parseInt(values[index].trim());
}
for (int pass = 1; pass < contain.length; pass++) {
for (int i = 0; i < contain.length - pass; i++) {
if (contain[i] > contain[i + 1]) {
int temp = contain[i];
contain[i] = contain[i + 1];
contain[i + 1] = temp;
StringJoiner sj = new StringJoiner(", ", "", "\n");
for (int value : contain) {
sj.add(Integer.toString(value));
}
publish(sj.toString());
}
}
}
return contain;
}
}
}
}
Related
package com.tools;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.AbstractListModel;
import java.awt.Color;
import javax.swing.JTextArea;
import java.awt.List;
import javax.swing.JScrollPane;
public class CleaningToolV2 {
private JFrame frame;
private JTextField folderName;
private JTextField date_from;
private JTextField date_to;
JRadioButton radio_max = new JRadioButton("max");
JRadioButton radio_png = new JRadioButton("png");
JRadioButton radio_psd = new JRadioButton("psd");
JRadioButton radio_tiff = new JRadioButton("tiff");
JComboBox<String> comboBox = new JComboBox<String>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
JTextArea textArea = new JTextArea();
ArrayList<File> selectedFiles = new ArrayList<File>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CleaningToolV2 window = new CleaningToolV2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public CleaningToolV2() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
CleaningToolV2 thisObj = this;
frame = new JFrame();
frame.setBounds(100, 100, 450, 539);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
String toDayDate = simpleDateFormat.format(new Date());
DefaultComboBoxModel<String> comboModel1 = new DefaultComboBoxModel<String>(new String[] {"Furn", "Unfurn"});
DefaultComboBoxModel<String> comboModel2 = new DefaultComboBoxModel<String>(new String[] {"Temp"});
comboBox.setModel(comboModel1);
comboBox.setBounds(20, 174, 145, 27);
frame.getContentPane().add(comboBox);
folderName = new JTextField();
folderName.setBounds(20, 53, 283, 26);
frame.getContentPane().add(folderName);
folderName.setColumns(10);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc=new JFileChooser(folderName.getText());
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int i=fc.showOpenDialog(frame);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
folderName.setText(filepath);
}
}
});
btnBrowse.setBounds(315, 53, 117, 29);
frame.getContentPane().add(btnBrowse);
JLabel label_ext = new JLabel("Extensions and File name token");
label_ext.setBounds(20, 111, 250, 16);
frame.getContentPane().add(label_ext);
radio_png.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel1);
}
});
radio_png.setBounds(20, 139, 78, 23);
frame.getContentPane().add(radio_png);
radio_max.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel2);
}
});
radio_max.setBounds(130, 139, 71, 23);
frame.getContentPane().add(radio_max);
JLabel label_folder = new JLabel("Select folder");
label_folder.setBounds(20, 25, 107, 16);
frame.getContentPane().add(label_folder);
JLabel lblSelectTimeFrame = new JLabel("Enter time frame (DD/MM/YYYY)");
lblSelectTimeFrame.setBounds(20, 235, 267, 16);
frame.getContentPane().add(lblSelectTimeFrame);
date_from = new JTextField();
date_from.setBounds(71, 263, 130, 26);
frame.getContentPane().add(date_from);
date_from.setColumns(10);
date_from.setText(toDayDate);
date_to = new JTextField();
date_to.setColumns(10);
date_to.setBounds(286, 263, 130, 26);
date_to.setText(toDayDate);
frame.getContentPane().add(date_to);
JLabel label_time_from = new JLabel("From :");
label_time_from.setBounds(20, 268, 57, 16);
frame.getContentPane().add(label_time_from);
JLabel label_time_to = new JLabel("To :");
label_time_to.setBounds(243, 268, 44, 16);
frame.getContentPane().add(label_time_to);
JButton btnClearAllFiles = new JButton("Clear All Files");
btnClearAllFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(File f:selectedFiles) {
f.delete();
}
thisObj.refreshList();
}
});
btnClearAllFiles.setBounds(184, 482, 117, 29);
frame.getContentPane().add(btnClearAllFiles);
radio_psd.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel1);
}
});
radio_psd.setBounds(232, 139, 71, 23);
frame.getContentPane().add(radio_psd);
radio_tiff.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
comboBox.setModel(comboModel1);
}
});
radio_tiff.setBounds(333, 139, 71, 23);
frame.getContentPane().add(radio_tiff);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(radio_png);
bgroup.add(radio_max);
bgroup.add(radio_psd);
bgroup.add(radio_tiff);
radio_png.setSelected(true);
JLabel label_selected_files = new JLabel("Selected Files");
label_selected_files.setBounds(20, 318, 127, 16);
frame.getContentPane().add(label_selected_files);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(20, 346, 396, 124);
frame.getContentPane().add(scrollPane);
textArea.setEditable(false);
scrollPane.setViewportView(textArea);
JButton btnFilterFiles = new JButton("Filter Files");
btnFilterFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
thisObj.refreshList();
}
});
btnFilterFiles.setBounds(130, 313, 117, 29);
frame.getContentPane().add(btnFilterFiles);
}
public void refreshList() {
File folder = new File(folderName.getText());
File[] listOfFiles = folder.listFiles();
selectedFiles = new ArrayList<File>();
String fileNames = "";
String selectedItem = comboBox.getSelectedItem().toString().toLowerCase();
for (int i = 0; i < listOfFiles.length; i++) {
Date modified = new Date(listOfFiles[i].lastModified());
String modiDateString = simpleDateFormat.format(modified);
String from_text = date_from.getText();
String to_text = date_to.getText();
if (listOfFiles[i].isFile() && modiDateString.compareTo(from_text) >= 0 && modiDateString.compareTo(to_text) <= 0) {
String fileName = listOfFiles[i].getAbsoluteFile().getAbsolutePath();
String ext = this.getSelectedFileExt();
if(fileName.toLowerCase().endsWith("."+ext) && fileName.toLowerCase().indexOf("_"+selectedItem) > -1) {
fileNames += listOfFiles[i].getAbsoluteFile().getAbsolutePath() + "\n";
selectedFiles.add(listOfFiles[i]);
}
}
}
textArea.setText(fileNames);
}
private String getSelectedFileExt() {
String ext;
if(radio_max.isSelected()) {
ext = "max";
} else if(radio_psd.isSelected()) {
ext = "psd";
} else if(radio_tiff.isSelected()) {
ext = "tiff";
} else {
ext = "png";
}
return ext;
}
}
here it was deleting the files if i give exact folder location.
but what i am trying to get it is it has to search the directory which conrtains subfolders also
it has to search along the sub folders and delete the specified files (eg- file name will be
borrry_furn) which was specified in the dropdown
plz help me thanks in advance.
it has to search the directory which conrtains subfolders also it has to search along the sub folders
Your method to search a directory needs to be recursive.
Here is an example of a recursive method that lists the files in all the sub directories:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFile extends JFrame
implements ActionListener, Runnable
{
JTable table;
DefaultTableModel model;
JTextField path;
JLabel currentFile;
JButton getFiles;
int totalFiles;
int totalDirectories;
public TableFile()
{
path = new JTextField("C:\\java");
add(path, BorderLayout.PAGE_START );
getFiles = new JButton( "Get Files" );
getFiles.addActionListener( this );
add(getFiles, BorderLayout.LINE_START );
String[] columnNames = {"IsFile", "Name"};
model = new DefaultTableModel(columnNames, 0);
table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );
add(scrollPane, BorderLayout.PAGE_END);
currentFile = new JLabel(" ");
// add(currentFile, BorderLayout.PAGE_END); // displays filename in label
}
public void actionPerformed(ActionEvent e)
{
model.setNumRows(0);
new Thread( this ).start();
table.requestFocusInWindow();
}
public void run()
{
totalFiles = 0;
totalDirectories = 0;
listFiles( new File( path.getText() ) );
System.out.println("Directories: " + totalDirectories);
System.out.println("Files : " + totalFiles);
}
private void listFiles(File dir)
{
updateTable( dir );
totalDirectories++;
System.out.println("Processing directory: " + dir);
// add a delay to demonstrate processing one directory at a time
try { Thread.sleep(500); }
catch(Exception e) {}
File[ ] entries = dir.listFiles( );
int size = entries == null ? 0 : entries.length;
for(int j = 0; j < size; j++)
{
if (entries[j].isDirectory( ))
{
listFiles( entries[j] );
}
else
{
updateTable( entries[j] );
currentFile.setText( entries[j].toString() );
totalFiles++;
}
}
}
private void updateTable(final File file)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
Vector<Object> row = new Vector<Object>(2);
row.addElement( new Boolean( file.isFile() ) );
row.addElement( file.toString() );
model.addRow( row );
int rowCount = table.getRowCount() - 1;
table.changeSelection(rowCount, rowCount, false, false);
}
});
}
public static void main(String[] args)
{
TableFile frame = new TableFile();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
I have a SortedListModel called comandaDescriptionListModel:
private SortedListModel comandaDescriptionListModel;
I have other SortedListModels within my application, but this one fails to add items after 1 element. Just 1 element gets added, and it makes no sense.
btnAddComanda.addActionListener(new ActionListener() {
#SuppressWarnings("unchecked")
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel addPanel = new JPanel();
addPanel.add(new JLabel("Descrição:"));
JTextField comandaDescriptionField = new JTextField();
comandaDescriptionField.setPreferredSize(new Dimension(200, 24));
addPanel.add(comandaDescriptionField);
comandaDescriptionField.requestFocusInWindow();
String comandaName = "C" + Integer.toString(comandaListModel.getSize()+1);
int result = JOptionPane.showConfirmDialog(null, addPanel, "Adicionar comanda",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
if (comandaListModel.getSize() == 0) {
productComboBox.setEnabled(true);
btnAddProduct.setEnabled(true);
}
String comandaDescription = comandaDescriptionField.getText();
getCurrentCashRegister().addComanda(comandaName, comandaDescription);
// Comanda description model not adding items,
// Need to fix it
comandaListModel.addElement(comandaName);
comandaDescriptionListModel.addElement(comandaDescription); // HERE <<<
comandaList.setSelectedIndex(comandaList.getLastVisibleIndex());
clearProductComboBox();
updateProductComboBox();
}
}
});
Here's a screenshot:
Under "descrição", it should continue to "b" and "c". I can only think it's a bug. Is there some swing bug that causes problems when appending to more than one list at the same time?
When I deal with multi JList components, I do it in own way and also play with all given facilities.
why not, I use this below source code?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MultiListExample extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JButton addBtn, removeBtn;
private JList<String> list1, list2, list3;
private DefaultListModel<String> dlm1, dlm2, dlm3;
public MultiListExample() {
init();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MultiListExample();
}
});
}
private void init() {
setTitle("Multi List Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 100, 300, 300);
textField = new JTextField();
textField.setFont(new Font("Dialog", Font.PLAIN, 15));
add(textField, BorderLayout.PAGE_START);
JPanel panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.CENTER);
addBtn = new JButton("Add Element");
addBtn.setFocusPainted(false);
addBtn.setFont(textField.getFont());
panel.add(addBtn, BorderLayout.PAGE_START);
JPanel innerPanel = new JPanel(new GridLayout(1, 3));
panel.add(innerPanel, BorderLayout.CENTER);
dlm1 = new DefaultListModel<String>();
dlm1.addElement("Apple");
dlm1.addElement("Avocado");
dlm1.addElement("Banana");
dlm1.addElement("Jambul");
list1 = new JList<String>(dlm1);
list1.setFont(textField.getFont());
innerPanel.add(list1);
dlm2 = new DefaultListModel<String>();
dlm2.addElement("Currant");
dlm2.addElement("Cherry");
dlm2.addElement("Cloudberry");
dlm2.addElement("Raisin");
list2 = new JList<String>(dlm2);
list2.setFont(textField.getFont());
list2.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 1, Color.BLACK));
innerPanel.add(list2);
dlm3 = new DefaultListModel<String>();
dlm3.addElement("Dragonfruit");
dlm3.addElement("Durian");
dlm3.addElement("Feijoa");
dlm3.addElement("Fig");
dlm3.addElement("Grape");
list3 = new JList<String>(dlm3);
list3.setFont(textField.getFont());
innerPanel.add(list3);
removeBtn = new JButton("Remove Element");
removeBtn.setFocusPainted(false);
removeBtn.setFont(textField.getFont());
add(removeBtn, BorderLayout.PAGE_END);
list1.setSelectedIndex(dlm1.getSize() - 1);
list2.setSelectedIndex(dlm2.getSize() - 1);
list3.setSelectedIndex(dlm3.getSize() - 1);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
removeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (dlm1.getSize() > 0)
dlm1.remove(list1.getSelectedIndex());
if (dlm2.getSize() > 0)
dlm2.remove(list2.getSelectedIndex());
if (dlm3.getSize() > 0)
dlm3.remove(list3.getSelectedIndex());
if (dlm1.getSize() > 0)
list1.setSelectedIndex(0);
if (dlm2.getSize() > 0)
list2.setSelectedIndex(0);
if (dlm3.getSize() > 0)
list3.setSelectedIndex(0);
}
});
setVisible(true);
}
private void addElementListener() {
if (textField.getText().length() > 2) {
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list1, dlm1);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list2, dlm2);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list3, dlm3);
}
}
private void addSortAndRemoveDuplicates(String element, JList<String> list, DefaultListModel<String> model) {
// Here doing all DefaultListModel operations explicitly.
if (!model.contains(element)) {
model.addElement(element);
int size = model.getSize();
String[] elements = new String[size];
for (int i = 0; i < size; i++)
elements[i] = (String) model.getElementAt(i);
Arrays.sort(elements);
model.removeAllElements();
for (int i = 0; i < size; i++)
model.addElement(elements[i]);
list.setSelectedIndex(model.getSize() - 1);
}
}
private String firstLetterCapWord(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
}
Hi I am working on an innovation in my company to handle the hits from the server so for that user has to add the service names in my application which is of monitoring application. So i have kept a button which will give the jtextfields counting to 9 so during submit button, how will i get the values from all the textboxes, below is my code,
package com.Lawrence;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Sample2 implements ActionListener
{
JFrame mainFrame;
static int count = 0;
static int width_textfield = 10;
static int height_textfield = 40;
static int height = 0;
JButton addTextField,submit;
JTextField virtualDirectories;
JLabel virtualDirectoriesName;
ArrayList<String> texts = new ArrayList<String>();
public Sample2()
{
mainFrame = new JFrame("Add Virtual Directory");
mainFrame.setSize(640,640);
mainFrame.setResizable(false);
mainFrame.setLayout(null);
addTextField = new JButton();
addTextField.setText("Add Virtual directory");
addTextField.setBounds(10, 10, 200, 25);
addTextField.addActionListener(this);
mainFrame.add(addTextField);
submit = new JButton();
submit.setText("Submit");
submit.setBounds(180, 560, 100, 25);
submit.addActionListener(this);
mainFrame.add(submit);
mainFrame.setVisible(true);
height = mainFrame.getHeight();
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()== "Add Virtual directory")
{
if(height_textfield <= height-80)
{
virtualDirectoriesName = new JLabel("Virtual Directory"+"\t"+":");
virtualDirectoriesName.setBounds(10,height_textfield,200, 25);
mainFrame.add(virtualDirectoriesName);
virtualDirectories = new JTextField();
virtualDirectories.setBounds(150,height_textfield,200,25);
mainFrame.add(virtualDirectories);
texts.add(virtualDirectories.getText());
count++;
//width_textfield++;
height_textfield = height_textfield+60;
mainFrame.revalidate();
mainFrame.repaint();
//http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
}
else
{
JOptionPane.showMessageDialog(mainFrame, "can only add"+count+"virtual Directories");
}
}
if(e.getActionCommand() == "Submit")
{
ArrayList<String> texts = new ArrayList<String>();
for(int i = 0; i< count;i++)
{
texts.add(virtualDirectories.getText());
}
System.out.println(texts.size());
System.out.println(texts.toString());
}
}
}
So i need to get the values from those textboxes and add it to an arraylist and then processing it to enter into my server for parsing the log files.So please explain me how to do it
You could store every textfield into an arraylist, just like you did with the texts. Also, please take a look at how to use layout managers.
ArrayList<JTextField> fields = new ArrayList<JTextField>();
fields.add(virtualDirectories);
for (int i = 0; i < count; i++) {
texts.add(fields.get(i).getText());
}
Edit:
This is a version of your code using layout managers. (plus the lines above, of course)
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Sample2 implements ActionListener {
JFrame mainFrame;
JPanel bottom;
JPanel center;
JPanel centerPanel1;
JPanel centerPanel2;
static int count = 0;
static int width_textfield = 10;
static int height_textfield = 40;
static int height = 0;
JButton addTextField, submit;
JTextField virtualDirectories;
JLabel virtualDirectoriesName;
ArrayList<JTextField> fields = new ArrayList<JTextField>();
ArrayList<String> texts = new ArrayList<String>();
int maxFields = 10;
public Sample2() {
mainFrame = new JFrame("Add Virtual Directory");
mainFrame.setSize(640, 640);
mainFrame.setResizable(false);
addTextField = new JButton();
addTextField.setText("Add Virtual directory");
addTextField.setBounds(10, 10, 200, 25);
addTextField.addActionListener(this);
submit = new JButton();
submit.setText("Submit");
submit.setBounds(180, 560, 100, 25);
submit.addActionListener(this);
center = new JPanel(new GridLayout(1, 2));
centerPanel1 = new JPanel(new GridLayout(maxFields, 1, 0, 20));
centerPanel2 = new JPanel();
center.add(centerPanel1);
center.add(centerPanel2);
bottom = new JPanel(new FlowLayout());
bottom.add(addTextField);
bottom.add(submit);
mainFrame.getContentPane().add(bottom, BorderLayout.SOUTH);
mainFrame.getContentPane().add(center, BorderLayout.CENTER);
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Add Virtual directory") {
if (count < maxFields) {
JPanel p = new JPanel(new GridLayout(1, 2));
virtualDirectoriesName = new JLabel("Virtual Directory" + "\t" + ":");
virtualDirectories = new JTextField();
p.add(virtualDirectoriesName);
p.add(virtualDirectories);
centerPanel1.add(p);
texts.add(virtualDirectories.getText());
fields.add(virtualDirectories);
count++;
// width_textfield++;
height_textfield = height_textfield + 60;
mainFrame.revalidate();
mainFrame.repaint();
// http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
} else {
JOptionPane.showMessageDialog(mainFrame, "can only add " + maxFields + " virtual Directories");
}
}
if (e.getActionCommand() == "Submit") {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < count; i++) {
texts.add(fields.get(i).getText());
}
System.out.println(texts.size());
System.out.println(texts.toString());
}
}
public static void main(String[] args) {
new Sample2();
}
}
Im new to GUI's in Java and having a hell of a time understanding this:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
public class Main extends JFrame {
private JPanel contentPane;
static JPanel panel;
static JScrollPane scrollPane;
static JButton btnStart;
private static String compTestArray[];
static Integer indexer = 0;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 739, 456);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnStart = new JButton("Start");
btnStart.setBounds(10, 379, 89, 23);
btnStart.addActionListener(new ButtonListener());
contentPane.add(btnStart);
panel = new JPanel();
panel.setBounds(10, 11, 513, 359);
contentPane.add(panel);
scrollPane = new JScrollPane(panel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
scrollPane.setBounds(10, 11, 633, 359);
contentPane.add(scrollPane);
compTestArray = new String[2];
compTestArray[0] = "172.16.98.3";
compTestArray[1] = "172.16.98.6";
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
//String labelText = "Computer Name\tTest Name\tIteration\tPass\tFail\tCrashes\tStart\tStop";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel("Computer"));
for(int ix = 0; ix < compTestArray.length; ix++){
// Clear panel
panel.removeAll();
//labelText = compTestArray[indexer] + "\tKPI_1_1_1_1\t" + ix + "/20\t1\t\t0\t\t0\t\t12:00\t12:30";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel(compTestArray[indexer]));
System.out.println("indexer is " + indexer);
// Create constraints
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer+2; i++) {
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.weightx = 0;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
// Repaint the GUI
scrollPane.validate();
} // Close for loop
// Disable Start button
btnStart.setEnabled(false);
} // Close public void actionPerformed(ActionEvent arg0)
} // Close static class ButtonListener implements ActionListener
}
Output:
I'm just making a small application on window builder and need some help with it. I've made 2 frames individually and I don't know how to specify the action of the button in such a way that when I click on the 'next' botton in the first frame, I want it to move to the second frame.
Here's the source code for each file.
first.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.JTextArea;
import java.awt.Font;
import java.awt.event.ActionListener;
public class first extends JFrame {
private JPanel contentPane;
private final Action action = new SwingAction();
private final Action action_1 = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
first frame = new first();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public first() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNext.setAction(action_1);
btnNext.setBounds(257, 228, 55, 23);
contentPane.add(btnNext);
JButton btnExit = new JButton("Exit");
btnExit.setBounds(344, 228, 51, 23);
contentPane.add(btnExit);
JRadioButton rdbtnAdd = new JRadioButton("Add");
rdbtnAdd.setBounds(27, 80, 109, 23);
contentPane.add(rdbtnAdd);
JRadioButton rdbtnDelete = new JRadioButton("Delete");
rdbtnDelete.setBounds(27, 130, 109, 23);
contentPane.add(rdbtnDelete);
JRadioButton rdbtnEdit = new JRadioButton("Edit");
rdbtnEdit.setBounds(27, 180, 109, 23);
contentPane.add(rdbtnEdit);
JLabel lblSelectAnOption = new JLabel("Select an Option");
lblSelectAnOption.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblSelectAnOption.setBounds(27, 36, 121, 23);
contentPane.add(lblSelectAnOption);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Next");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
new second_add();
}
}
}
second.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
public class second_add extends JFrame {
private JPanel contentPane;
private JTextField txtTypeYourQuestion;
private JTextField txtQuestionWeight;
private JTextField txtEnter;
private JTextField txtEnter_1;
private JTextField txtValue;
private JTextField txtValue_1;
private final Action action = new SwingAction();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
second_add frame = new second_add();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public second_add() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtTypeYourQuestion = new JTextField();
txtTypeYourQuestion.setBounds(22, 11, 177, 20);
txtTypeYourQuestion.setText("Type your Question Here");
contentPane.add(txtTypeYourQuestion);
txtTypeYourQuestion.setColumns(10);
txtQuestionWeight = new JTextField();
txtQuestionWeight.setBounds(209, 11, 86, 20);
txtQuestionWeight.setText("Question weight");
contentPane.add(txtQuestionWeight);
txtQuestionWeight.setColumns(10);
txtEnter = new JTextField();
txtEnter.setBounds(22, 55, 86, 20);
txtEnter.setText("Enter . . .");
contentPane.add(txtEnter);
txtEnter.setColumns(10);
txtEnter_1 = new JTextField();
txtEnter_1.setText("Enter . . . ");
txtEnter_1.setBounds(22, 104, 86, 20);
contentPane.add(txtEnter_1);
txtEnter_1.setColumns(10);
txtValue = new JTextField();
txtValue.setText("Value . .");
txtValue.setBounds(118, 55, 51, 20);
contentPane.add(txtValue);
txtValue.setColumns(10);
txtValue_1 = new JTextField();
txtValue_1.setText("Value . .");
txtValue_1.setBounds(118, 104, 51, 20);
contentPane.add(txtValue_1);
txtValue_1.setColumns(10);
JButton btnFinish = new JButton("Finish");
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnFinish.setAction(action);
btnFinish.setBounds(335, 228, 89, 23);
contentPane.add(btnFinish);
JButton btnAddChoice = new JButton("Add choice");
btnAddChoice.setBounds(236, 228, 89, 23);
contentPane.add(btnAddChoice);
JButton btnAddQuestion = new JButton("Add question");
btnAddQuestion.setBounds(136, 228, 89, 23);
contentPane.add(btnAddQuestion);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
}
Having multiple JFrame instances in one application is bad usability
Consider using something like a CardLayout instead.
Modify like this-
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
second_add second = new second_add();
setVisible(false); // Hide current frame
second.setVisible(true);
}
});
You can navigate to a frame by creating its object and using setVisible method to display it. If you want to do it on a button click, write it inside its event handler.
JFrame o = new JFrame();
o.setVisible(true);
dispose(); // This will close the current frame
The quick and dirty solution would to set the first frame's visibility to false and the second frames visibility to true in your buttonclick action. (see Sajal Dutta's answer)
But to have a consistent behaviour even for more than 2 frames, let each frame be stored in a HashTable in your main class (class holding the main method and not extending JFrame) with the ID being the order of the frame (first frame D 1, second: ID 2, etc.).
Then create a static method
public void switchFrame(JFrame originatingFrame, int NextFrame){
originatingFrame.this.setVisible(false);
((JFrame) myHashTable.get(NextFrame)).setVisible(true);
}
in your main class which can be called from each frame using
mainClass.switchFrame(this, IdOfFrameYouWantToGoTo);
that way you can also implement "Back"- and "Skip"-Buttons should you want to create something like a wizard.
NOTE: I did not test this code. This should just be seen as a general overview of how to do this.
The below piece of code will show to navigate from one page to another page in a menu format.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class AddressBookDemo implements ActionListener, Runnable {
ArrayList personsList;
PersonDAO pDAO;
Panel panel;
JFrame appFrame;
JLabel jlbName, jblPassword, jlbAddress;
JPasswordField jPassword;
JTextField jtfName, jtfAddress;
JButton jbbSave, jbnClear, jbnExit, btnNext, button;
String name, address, password;
final int CARDS = 4;
CardLayout cl = new CardLayout();
JPanel cardPanel = new JPanel(cl);
CardLayout c2 = new CardLayout();
JPanel cardPanel2 = new JPanel(c2);
int currentlyShowing = 0;
Thread errorThrower;
// int phone;
// int recordNumber; // used to naviagate using >> and buttons
Container cPane;
Container cPane2;
private JFrame frame;
private TextArea textArea;
private Thread reader;
private Thread reader2;
private boolean quit;
private final PipedInputStream pin = new PipedInputStream();
private final PipedInputStream pin2 = new PipedInputStream();
public static void main(String args[]) {
new AddressBookDemo();
}
public AddressBookDemo() {
name = "";
password = "";
address = "";
// phone = -1; //Stores 0 to indicate no Phone Number
// recordNumber = -1;
createGUI();
personsList = new ArrayList();
// creating PersonDAO object
pDAO = new PersonDAO();
}
public void createGUI() {
/* Create a frame, get its contentpane and set layout */
appFrame = new JFrame("ManualDeploy ");
cPane = appFrame.getContentPane();
cPane.setLayout(new GridBagLayout());
// frame=new JFrame("Java Console");
textArea=new TextArea();
textArea.setEditable(false);
Button button=new Button("clear");
panel=new Panel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
panel.add(textArea,gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
panel.add(button,gridBagConstraintsx03);
// frame.add(panel);
// frame.setVisible(true);
// cPane2 = frame.getContentPane();
// cPane2.setLayout(new GridBagLayout());
button.addActionListener(this);
try
{
PipedOutputStream pout=new PipedOutputStream(this.pin);
System.setOut(new PrintStream(pout,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
}
try
{
PipedOutputStream pout2=new PipedOutputStream(this.pin2);
System.setErr(new PrintStream(pout2,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
}
quit=false; // signals the Threads that they should exit
// Starting two seperate threads to read from the PipedInputStreams
//
reader=new Thread(this);
reader.setDaemon(true);
reader.start();
//
reader2=new Thread(this);
reader2.setDaemon(true);
reader2.start();
// testing part
// you may omit this part for your application
//
System.out.println("Hello World 2");
System.out.println("All fonts available to Graphic2D:\n");
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames=ge.getAvailableFontFamilyNames();
for(int n=0;n<fontNames.length;n++) System.out.println(fontNames[n]);
// Testing part: simple an error thrown anywhere in this JVM will be printed on the Console
// We do it with a seperate Thread becasue we don't wan't to break a Thread used by the Console.
System.out.println("\nLets throw an error on this console");
errorThrower=new Thread(this);
errorThrower.setDaemon(true);
errorThrower.start();
arrangeComponents();
// arrangeComponents2();
final int CARDS = 2;
final CardLayout cl = new CardLayout();
final JPanel cardPanel = new JPanel(cl);
JMenu menu = new JMenu("M");
for (int x = 0; x < CARDS; x++) {
final int SELECTION = x;
JPanel jp = new JPanel();
if (x == 0) {
jp.add(cPane);
} else if (x == 1) {
jp.add(panel);
} else if (x == 2)
jp.add(new JButton("Panel 2"));
else
jp.add(new JComboBox(new String[] { "Panel 3" }));
cardPanel.add("" + SELECTION, jp);
JMenuItem menuItem = new JMenuItem("Show Panel " + x);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
currentlyShowing = SELECTION;
cl.show(cardPanel, "" + SELECTION);
}
});
menu.add(menuItem);
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
btnNext = new JButton("Next >>");
JButton btnPrev = new JButton("<< Previous");
JPanel p = new JPanel(new GridLayout(1, 2));
p.add(btnPrev);
p.add(btnNext);
btnNext.setVisible(false);
JFrame f = new JFrame();
f.getContentPane().add(cardPanel);
f.getContentPane().add(p, BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setJMenuBar(menuBar);
f.setVisible(true);
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing < CARDS - 1) {
cl.next(cardPanel);
currentlyShowing++;
}
}
});
btnPrev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (currentlyShowing > 0) {
cl.previous(cardPanel);
currentlyShowing--;
}
}
});
}
public void arrangeComponents() {
jlbName = new JLabel("Username");
jblPassword = new JLabel("Password");
jlbAddress = new JLabel("Sftpserver");
jtfName = new JTextField(20);
jPassword = new JPasswordField(20);
jtfAddress = new JTextField(20);
jbbSave = new JButton("move sftp");
jbnClear = new JButton("Clear");
jbnExit = new JButton("Exit");
/* add all initialized components to the container */
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
cPane.add(jlbName, gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
gridBagConstraintsx02.gridx = 1;
gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx02.gridy = 0;
gridBagConstraintsx02.gridwidth = 2;
gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
cPane.add(jtfName, gridBagConstraintsx02);
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
cPane.add(jblPassword, gridBagConstraintsx03);
GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
gridBagConstraintsx04.gridx = 1;
gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx04.gridy = 1;
gridBagConstraintsx04.gridwidth = 2;
gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
cPane.add(jPassword, gridBagConstraintsx04);
GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
gridBagConstraintsx05.gridx = 0;
gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx05.gridy = 2;
cPane.add(jlbAddress, gridBagConstraintsx05);
GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
gridBagConstraintsx06.gridx = 1;
gridBagConstraintsx06.gridy = 2;
gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx06.gridwidth = 2;
gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
cPane.add(jtfAddress, gridBagConstraintsx06);
GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
gridBagConstraintsx09.gridx = 0;
gridBagConstraintsx09.gridy = 4;
gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
cPane.add(jbbSave, gridBagConstraintsx09);
GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
gridBagConstraintsx10.gridx = 1;
gridBagConstraintsx10.gridy = 4;
gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnClear, gridBagConstraintsx10);
GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
gridBagConstraintsx11.gridx = 2;
gridBagConstraintsx11.gridy = 4;
gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnExit, gridBagConstraintsx11);
jbbSave.addActionListener(this);
// jbnDelete.addActionListener(this);
jbnClear.addActionListener(this);
jbnExit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("inside button123");
if (e.getSource() == jbbSave) {
savePerson();
} else if (e.getSource() == jbnClear) {
clear();
} else if (e.getSource() == jbnExit) {
System.exit(0);
}
else if (e.getSource() == button)
{
System.out.println("inside button");
textArea.setText(" ");
}
}
// Save the Person into the Address Book
public void savePerson() {
name = jtfName.getText();
password = jPassword.getText();
address = jtfAddress.getText();
if (name.equals("")) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
} else if (password != null && password.isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter password",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
else {
btnNext.setVisible(true);
JOptionPane.showMessageDialog(null, "Person Saved");
}
}
public void clear() {
jtfName.setText("");
jPassword.setText("");
jtfAddress.setText("");
personsList.clear();
}
public synchronized void run()
{
try
{
while (Thread.currentThread()==reader)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin.available()!=0)
{
String input=this.readLine(pin);
textArea.append(input);
}
if (quit) return;
}
while (Thread.currentThread()==reader2)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin2.available()!=0)
{
String input=this.readLine(pin2);
textArea.append(input);
}
if (quit) return;
}
} catch (Exception e)
{
textArea.append("\nConsole reports an Internal error.");
textArea.append("The error is: "+e);
}
// just for testing (Throw a Nullpointer after 1 second)
// if (Thread.currentThread()==errorThrower)
// {
// try { this.wait(1000); }catch(InterruptedException ie){}
// throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
// }
}
public synchronized String readLine(PipedInputStream in) throws IOException
{
String input="";
do
{
int available=in.available();
if (available==0) break;
byte b[]=new byte[available];
in.read(b);
input=input+new String(b,0,b.length);
}while( !input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
return input;
}
public synchronized void windowClosed(WindowEvent evt)
{
quit=true;
this.notifyAll(); // stop all threads
try { reader.join(1000);pin.close(); } catch (Exception e){}
try { reader2.join(1000);pin2.close(); } catch (Exception e){}
System.exit(0);
}
}