How to print an output on GUI textbox instead of Eclipse console? - java

I am trying to allow a user click a btnGenerate which then generates a random number that is assigned to a phrase that can be called to print out the phrase in a box below the button in the application window in eclipse.
The problem is that the random statement comes up on the Eclipse console instead of the textbox on my GUI.
Any help is appreciated. Here is my code so far:
//generate crime button
JButton generateBtn = new JButton("Generate Crime");
generateBtn.setBackground(Color.LIGHT_GRAY);
generateBtn.setFont(new Font("HGHeiseiKakugothictaiW3", Font.BOLD, 20));
GridBagConstraints gbc_generateBtn = new GridBagConstraints();
gbc_generateBtn.fill = GridBagConstraints.BOTH;
gbc_generateBtn.insets = new Insets(0, 0, 5, 5);
gbc_generateBtn.gridx = 15;
gbc_generateBtn.gridy = 5;
frmHeroVillains.getContentPane().add(generateBtn, gbc_generateBtn);
generateBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*random number generator that generates a number between 1-4 and outputs a random crime to the updatePane depending on which
number was generated */
int number = ((int) (Math.random()*4)+1);
switch (number) {
case 1:
System.out.println("Jewelry Heist on main street!");
break;
case 2:
System.out.println("Mugging in China town!");
break;
case 3:
System.out.println("Boeing 247 - Hijacked!");
default:
System.out.println("Nothing to Report.");
break;
}
;
JLabel updateLabel = new JLabel("UPDATE ALERT.... " + number);
GridBagConstraints gbc_updateLabel = new GridBagConstraints();
gbc_updateLabel.gridheight = 3;
gbc_updateLabel.insets = new Insets(0, 0, 5, 5);
gbc_updateLabel.gridx = 15;
gbc_updateLabel.gridy = 12;
frmHeroVillains.getContentPane().add(updateLabel, gbc_updateLabel);} }
);

You need to redirect the System.out.println(...) message to your own component.
Check out the Message Console for one approach to doing this. You can redirect the output to a JTextArea or JTextPane.

public static void main(String[] args) throws Exception {
//Must throws Exception
JPanel myOutput = new JPanel();
myOutput.setVisible(true);
myOutput.setBackground(Color.GRAY);
JTextArea mynewText = new JTextArea();
myOutput.add(mynewText);
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(
oracle.openStream()));
//InputStreamReader wrapped in BufferedReader
String inputLine;
inputLine = in.readLine();
mynewText.setText(inputLine);
in.close();
//In the target window class
mainWindow.add(myOutput);

Related

How to use JButton in Java

I'm trying to create a hangman game using the Swing class and Graphics class for a APCS class I have.
I created a JButton that would take the guess typed in by the user and either add it to the "misses" or fill in all of the corresponding letters in the word. I have a separate txt file where I pick a random word from.
When I run the program, all of the components show up, but the button does not do anything. I have been working on this for a few days and don't know what I am doing wrong. I have only learnt how to use the Swing class recently, so it may be a stupid mistake for all I know. I have put all of the code down below.
public class Hangman extends JFrame {
DrawPanel panel = new DrawPanel();
Graphics g = panel.getGraphics();
JTextField guess;
JTextField outputWord;
JTextField missesString;
boolean play;
JButton button = new JButton();
String output = "";
String word;
int misses = 0;
public Hangman() {
int again = 0;
String[] dictionary = new String[1000];
In words = new In("words.txt");
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(500, 500);
for (int i = 0; i < 1000; i++) {
dictionary[i] = words.readLine();
}
do {
int num = (int) (Math.random() * 1000);
word = dictionary[num].toLowerCase();
String answer = word;
word = "";
for (int i = answer.length(); i > 0; i--) {
word = word + "*";
}
int length = answer.length();
app.setLayout(new BorderLayout());
JLabel letter = new JLabel();
letter.setFont(new Font("Arial", Font.BOLD, 20));
letter.setText("Enter Your guess");
guess = new JTextField(10);
JLabel output = new JLabel();
output.setFont(new Font("Arial", Font.BOLD, 20));
output.setText("The Word is");
outputWord = new JTextField(30);
outputWord.setText(word);
outputWord.setEditable(false);
JLabel misses = new JLabel();
misses.setFont(new Font("Arial", Font.BOLD, 20));
misses.setText("Misses:");
missesString = new JTextField(52);
missesString.setEditable(false);
button = new JButton("Guess");
button.addActionListener(new ButtonListener());
JPanel panels = new JPanel();
panels.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.add(letter);
panel1.add(guess);
panel1.add(button);
JPanel panel2 = new JPanel();
panel2.add(output);
panel2.add(outputWord);
JPanel panel3 = new JPanel();
panel3.add(misses);
panel3.add(missesString);
app.add(panel1, BorderLayout.NORTH);
app.add(panel2, BorderLayout.EAST);
app.add(panel3, BorderLayout.SOUTH);
app.add(panels);
app.setVisible(true);
again = JOptionPane.showConfirmDialog(null, "Do you want to play again?");
} while (again == JOptionPane.YES_OPTION);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guess) {
output = "";
}
for (int i = 0; i <= word.length() - 1; i++) {
if (guess.getText().equalsIgnoreCase(word.substring(i, i + 1))) {
output = output.substring(0, i) + guess + output.substring(i + 1, word.length() - 1);
outputWord.setText(output);
} else {
misses++;
missesString.setText(missesString.getText() + guess + " ");
}
}
}
}
}
The components show up perfectly on the screen, it is only the button that is giving me a hard time by not working as expected.

