My code with java GUI adds to an arraylist from a file.txt I have in a button the code that compares the code introduced in a textfield with the position in the araylist with an if else. But enter what you enter always goes through the else never through the if.
If I add the components manually as in Arraylist ArrayList <String> answer = new ArrayList <String> ();
then if else works.
But it seems that if I compare the text of the textfield with the
ArrayList <String> answer1 = new ArrayList <String> ();, the if does not work does not do well the comparison
The question is that I need to ask the user 266 questions The user must enter the answers, if the answer is not correct, an incorrect reply message should come out
but I can not get the if else to work with an arraylist loaded with a file.text here is my code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class question_answer extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnAnswer;
private JLabel lblNewLabelcuestion;
private JLabel LabelTextF;
private JLabel labelArraylistPos;
private JLabel lblNewLabelTF;
private JLabel lblNewLabelAL;
static int count = 0;
private JLabel lblNewLabel_1;
private static JTextArea textArea;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
question_answer frame = new question_answer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public question_answer() {
File archive = null;
FileReader fr = null;
//This works
/*
* ArrayList<String> question = new ArrayList<String>();
* question.add("What is your name?");
* question.add("What is your surname?");
* question.add("What is your age?");
* ArrayList<String> answer = new ArrayList<String>();
* answer.add("Pedro");
* answer.add("Rodriguez");
* answer.add("46");
*/
ArrayList<String> answer1 = new ArrayList<String>();
try {
archive = new File("C:\\answer.txt");
String line;
fr = new FileReader(archive);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
answer1.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
finally {
try {
if (fr != null) {
fr.close();
}
} catch (IOException e) {
}
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 567, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabelcuestion = new JLabel("New label");
lblNewLabelcuestion.setBounds(60, 56, 360, 24);
contentPane.add(lblNewLabelcuestion);
lblNewLabelTF = new JLabel("New label");
lblNewLabelTF.setBounds(60, 292, 56, 16);
contentPane.add(lblNewLabelTF);
LabelTextF = new JLabel("TextField");
LabelTextF.setBounds(60, 263, 56, 16);
contentPane.add(LabelTextF);
lblNewLabelAL = new JLabel("New label");
lblNewLabelAL.setBounds(170, 292, 56, 16);
contentPane.add(lblNewLabelAL);
labelArraylistPos = new JLabel("Arraylist Position");
labelArraylistPos.setBounds(170, 263, 110, 16);
contentPane.add(labelArraylistPos);
textField = new JTextField();
textField.setBounds(340, 139, 116, 22);
contentPane.add(textField);
textField.setColumns(10);
lblNewLabelcuestion.setText(answer1.get(count));
btnAnswer = new JButton("answer");
lblNewLabelAL.setText(answer1.get(count));
btnAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line1;
for (int j = 0; j < answer1.size(); j++) {
line1 = answer1.get(j);
textArea.append(line1);
}
lblNewLabelcuestion.setText(answer1.get(count));
lblNewLabelAL.setText(answer1.get(count));
lblNewLabelTF.setText(textField.getText());
String c = answer1.get(count);
String Tf = textField.getText();
if (Tf.equals(c)) {
lblNewLabel_1.setText("Good");
} else {
lblNewLabel_1.setText("Wrong");
}
count += 1;
}
});
btnAnswer.setBounds(340, 198, 97, 25);
contentPane.add(btnAnswer);
lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(45, 153, 256, 16);
contentPane.add(lblNewLabel_1);
textArea = new JTextArea();
textArea.setBounds(345, 273, 181, 67);
contentPane.add(textArea);
lblNewLabel = new JLabel("achive.text content");
lblNewLabel.setBounds(340, 244, 116, 16);
contentPane.add(lblNewLabel);
}
}
`
In any text editor, when you press enter, the the editor enters what is called a line break. This character is invisible but it tells the editor where to make a new line. You need to remove these characters from your lines. Good news is you only have to add one line of code to achieve this! Where you have:
while ((line = br.readLine()) != null) {
answer1.add(line);
}
Replace it with:
while ((line = br.readLine()) != null) {
line = line.replace(System.getProperty("line.separator"), “”);
answer1.add(line);
}
The above code will replace any line separator defined by the OS with an empty string, thereby making your compared strings equal.
The solution was String c = answer1.get(count).trim();
Related
Currently, I learn Java guI, swing.
I would like to link the j1('open' button) in Yam class with a Open_Button Class's function.
If I write a file name in "textField" which is a global variable in Yam class, and press the 'open', the "TextArea" has to show an output the opened file's content.
but somehow it doesn't work. I think the open_button class's function is not connected with the "textField" in Yam class.
But I really can't find what's wrong.
(sorry for my poor Engish..;( i'll show you full code. I want to follow Minimal, Complete, and Verifiable rull but I really don't know where is wrong part..)
Yam class )
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File.*;
import java.io.*;
import java.nio.file.*;
public class Yam extends JFrame {
Container contentPane;
JButton j1, j2, j3, j4, j5, j6;
JTextField textField;
JTextField textField_1;
TextArea textArea, textArea_1;
public Yam() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = getContentPane();
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(14, 12, 240, 24);
contentPane.add(textField);
textField.setColumns(20);
j1 = new JButton("Open");
j1.setBounds(294, 11, 105, 27);
j1.addActionListener(new AB());
contentPane.add(j1);
textField_1 = new JTextField();
textField_1.setBounds(14, 48, 240, 24);
contentPane.add(textField_1);
textField_1.setColumns(20);
j2 = new JButton("Save");
j2.setBounds(294, 47, 105, 27);
contentPane.add(j2);
textArea = new TextArea();
textArea.setBounds(10, 105, 405, 190);
contentPane.add(textArea);
j3 = new JButton("Compile");
j3.setBounds(10, 319, 87, 25);
j3.addActionListener(new AB());
contentPane.add(j3);
j4 = new JButton("Save Errors");
j4.setBounds(111, 319, 87, 25);
contentPane.add(j4);
j5 = new JButton("Delete");
j5.setBounds(217, 319, 87, 25);
contentPane.add(j5);
j6 = new JButton("Clear");
j6.setBounds(321, 319, 87, 25);
j6.addActionListener(new AB());
contentPane.add(j6);
textArea_1 = new TextArea();
textArea_1.setBounds(10, 391, 405, 253);
contentPane.add(textArea_1);
setSize(506, 698);
setVisible(true); }
class AB implements ActionListener {
private TextArea args;
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
CmdClass cmd = new CmdClass();
Open_button open = new Open_button();
JFrame f = new JFrame("what");
if(source == j1) {
}
else if(source == j2) {
}
else if(source == j3) {
if(cmd.main(args))
textArea_1.append("Compile Success\n");
}
else if(source == j4) { }
else if(source == j5) { }
else {
textField.setText(" ");
textField_1.setText(" ");
textArea.setText(" ");
textArea_1.setText(" "); }}}
public static void main(String[] args) {
new Yam();
}
public static String getFileName() {
// TODO Auto-generated method stub
return null;}}
Open_button class)
import java.io.*;
import java.nio.file.*;
import java.io.File;
public class Open_button {
Path Path;
public void main(String Str_paths){
Yam y = new Yam();
Str_paths = y.textField.getText();
Path = FileSystems.getDefault().getPath(Str_paths);
File file = Path.toFile();
if(Path.toFile() != null)
y.textArea.append("file exist!");
else {
y.textArea_1.append("file not exist");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(Str_paths));
String line;
while ((line = br.readLine()) != null) {
y.textArea.append(line);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
I think you want for some reason to open and read a file which the filepath is designated on the jtextfield; Simplest way would be:
JButton openButton = new JButton("Open File");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String thePath = textfield.getText();
File theFile = new File(thePath);
...read..write..
}
});
I would declare this directly on the Yam class;
From what I have seen, your code has two issues: first, there are two Yam (y) instances (the one declared in OpenButton class is different than the one located above) and, second, you assume that the file is readable and always located on Filesystem view...I think you should also consider a JFileChooser dialog.
Regards, André
I want to make the result of my buffered reader to appear in a text area, but It doesn't work for me.
I want the text area to get the result exactly as the system out print do, it is for more than one line, I tried to set the text area with string s but didn't work, just give me the result of one line.
Here is my Code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.ScrollPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Window extends JFrame {
/**
* Launch the application.
* #throws FileNotFoundException
*/
public static void main(String[] args) {
Window frame = new Window();
frame.setTitle("SWMA Extractor");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setBounds(50, 50, 665, 550);
//frame.setLocation(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
}
/**
* Create the frame.
*/
public Window() {
setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel path = new JLabel("File Location");
path.setHorizontalAlignment(SwingConstants.CENTER);
path.setBounds(20, 11, 74, 23);
contentPane.add(path);
final JTextField location = new JTextField();
location.setBounds(104, 12, 306, 20);
contentPane.add(location);
location.setColumns(10);
final JTextArea textArea = new JTextArea();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(20, 80, 605, 430);
contentPane.add(scrollPane);
scrollPane.add(textArea);
JButton btn = new JButton("Get Info.");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
File output = null;
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
int lineNumber = 1;
while((s = br.readLine()) != null) {
if (s.contains("System")) {
System.out.println(s);
String nextLine = br.readLine();
System.out.println(nextLine);
String nextLine1 = br.readLine();
System.out.println(nextLine1);
String nextLine2 = br.readLine();
System.out.println(nextLine2);
String nextLine3 = br.readLine();
System.out.println(nextLine3);
System.out.println();
}
}
lineNumber++;
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
btn.setBounds(433, 11, 192, 23);
contentPane.add(btn);
JButton clr = new JButton("Clear");
clr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getLocation = location.getText();
String s;
try {
textArea.setText("");
location.setText("");
} catch (Exception e1) {
}
}
});
clr.setBounds(20, 45, 605, 23);
contentPane.add(clr);
}
}
I see you say you tried setting the text, but the setText method actually replaces the whole current text with the new one:
JTextComponent #1669:
((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
You should use insert or append methods:
Replace
System.out.println(s);
with
textArea.append(s);
Also, check the following question for a better way of doing this:
Opening, Editing and Saving text in JTextArea to .txt file
private void fileRead(){
try{
FileReader read = new FileReader("filepath");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp = scan.nextLine() + System.lineSeparator();
storeAllString = storeAllString + temp;
}
}
catch (Exception exception) {
exception.printStackTrace();
}
}
#Hovercraft's suggestion is very good. If you don't want to process the file in any way, you could directly read it into the JTextArea:
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
textArea.read(br, "Stream description");
} catch (IOException e2) {
e2.printStackTrace();
}
I'm totally new to this section of networking with java.
What I'm trying to do is that, I want the user to add machine type and serial and when he press a button, this will extract the machine expiration date, model and country from a website and then put this data in a txt file automatically.
I'd like as well that the browser to be hidden but don't know how to do it.
I will really appreciate your help.
As well I would prefer to use JTextArea with a vertically only scroll pane to allow the user adding more than one machine (let's say 50 machines) at once , but as well, I don't know how to make the program read the type and serial from this JTextArea separatly
Here is my current code
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.URI;
public class PEW_Frame extends JFrame {
private JPanel contentPane;
private JTextField type;
private JTextField serial;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PEW_Frame frame = new PEW_Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PEW_Frame() {
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);
type = new JTextField();
type.setBounds(121, 27, 86, 20);
contentPane.add(type);
type.setColumns(10);
serial = new JTextField();
serial.setBounds(121, 72, 86, 20);
contentPane.add(serial);
serial.setColumns(10);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(34, 30, 46, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(34, 75, 46, 14);
contentPane.add(lblNewLabel_1);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Desktop d = Desktop.getDesktop();
String getType = type.getText();
String getSerial = serial.getText();
//String getType1 = type1.getText();
//String getSerial1 = serial1.getText();
String url = "https://www-947.ibm.com/support/entry/portal/wlup?type="+getType+"&serial="+getSerial;
//String url1 = "https://www-947.ibm.com/support/entry/portal/wlup?type="+getType1+"&serial="+getSerial1;
try {
if (getType.isEmpty() || getSerial.isEmpty()) {
throw new Exception();
}
d.browse(new URI(url));
//d.browse(new URI(url1));
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,"You must select SLA and period","Error !", JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(176, 189, 89, 23);
contentPane.add(btnNewButton);
//type1 = new JTextField();
//type1.setBounds(229, 27, 86, 20);
//contentPane.add(type1);
//type1.setColumns(10);
//serial1 = new JTextField();
//serial1.setBounds(229, 72, 86, 20);
//contentPane.add(serial1);
//serial1.setColumns(10);
}
}
You can get some help from the following example:
https://github.com/dotKom/OnlineGuru/blob/master/onlineguru/src/main/java/no/ntnu/online/onlineguru/plugin/plugins/middag/UpdateMenu.java#L40
public void run() {
StringBuilder sb = new StringBuilder();
// This posts the required fields to the sit.no RESTful menu api.
try {
// Prepare post data
String postData = "diner="+ kantine.toLowerCase() +"&trigger=single";
// Open connection
java.net.URL url = new URL(URLTEXT);
URLConnection conn = url.openConnection();
// Write the post data
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postData);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
wr.close();
rd.close();
} catch (IOException e) {
logger.error("Failed to get JSON data from "+URLTEXT, e.getCause());
}
// Get the html content into a clean string
String json = new String(sb);
json = StringEscapeUtils.unescapeJava(json);
String html = json.split(":")[1].replaceAll("^\"|\"}$", "");
// Traverse html with Jsoup
String menu = findMenuItems(html);
setMenu(kantine, menu);
}
I am looking for a way to save the users input from a jlist into a txt file. It's for a homework project. I have the program set up to take user input from a textfield, then it goes into the jlist once they hit the add button. The jlist has a defaultlistmodel on it, and I'm wondering if there is a way to create a save button and allow it to save the complete jlist into a .txt file.
Also, here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
public class i extends JFrame {
private JPanel contentPane;
private JTextField jTextField;
DefaultListModel ListModel = new DefaultListModel();
ArrayList<String> arr = new ArrayList <String>();
String str;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
i frame = new i();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public i() {
super("List");
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);
jTextField = new JTextField();
jTextField.setBounds(15, 80, 168, 20);
contentPane.add(jTextField);
jTextField.setColumns(10);
final JList jList = new JList(ListModel);
jList.setBorder(new LineBorder(new Color(0, 0, 0)));
jList.setBounds(289, 54, 135, 197);
contentPane.add(jList);
JButton jButton = new JButton("Add");
jButton.setBounds(190, 79, 89, 23);
contentPane.add(jButton);
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String str=jTextField.getText();
ListModel.addElement(str);
jTextField.setText("");
arr.add(str);
System.out.println(arr);
}
});
JButton delete = new JButton("DELETE");
delete.setBounds(190, 162, 89, 23);
contentPane.add(delete);
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent k){
ListModel.removeElement(jList.getSelectedValue());
}
});
JButton btnUp = new JButton("UP");
btnUp.setBounds(190, 125, 89, 23);
contentPane.add(btnUp);
btnUp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int index = jList.getSelectedIndex();
if(index == -1){
JOptionPane.showMessageDialog(null, "Select something to move.");
} else if(index > 0) {
String temp = (String)ListModel.remove(index);
ListModel.add(index - 1, temp);
jList.setSelectedIndex(index -1);
}
}
});
JButton btnDown = new JButton("DOWN");
btnDown.setBounds(190, 196, 89, 23);
contentPane.add(btnDown);
btnDown.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e ){
int index = jList.getSelectedIndex();
if( index == -1 )
JOptionPane.showMessageDialog(null, "Select something to move.");
else if( index < ListModel.size() - 1 ){
String temp = (String)ListModel.remove( index );
ListModel.add( index + 1, temp );
jList.setSelectedIndex( index + 1 );
}
}
});
JLabel lblItems = new JLabel("Items:");
lblItems.setBounds(290, 37, 46, 14);
contentPane.add(lblItems);
JButton btnPrint = new JButton("PRINT");
btnPrint.setBounds(190, 228, 89, 23);
contentPane.add(btnPrint);
btnPrint.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
}
you need use File class to save your list in that
File file = new File("c:/test/myfile.txt");
now file's created and opened!
and for write some output to file
use Formatter Class:
public class CreateFile
{
private Formatter x;
void openFile()
{
try
{
x = new Formatter("c:/myfile.txt");
System.out.println("you created a file");
}
catch(Exception e)
{
System.err.println("error in opening file");
}
}
void addFile()
{
x.format("%s %s %s\n","20","Start","Today");
}
void closeFile()
{
x.close();
}
}
as you see,addFile method accept 3 String passed to write in the file
i passed "20" , "Start" , "Today"
you can use more/less than %s , and pass user input or a list in String to write in the file.
good luck
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);
}
}