How To Keep Size Of JTextArea constant? - java

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

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

Strings not being, correctly, written to JTextField/Area on selection of row in JList

I'm using a vector to store the information displayed in the JList and I want to use the index of the selected index to copy the data of that row into the JTextField and JTextArea. I am having some issues where the selected item isn't be shown in the JTextField/Area but instead showing the data of a previous selected index. Every second index has an issue of showing the wrong data, 2, 4, 6, 8, 10 and then 11. Each of them will only show the right data if you select first when the program has just been executed. The print lines that I have added to the ListSelectionEvent listener shows the correct data of the selected index but it doesn't correctly copy it into the JTextArea/JTextField.
Selected right after the program was executed.
I selected a few other indices then tried to select it again
code:
public class EditFlashcardGui implements ListSelectionListener {
private JFrame frame;
private JPanel listPanel;
private Vector<Vector> flashcardMasterVector = new Vector<Vector>();
private JList list;
private JPanel tablePanel, dataPanel, textFieldPanel;
private JButton submitButton, cancelButton;
private JTextField frontTextField;
private JTextArea reverseTextArea;
private GridBagLayout gridBagLayout;
private GridBagConstraints constraints;
private JLabel frontTextLabel, reverseTextLabel;
Vector<Vector> masterVector = new Vector<Vector>();
public EditFlashcardGui() {
frame = new JFrame("Edit / Delete Flashcards");
frame.setSize(500, 200);
Container con = frame.getContentPane();
con.setLayout(new BorderLayout());
listPanel = new JPanel(new BorderLayout());
Vector<String> columnNames = new Vector<String>();
columnNames.add("id");
columnNames.add("front text");
columnNames.add("reverse text");
list = new JList(populateList());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(this);
Font font1 = new Font("SansSerif", Font.BOLD, 20);
list.setFont(font1);
tablePanel = new JPanel();
tablePanel.add(list);
JScrollPane scrollPane = new JScrollPane(list);
con.add(scrollPane, BorderLayout.NORTH);
// south panel
gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
textFieldPanel = new JPanel(gridBagLayout);
// cancelButton = new JButton("Cancel");
// dataPanel.add(cancelButton, BorderLayout.SOUTH);
frontTextLabel = new JLabel("Front Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 0;
gridBagLayout.setConstraints(frontTextLabel, constraints);
textFieldPanel.add(frontTextLabel);
frontTextField = new JTextField();
frontTextField.setColumns(30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 1;
gridBagLayout.setConstraints(frontTextField, constraints);
textFieldPanel.add(frontTextField);
reverseTextLabel = new JLabel("Reverse Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 2;
gridBagLayout.setConstraints(reverseTextLabel, constraints);
textFieldPanel.add(reverseTextLabel);
reverseTextArea = new JTextArea(3, 30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 3;
gridBagLayout.setConstraints(reverseTextArea, constraints);
textFieldPanel.add(reverseTextArea);
submitButton = new JButton("Submit");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 4;
gridBagLayout.setConstraints(submitButton, constraints);
textFieldPanel.add(submitButton);
con.add(textFieldPanel, BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public Vector<Vector> populateList() {
//flashcardMasterVector = flashcardDB.getList();
//Vector<String> flashcardVector = new Vector<String>();
Integer temp = 0;
for(int i = 0; i <= 20; i++) {
Vector<String> flashcardVector = new Vector<String>();
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
masterVector.add(i, flashcardVector);
temp++;
}
return masterVector;
}
public static void main(String[] args) {
EditFlashcardGui gui = new EditFlashcardGui();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (! e.getValueIsAdjusting())
{
System.out.print("id : " );
System.out.println(masterVector.get(list.getSelectedIndex()).get(0));
System.out.print("front text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(1));
frontTextField.setText(masterVector.get(e.getFirstIndex())
.get(1).toString());
System.out.print("reverse text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(2));
reverseTextArea.setText(masterVector.get(e.getFirstIndex())
.get(2).toString());
}
}
}
have to read Oracles tutorial about How to Use JList
you can't put Vector<Vector> to the JList directly,
put value and to use XxxListModel only, but in this case have to create crazy workaround for AbstractListModel, use simple array instead
JList is based on one dimensional array have to use Vector<Object (or String or Double...)>
don't complicate simple things put this array to the JTable (to the XxxTableModel), remove all synchronizations columns, remove JTableHeader if required, then output to the GUI looks like as JList
JTable.removeColumn remove only column from view, all data are still presented and stored into XxxTableModel without any changes
then selected (have to test for -1 == none of row is selected) row (have to convertViewToModel in the case that JTable is sorted or filtered) returns all required data from XxxTableModel
Use list.getSelectedIndex() instead of e.getFirstIndex() method.
Code :
frontTextField.setText( masterVector.get(list.getSelectedIndex() ).get(1).toString() );
reverseTextArea.setText(masterVector.get( list.getSelectedIndex()).get(2).toString() );
Clean Code:
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
Vector masterVec = masterVector.get( list.getSelectedIndex() );
System.out.print("id : ");
System.out.println(masterVec.get(0));
System.out.print("front text : ");
System.out.println(masterVec.get(1));
System.out.print("reverse text : ");
System.out.println(masterVec.get(2));
frontTextField.setText(masterVec.get(1).toString());
reverseTextArea.setText(masterVec.get(2).toString());;
}
}

How to get rid of spaces in the string of my Calc program

I was wondering how I would be able to account for spaces in my Calculator program. Right now it is set up to only work if there is a space after every value. I want it to be able to work if there is multiple spaces as well. I tried doing something (in my action performed, under the '=' sign test), but it didn't really work. So wanted to know how I could make it account for multiple spaces (like if there are more than one space before the next value, then it should recognize that that is the case, and delete the extra spaces). Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
int counter = 0;
if (text.equals("="))
{
doMath math = new doMath();
for(int i = 0; i <b.length(); i++)
{
String c = b.substring(i,(i+1));
String d = b.substring((i+1),(i+2));
String temp = "";
if( c.equals(" ") && c.equals(d))
{
temp = b.substring(0,i)+(b.substring(i+1));
b = temp;
}
}
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
counter ++;
if(counter <2)
{
b+= " ";
display.setText(b);
}
else
{
b+="";
display.setText(b);
}
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
counter = 0;
}
}
This method requires knowledge of regular expressions. For each string, simply replace any instance of multiple consecutive spaces with a single space. In other words, using regular expressions, you would replace "\\s+", which means "more than one space," with " ", which is just the space character.
Example:
String c = ...
c = c.replaceAll("\\s+", " ");
String str = "your string";
Pattern _pattern = Pattern.compile("\\s+");
Matcher matcher = _pattern.matcher(str);
str = matcher.replaceAll(" ");
Instead of using a substring, use a Scanner which takes a String as a parameter.
Or you can disable the "Space" button after it's pressed, enabling it back, when a different button is pressed.
If b is not empty you could try looking at the previous character using charAt and if it is a space do nothing.

Categories

Resources