JFrame stuck when opening another JFrame

EDIT2: Tested it. It is definetily a problem with the new JPanel.
SOLUTION:
As proposed the answer is that i forgot to explicitely set my JPanel onto my JFrame. Change:
setContentPane(contentPanetagesliste);
to
frame.setContentPane(contentPanetagesliste);
and it works for me!
My Problem is a strange behavior of JFrame.
In my code I got a radioButton on my MainFrame. When it is pressed it opens up the other Frame.
RadioBTNtagesliste.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
frame.setSize(590, 450); ...
In my new Frame I made a JPanel. Before adding the JPanel the other Frame didn't freeze, so I believe the problem got something to do with the new JPanel.
JPanel contentPanetagesliste;
contentPanetagesliste = new JPanel();
contentPanetagesliste.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPanetagesliste);
In the end I add a JScrollPane to the JPanel (that's the reason why I had to make one) and make the JFrame visible.
JScrollPane jsp = new JScrollPane(contentPanetagesliste);
frame.add(jsp);
frame.setVisible(true);
I absolutely have no clue how the new JPanel could interfere with the Main JFrame or the JPanel lying above the MainJFrame. I hope some of you can help me.
EDIT: because it wasn't clear to some: by stuck i mean unresponsive and when i move it, it goes blank grey.
To the image: When I press the radio button to the far top right, the new window opens, is fully functional but the old window is stuck.
image
For additional information I'll post the complete code from my action listener with explanation.
RadioBTNtagesliste.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
try {
if(RadioBTNtagesliste.isSelected() == true){
String Eintrag = HttpClass.httpRequestEintrag(usernamevar,EintragStringPK,"eintragTABLE");
JSONObject jsonObjectEintrag = new JSONObject(Eintrag);
int ProjektJSONlength = jsonObjectEintrag.length() - 1;
frame.setSize(590, 450);
JPanel contentPanetagesliste;
contentPanetagesliste = new JPanel();
contentPanetagesliste.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPanetagesliste);
double[] temp = new double[ProjektJSONlength+2];
temp[0] = 10;
temp[1] = 30;
for(int i = 0; i < ProjektJSONlength; i++){
temp[i+2] = 25;
}
double size[][] = {{2, 90, 90, 90, 90, 90,90, 2}, // Columns
temp}; // Rows
contentPanetagesliste.setLayout(new TableLayout(size));
String label[] = {"Eintrag Nr.", "Projekt", "Aktivität", "Dauer", "Beschreibung", "Symbol"};
JButton button[] = new JButton[label.length];
JTextField textfield[] = new JTextField[label.length];
for (int i = 0; i < label.length; i++) {
button[i] = new JButton(label[i]);
}
contentPanetagesliste.add(button[0], "1, 1");
contentPanetagesliste.add(button[1], "2, 1");
contentPanetagesliste.add(button[2], "3, 1");
contentPanetagesliste.add(button[3], "4, 1");
contentPanetagesliste.add(button[4], "5, 1");
contentPanetagesliste.add(button[5], "6, 1");
EintragStringPK = "Neu";
for (int key=0; key<=ProjektJSONlength;key++) {
JSONObject jsonObjectProjekteObjekt0 = jsonObjectEintrag.getJSONObject(String.valueOf(key));
String Eintraege = jsonObjectProjekteObjekt0.toString();
String EintragStringDauer = jsonObjectProjekteObjekt0.getString("dauer"); // String auslesen!!!
String EintragStringBEschreibung = jsonObjectProjekteObjekt0.getString("beschreibung"); // String auslesen!!!
String EintragStringProjektname = jsonObjectProjekteObjekt0.getString("projektname"); // String auslesen!!!
String EintragStringAktivitaet = jsonObjectProjekteObjekt0.getString("kategorie"); // String auslesen!!!
EintragStringPK = jsonObjectProjekteObjekt0.getString("pk_ei_id"); // String auslesen!!!
System.out.println("test" + key);
System.out.println(ProjektJSONlength);
String labelCONTENT[] = {EintragStringPK, EintragStringProjektname, EintragStringAktivitaet, EintragStringDauer, EintragStringBEschreibung, "Symbol"};
for (int i = 0; i < labelCONTENT.length; i++) {
textfield[i] = new JTextField(labelCONTENT[i]);
}
int keypone = key+2;
String keyString = Integer.toString(keypone);
contentPanetagesliste.add(textfield[0], "1, "+keyString);
contentPanetagesliste.add(textfield[1], "2, "+keyString);
contentPanetagesliste.add(textfield[2], "3, "+keyString);
contentPanetagesliste.add(textfield[3], "4, "+keyString);
contentPanetagesliste.add(textfield[4], "5, "+keyString);
contentPanetagesliste.add(textfield[5], "6, "+keyString);
}
JScrollPane jsp = new JScrollPane(contentPanetagesliste);
frame.add(jsp);
frame.setVisible(true);
System.out.println("ende");
}else{
frame.setVisible(false);
System.out.println("ende2");
}
System.out.println("ende3");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("ende4");
}
});
Explanation:
I create the JFrame, afterwards the JPanel.
Create an Array and the rest necessary for my Table, because the goal is to make a generated table with data from a SQL DB.
There is also a HTTPrequest and a loop to get out the data and put it into the table fields.
Still in the loop the filled table fields are added to the content pane and at the very and the Jpanel get's his JScrollPane and the frame is set visible.
I really hope someone can help me, and if you got tips for making better questions I've got an open ear.
setContentPane(contentPanetagesliste); should be explicit set to the new frame you created like this: frame.setContentPane(contentPanetagesliste);.

How can I access variables outside of loop in Java?

So I have my if statements to search a .txt file for the currency codes that correspond to the country the user types in. I store those country codes in Strings called 'from' and 'to'. I need to access the results of the if statements which are stored in the 'from' and 'to' variables to plug into something later. When I try to use these in the line way down at the end it says Cannot find symbol 'from' and Cannot find symbol 'to'. How can I fix this?
//all my imports here
public class ExchangeApp {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300,400);
frame.setTitle("Exchange App");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 2, 5, 3));
//GUI Elements
JLabel toLabel = new JLabel("To");
JTextField CurrencyTo = new JTextField(20);
JLabel fromLabel = new JLabel("From");
JTextField CurrencyFrom = new JTextField(20);
JLabel amountLabel = new JLabel("Amount");
JTextField AmountText = new JTextField(20);
JLabel displayLabel = new JLabel();
JLabel updateLabel = new JLabel();
JButton Calculate = new JButton("Calculate");
JButton Clear = new JButton("Clear");
//Add elements to panel
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(fromLabel);
panel.add(CurrencyFrom);
panel.add(toLabel);
panel.add(CurrencyTo);
panel.add(amountLabel);
panel.add(AmountText);
panel.add(Calculate);
panel.add(Clear);
panel.add(displayLabel);
panel.add(updateLabel);
//make visible
frame.add(panel);
frame.setVisible(true);
class calculateListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==Calculate){
String line, from, to;
String fromString = CurrencyFrom.getText();
String toString = CurrencyTo.getText();
double amount = Double.parseDouble(AmountText.getText());
try{
//import text file
File inputFile = new File("currency.txt");
//create file scanner
Scanner input = new Scanner(inputFile);
try{
//skip first line
input.nextLine();
//while has next line
while(input.hasNextLine()){
//set line equal to entire line
line = input.nextLine();
String[] countryArray = line.split("\t");
//search for from
if(fromString.equals(countryArray[0])){
//set 'from' equal to that country code
from = countryArray[2];
//testing
System.out.println(from);
}
//search for to
if(toString.equals(countryArray[0])){
//set 'to' equal to that country code
to = countryArray[2];
System.out.println(to);
}
else{
displayLabel.setText("To country not found");
}
}//while loop
}//2nd try
finally{input.close();}
}//1st try
catch(IOException exception){
System.out.println(exception);
}//catch bracket
}//if bracket ****these 2 variables****
String address = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to;
}//action bracket
}//class implements action listener bracket
ActionListener listener = new calculateListener();
Calculate.addActionListener(listener);
}//main bracket
}//class bracket

Change java applet to java application

I have an applet that runs a GUI. I want to call this GUI from my other program. I know that I need to turn this applet into an application. I have an init() and a actionPerformed(ActionEvent ae). How can I do it?
My code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class survey extends Applet implements ActionListener
{
private TextField question;
private Button enter, start;
int count = 0;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
String text, input;
private Label intro1, intro2, intro3;
private Label qone1, qone2, qone3, qone4, qone5, qone6, qone7, qone8, qone9, qone10, qone11, qone12;
private Label qtwo1, qtwo2, qtwo3, qtwo4, qtwo5, qtwo6, qtwo7, qtwo8, qtwo9, qtwo10, qtwo11, qtwo12;
private Label qthree1, qthree2, qthree3, qthree4, qthree5, qthree6, qthree7, qthree8, qthree9, qthree10, qthree11, qthree12;
private Label qfour1, qfour2, qfour3, qfour4, qfour5, qfour6, qfour7, qfour8, qfour9, qfour10, qfour11, qfour12;
private Label qfive1, qfive2, qfive3, qfive4, qfive5, qfive6, qfive7, qfive8, qfive9, qfive10, qfive11, qfive12;
private Label qsix1, qsix2, qsix3, qsix4, qsix5, qsix6, qsix7, qsix8, qsix9, qsix10, qsix11, qsix12;
private Label qseven1, qseven2, qseven3, qseven4, qseven5, qseven6, qseven7, qseven8, qseven9, qseven10, qseven11, qseven12;
private Label qeight1, qeight2, qeight3, qeight4, qeight5, qeight6, qeight7, qeight8, qeight9, qeight10, qeight11, qeight12;
private Label qnine1, qnine2, qnine3, qnine4, qnine5, qnine6, qnine7, qnine8, qnine9, qnine10, qnine11, qnine12;
private Label qten1, qten2, qten3, qten4, qten5, qten6, qten7, qten8, qten9, qten10, qten11, qten12;
private Label qeleven1, qeleven2, qeleven3, qeleven4, qeleven5, qeleven6,
private Label finish1, finish2, finish3;
public void init()
{
setLayout(null);
start = new Button ("Start");
question = new TextField(10);
enter = new Button ("Enter");
if (count == 0)
{
setBackground( Color.yellow);
intro1 = new Label("Target Advertising", Label.CENTER);
intro1.setFont(new Font("Times-Roman", Font.BOLD, 16));
intro2 = new Label("Welcome to this questionnaire. First, we would like to know more about your personal preferences.");
intro3 = new Label("For each question, Input a rating between 0-9 (zero = least interested, 9 = most interested) in the text box. Click enter for next question.");
add(intro1);
add(intro2);
add(intro3);
intro1.setBounds(0,0,800,20);
intro2.setBounds(15,20,800,20);
intro3.setBounds(15,40,800,20);
add(start);
start.setBounds(370,60,70,23);
start.addActionListener(this);
}
if(count == 1)
{
setBackground( Color.yellow );
qone1 = new Label("Question 1", Label.LEFT);
qone1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qone2 = new Label("How much do you like action movies?");
qone3 = new Label("0");
qone4 = new Label("1");
qone5 = new Label("2");
qone6 = new Label("3");
qone7 = new Label("4");
qone8 = new Label("5");
qone9 = new Label("6");
qone10 = new Label("7");
qone11 = new Label("8");
qone12 = new Label("9");
add(qone1);
add(qone2);
add(qone3);
add(qone4);
add(qone5);
add(qone6);
add(qone7);
add(qone8);
add(qone9);
add(qone10);
add(qone11);
add(qone12);
qone1.setBounds(15,0,800,20);
qone2.setBounds(15,20,800,15);
qone3.setBounds(15,60,800,15);
qone4.setBounds(15,80,800,15);
qone5.setBounds(15,100,800,15);
qone6.setBounds(15,120,800,15);
qone7.setBounds(15,140,800,15);
qone8.setBounds(15,160,800,15);
qone9.setBounds(15,180,800,15);
qone10.setBounds(15,200,800,15);
qone11.setBounds(15,220,800,15);
qone12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if (count == 2)
{
qtwo1 = new Label("Question 2", Label.LEFT);
qtwo1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qtwo2 = new Label("How much do you like Science Fiction?");
qtwo3 = new Label("0");
qtwo4 = new Label("1");
qtwo5 = new Label("2");
qtwo6 = new Label("3");
qtwo7 = new Label("4");
qtwo8 = new Label("5");
qtwo9 = new Label("6");
qtwo10 = new Label("7");
qtwo11 = new Label("8");
qtwo12 = new Label("9");
add(qtwo1);
add(qtwo2);
add(qtwo3);
add(qtwo4);
add(qtwo5);
add(qtwo6);
add(qtwo7);
add(qtwo8);
add(qtwo9);
add(qtwo10);
add(qtwo11);
add(qtwo12);
qtwo1.setBounds(15,0,800,20);
qtwo2.setBounds(15,20,800,15);
qtwo3.setBounds(15,60,800,15);
qtwo4.setBounds(15,80,800,15);
qtwo5.setBounds(15,100,800,15);
qtwo6.setBounds(15,120,800,15);
qtwo7.setBounds(15,140,800,15);
qtwo8.setBounds(15,160,800,15);
qtwo9.setBounds(15,180,800,15);
qtwo10.setBounds(15,200,800,15);
qtwo11.setBounds(15,220,800,15);
qtwo12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 3)
{
qthree1 = new Label("Question 3", Label.LEFT);
qthree1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qthree2 = new Label("How much do you like comedy?");
qthree3 = new Label("0");
qthree4 = new Label("1");
qthree5 = new Label("2");
qthree6 = new Label("3");
qthree7 = new Label("4");
qthree8 = new Label("5");
qthree9 = new Label("6");
qthree10 = new Label("7");
qthree11 = new Label("8");
qthree12 = new Label("9");
add(qthree1);
add(qthree2);
add(qthree3);
add(qthree4);
add(qthree5);
add(qthree6);
add(qthree7);
add(qthree8);
add(qthree9);
add(qthree10);
add(qthree11);
add(qthree12);
qthree1.setBounds(15,0,800,20);
qthree2.setBounds(15,20,800,15);
qthree3.setBounds(15,60,800,15);
qthree4.setBounds(15,80,800,15);
qthree5.setBounds(15,100,800,15);
qthree6.setBounds(15,120,800,15);
qthree7.setBounds(15,140,800,15);
qthree8.setBounds(15,160,800,15);
qthree9.setBounds(15,180,800,15);
qthree10.setBounds(15,200,800,15);
qthree11.setBounds(15,220,800,15);
qthree12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 4)
{
qfour1 = new Label("Question 4", Label.LEFT);
qfour1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qfour2 = new Label("How much do you like luxary cars?");
qfour3 = new Label("0");
qfour4 = new Label("1");
qfour5 = new Label("2");
qfour6 = new Label("3");
qfour7 = new Label("4");
qfour8 = new Label("5");
qfour9 = new Label("6");
qfour10 = new Label("7");
qfour11 = new Label("8");
qfour12 = new Label("9");
add(qfour1);
add(qfour2);
add(qfour3);
add(qfour4);
add(qfour5);
add(qfour6);
add(qfour7);
add(qfour8);
add(qfour9);
add(qfour10);
add(qfour11);
add(qfour12);
qfour1.setBounds(15,0,800,20);
qfour2.setBounds(15,20,800,15);
qfour3.setBounds(15,60,800,15);
qfour4.setBounds(15,80,800,15);
qfour5.setBounds(15,100,800,15);
qfour6.setBounds(15,120,800,15);
qfour7.setBounds(15,140,800,15);
qfour8.setBounds(15,160,800,15);
qfour9.setBounds(15,180,800,15);
qfour10.setBounds(15,200,800,15);
qfour11.setBounds(15,220,800,15);
qfour12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 5)
{
qfive1 = new Label("Question 5", Label.LEFT);
qfive1.setFont(new Font("Times-Roman", Font.BOLD, 16));
qfive2 = new Label("How much do you like trucks?");
qfive3 = new Label("0");
qfive4 = new Label("1");
qfive5 = new Label("2");
qfive6 = new Label("3");
qfive7 = new Label("4");
qfive8 = new Label("5");
qfive9 = new Label("6");
qfive10 = new Label("7");
qfive11 = new Label("8");
qfive12 = new Label("9");
add(qfive1);
add(qfive2);
add(qfive3);
add(qfive4);
add(qfive5);
add(qfive6);
add(qfive7);
add(qfive8);
add(qfive9);
add(qfive10);
add(qfive11);
add(qfive12);
qfive1.setBounds(15,0,800,20);
qfive2.setBounds(15,20,800,15);
qfive3.setBounds(15,60,800,15);
qfive4.setBounds(15,80,800,15);
qfive5.setBounds(15,100,800,15);
qfive6.setBounds(15,120,800,15);
qfive7.setBounds(15,140,800,15);
qfive8.setBounds(15,160,800,15);
qfive9.setBounds(15,180,800,15);
qfive10.setBounds(15,200,800,15);
qfive11.setBounds(15,220,800,15);
qfive12.setBounds(15,240,800,15);
add(question);
add(enter);
question.setBounds(15,260,70,15);
enter.setBounds(90,260,110,23);
question.addActionListener(this);
enter.addActionListener(this);
}
if(count == 7)
{
finish1 = new Label("Thank You." , Label.CENTER);
finish1.setFont(new Font("Times-Roman", Font.BOLD, 50));
finish2 = new Label("Questionnaire Completed.", Label.CENTER);
finish2.setFont(new Font("Times-Roman", Font.BOLD, 50));
add(finish1);
add(finish2);
finish1.setBounds(0,200,800,60);
finish2.setBounds(0,300,800,60);
}
}
public void actionPerformed(ActionEvent ae)
{
String button = ae.getActionCommand();
text = question.getText();
b = 0;
c = 0;
if (count == 6)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qsix1);
remove(qsix2);
remove(qsix3);
remove(qsix4);
remove(qsix5);
remove(qsix6);
remove(qsix7);
remove(qsix8);
remove(qsix9);
remove(qsix10);
remove(qsix11);
remove(qsix12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("OL"))
{
b = 1;
count = 7;
init();
}
else
{
b = 2;
count = 7;
init();
}
}
if (count == 5)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qfive1);
remove(qfive2);
remove(qfive3);
remove(qfive4);
remove(qfive5);
remove(qfive6);
remove(qfive7);
remove(qfive8);
remove(qfive9);
remove(qfive10);
remove(qfive11);
remove(qfive12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("BR"))
{
b = 1;
count = 6;
init();
}
else
{
b = 2;
count = 6;
init();
}
}
if (count == 4)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qfour1);
remove(qfour2);
remove(qfour3);
remove(qfour4);
remove(qfour5);
remove(qfour6);
remove(qfour7);
remove(qfour8);
remove(qfour9);
remove(qfour10);
remove(qfour11);
remove(qfour12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("no"))
{
b = 1;
count = 5;
init();
}
else
{
b = 2;
count = 5;
init();
}
}
if (count == 3)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qthree1);
remove(qthree2);
remove(qthree3);
remove(qthree4);
remove(qthree5);
remove(qthree6);
remove(qthree7);
remove(qthree8);
remove(qthree9);
remove(qthree10);
remove(qthree11);
remove(qthree12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("black"))
{
b = 1;
count = 4;
init();
}
else
{
b = 2;
count = 4;
init();
}
}
if (count == 2)
{
input = text.toLowerCase();
remove(enter);
remove(question);
question.setText("");
remove(qtwo1);
remove(qtwo2);
remove(qtwo3);
remove(qtwo4);
remove(qtwo5);
remove(qtwo6);
remove(qtwo7);
remove(qtwo8);
remove(qtwo9);
remove(qtwo10);
remove(qtwo11);
remove(qtwo12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("yes"))
{
b = 1;
count = 3;
init();
}
else
{
b = 2;
count = 3;
init();
}
}
if (count == 1)
{
input = text.toUpperCase();
remove(enter);
remove(question);
question.setText("");
remove(qone1);
remove(qone2);
remove(qone3);
remove(qone4);
remove(qone5);
remove(qone6);
remove(qone7);
remove(qone8);
remove(qone9);
remove(qone10);
remove(qone11);
remove(qone12);
try{
FileWriter fstream = new FileWriter("lets3.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(new String(input));
out.write("\n");
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
if(input.equals("i"))
{
b = 1;
count = 2;
init();
}
else
{
b = 1;
count = 2;
init();
}
}
if (count == 0)
{
remove(intro1);
remove(intro2);
remove(intro3);
remove(start);
count = 1;
init();
}
this.validate();
}
}
In all honesty, you need to re-write your program from scratch so that you can incorporate OOP techniques, arrays, collections, and other advantages that Java has to offer. I recommend:
First of all since your code displays a series of questions and prompts for response, don't hard-code the questions in the code but make them part of the data. Have your program read in a text file that holds the questions. This will allow you to change questions or add questions without altering code.
Create a non-GUI Question class that holds questions and user responses and that is used by the GUI as its "model".
Create an ArrayList of Question objects.
For your GUI, code to the JPanel, not the applet or the JFrame. This will give you the option of using your GUI in a JFrame or a JApplet, or even a JDialog or embedded in another JPanel should you so desire.
If you will need to swap display panels, consider using CardLayout for this purpose.
If however all you'll be doing is changing the text of the question, then display the question text in a JLabel and when you want to change it, call setText(...) on the JLabel passing in the new question's text.
Use the user-friendly layout managers to ease your work of laying out components in the GUI.
Your current code has a lot of unnecessary redundencies. Use of arrays and collections such as ArrayLists will remove many of these redudancies and make debugging and upgrading much easier.
As others have stated and as I stated in my earlier comment, you should move up to the Swing library as it is much more flexible and robust than the AWT gui library that you are currently using. The Swing tutorials will show you what you need to know to create beautiful Swing programs.
Just add a main() method, make a Frame for your applet, add the applet to the frame, and call the applet's init() and start() methods. See my Mandelbrot.java for an example: http://unixshell.jcomeau.com/src/java/com/jcomeau/Mandelbrot.java
One advantage of this approach is that it can be used with any existing applet, to allow it to function as either an applet or application. Use a JFrame if you're using Swing components, otherwise it should work pretty nearly the same.
In general, you'll want to change all the non swing components to swing components. For events, they're roughly the same for both applets and swing applications. Hope it helps.
I'm not sure what you are asking, but if you want it inside a window all you need to do is this:
public Object[] startNewSurvey()
{
java.awt.Frame f = new java.awt.Frame("You're title here.");
f.setSize(new Dimension(<Width>, <Height>));
f.setResizable(false);
survey s = new survey();
s.init();
f.add(s);
f.setVisible(true);
return new Object[] { f, s };
}
That will just instance a brand new frame and put another new instance of your survey class in that frame, then display it. It also returns a 2 sized Object[] array containing the new Frame and survey instances made. Hope that helps.
https://way2java.com/applets/applet-to-application/
Following are the changes to be made from Applet to Application
Delete the statement "import java.applet" package
Replace extends Applet with Frame
Replace the init() method with constructor
Check the layout (for Applet, the default layout is FlowLayout and for Frame, it is BorderLayout)
Add setXXX() methods like setSize() etc.
Add the main() method
HTML is not required (delete it)

How To Keep Size Of JTextArea constant?

I'm using an object of JTextArea in my application which deals with sending sms.
I've used a DocumentFilter so as to allow only 160 characters to be typed in the textarea but now, I want the size of the textarea to be constant. it goes on increasing if I keep writing on the same line without pressing 'enter' key or even when I keep on pressing only Enter key. I tried once using 'scrollbar' too but the problem remains same. Suggest me something over this. Below is my code. Please check it.
class Send_sms extends JPanel implements ActionListener,DocumentListener
{
JButton send;
JTextArea smst;
JLabel title,limit;
JPanel mainp,titlep,sendp,wrap,titlewrap,blankp1,blankp2,sendwrap;
JScrollPane scroll;
Border br,blackbr;
Boolean flag = false;
PlainDocument plane;
public static final int LINES = 4;
public static final int CHAR_PER_LINE = 40;
//character limit 160 for a sms
public Send_sms()
{
br = BorderFactory.createLineBorder(Color.RED);
blackbr = BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.DARK_GRAY,Color.GRAY);
setBorder(blackbr);
title = new JLabel("Enter the text you want to send!");
title.setFont(new Font("",Font.BOLD,17));
limit = new JLabel(""+charCount+" Characters");
smst = new JTextArea(LINES,CHAR_PER_LINE);
smst.setSize(100,100);
plane = (PlainDocument)smst.getDocument();
//adding DocumentSizeFilter 2 keep track of characters entered
plane.setDocumentFilter(new DocumentSizeFilter(charCount));
plane.addDocumentListener(this);
send = new JButton("Send");
send.setToolTipText("Click Here To Send SMS");
send.addActionListener(this);
//scroll = new JScrollPane(smst);
//scroll.setPreferredSize(new Dimension(200,200));
//scroll.setVerticalScrollBarPolicy(null);
//scroll.setHorizontalScrollBarPolicy(null);
smst.setBorder(br);
blankp1 = new JPanel();
blankp2 = new JPanel();
titlep = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlewrap = new JPanel(new GridLayout(2,1));
mainp = new JPanel(new BorderLayout());
sendwrap = new JPanel(new GridLayout(3,1));
sendp = new JPanel(new FlowLayout(FlowLayout.CENTER));
wrap = new JPanel(new BorderLayout());
titlep.add(title);
titlewrap.add(titlep);
titlewrap.add(blankp1);
sendp.add(send);
sendwrap.add(limit);
sendwrap.add(blankp2);
sendwrap.add(sendp);
wrap.add(smst,BorderLayout.CENTER);
mainp.add(titlewrap,BorderLayout.NORTH);
mainp.add(wrap,BorderLayout.CENTER);
mainp.add(sendwrap,BorderLayout.SOUTH);
add(mainp);
}
public void actionPerformed(ActionEvent e)
{
Vector<Vector<String>> info = new Vector<Vector<String>> ();
Vector<String> numbers = new Vector<String>();
if(e.getSource() == send)
{
//Call a function to send he message to all the clients using text
//charCount = 165;
String msg = smst.getText();
if(msg.length() == 0)
JOptionPane.showMessageDialog(null,"Please Enter Message","Error",JOptionPane.ERROR_MESSAGE);
else
{
// System.out.println("Message:"+msg);
Viewdata frame = new Viewdata(msg);
limit.setText(""+charCount+" Characters");
charCount = 160;
}
}
}
public void insertUpdate(DocumentEvent e)
{
System.out.println("The legth:(insert) "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
if(charCount >0)
charCount--;
else
break;
}
limit.setText(""+charCount+" Characters");
}
public void removeUpdate(DocumentEvent e)
{
//System.out.println("The legth(remove): "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
charCount++;
}
limit.setText(""+charCount+" Characters");
}
public void changedUpdate(DocumentEvent e)
{
//System.out.println("The legth(change): "+e.getLength());
}
}//end Send_sms
Sound like you are creating the text area using
JTextArea textArea = new JTextArea();
When using this format the text area doesn't have a preferred size so it keeps on growing. If you use:
JTextArea textArea = new JTextArea(2, 30);
JScrollPane scrollPane = new JScrollPane( textArea );
Then the text area will have a preferred size of 2 rows and (roughly) 30 columns. As you type when you exceed the preferred width the horizontal scrollbar will appear. Or if you turn on wrapping, then the text will wrap and a vertical scrollbar will appear.
you need to specify:
textArea.setColumns (160);
textArea.setLineWrap (true);
textArea.setWrapStyleWord (false); //default
But the real problem is that you allow to input more than 160 characters. You need to create some kind of validator which will skip all inputed characters when there are already 160 characters written.
Initialise the textArea with a document that extends PlainDocument and in the insertString method limit the characters to 160

Categories

Resources