Every time I click the radio button for in2cm and try to convert, there is nothing showing when I click the convert button. If possible also show me how to use a list box, so I will just put it on a list box and make the GUI much more easier to use.
ButtonGroup convertgroup=new ButtonGroup();
jr=new JRadioButton[10];
jr[0]=new JRadioButton("Inch to Cm");
l1 = new JTextField(25);
l2 = new JTextField(25);
length1 = new JLabel("ft", SwingConstants.LEFT);
length2 = new JLabel("cm", SwingConstants.LEFT);
convertgroup.add(jr[0]);
jr[1]=new JRadioButton("Meter to Feet");
length = new JLabel("m = ", SwingConstants.LEFT);
l1 = new JTextField(25);
l2 = new JTextField(25);
length1 = new JLabel("ft", SwingConstants.LEFT);
length2 = new JLabel("cm", SwingConstants.LEFT);
convertgroup.add(jr[1]);
jr[2]=new JRadioButton("Mile to Km");
Mi2Km = new JTextField(25);
Km2Mi = new JTextField(25);
length3 = new JLabel("Mile", SwingConstants.LEFT);
length4 = new JLabel("Km", SwingConstants.LEFT);
convertgroup.add(jr[2]);
jr[3]=new JRadioButton("Nautical Mile to Km");
Nmi2Km= new JTextField(25);
Km2Nmi= new JTextField(25);
jr[4]=new JRadioButton("League to Km");
Le2Km = new JTextField(25);
Km2Le = new JTextField(25);
submit = new JButton("Convert");
clear = new JButton("Clear");
quit = new JButton("Quit");
submit.addActionListener(this);
clear.addActionListener(this);
quit.addActionListener(this);
converterPanel.add(jr[0]);
converterPanel.add(jr[2]);
converterPanel.add(jr[1]);
converterPanel.add(l1);
converterPanel.add(length);
converterPanel.add(l2);
converterPanel.add(length1);
converterPanel.add(jr[3]);
converterPanel.add(jr[4]);
converterPanel.add(submit);
converterPanel.add(clear);
converterPanel.add(quit);
length.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
Here is the action performed:
public void actionPerformed(ActionEvent event) {
if (event.getSource() == quit) {
System.exit(0);
}
if (event.getSource() == clear) {
l1.setText("");
l2.setText("");
}
if (event.getSource()== submit) {
if(!jr[0].isSelected() && !jr[1].isSelected() && !jr[2].isSelected())
JOptionPane.showMessageDialog(converterFrame,
"No RadioButton has been Selected ", "Warning",
JOptionPane.WARNING_MESSAGE);
if(jr[0].isSelected())
in2cm();
if(jr[1].isSelected()){
lengthConvert();
return;
}
}
}
I have found the problem and fixed it, but how can i change the jlabel every time the jr[0] is selected? because the jlabel in jr[1] is m and feet, and in jr[0] i need to make it in and cm.
Related
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.
I'm trying to set up the frame for a pizza order form, and I'm having trouble with the orderPanel and the buttonsPanel. I can either make one or the other show up, but not both? In this current code I'm posting, the buttons are showing, but the textbox/orderPanel isn't. And I've gotten it so the orderPanel DOES show, but then it hides the buttons, which is also not good. I want the buttons at the very bottom and the orderPanel right above it; how can I do that?
class PizzaOrderFrame extends JFrame
{
final private JPanel crustPanel, sizePanel, toppingsPanel, orderPanel, buttonsPanel;
final private TitledBorder crustBorder, sizeBorder, toppingsBorder, orderBorder;
final private JButton quitButton, clearButton, orderButton;
final private JTextArea orderTextArea;
final private JRadioButton thin, regular, deepDish;
final private JCheckBox pepperoni, sausage, bacon, extraCheese, olives, mushrooms;
double smallSizeCost = 8.0;
double mediumSizeCost = 12.0;
double largeSizeCost = 16.0;
double superSizeCost = 20.0;
double toppingsCost = 1.0;
double toppingsCount = 0;
double tax = 0.07;
double orderSubTotal = 0;
double orderTotal = 0;
public PizzaOrderFrame()
{
setTitle("Pizza Order Form");
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
double setScreen = screenWidth * .80;
double setScreen3 = screenHeight * .80;
int setScreen2 = (int) setScreen;
int setScreen4 = (int) setScreen3;
setSize(setScreen2, setScreen4);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
crustPanel = new JPanel();
crustBorder = new TitledBorder("Select your crust");
crustBorder.setTitleJustification(TitledBorder.CENTER);
crustBorder.setTitlePosition(TitledBorder.TOP);
crustPanel.setBorder(crustBorder);
thin = new JRadioButton("Thin");
regular = new JRadioButton("Regular");
deepDish = new JRadioButton("Deep-Dish");
ButtonGroup group = new ButtonGroup();
group.add(thin);
group.add(regular);
group.add(deepDish);
crustPanel.add(thin);
crustPanel.add(regular);
crustPanel.add(deepDish);
add(crustPanel, BorderLayout.WEST);
sizePanel = new JPanel();
sizeBorder = new TitledBorder("Select your size");
sizeBorder.setTitleJustification(TitledBorder.CENTER);
sizeBorder.setTitlePosition(TitledBorder.TOP);
sizePanel.setBorder(sizeBorder);
String[] sizeOptions = new String [] {"Small", "Medium", "Large", "Super" };
JComboBox<String> size = new JComboBox<>(sizeOptions);
String selectedSize = (String) size.getSelectedItem();
sizePanel.add(size);
add(sizePanel, BorderLayout.CENTER);
toppingsPanel = new JPanel();
toppingsBorder = new TitledBorder("Select your toppings");
toppingsBorder.setTitleJustification(TitledBorder.CENTER);
toppingsBorder.setTitlePosition(TitledBorder.TOP);
toppingsPanel.setBorder(toppingsBorder);
pepperoni = new JCheckBox("Pepperoni");
sausage = new JCheckBox("Sausage");
extraCheese = new JCheckBox("Extra Cheese");
mushrooms = new JCheckBox("Mushrooms");
olives = new JCheckBox("Olives");
bacon = new JCheckBox("Bacon");
toppingsPanel.add(pepperoni);
toppingsPanel.add(sausage);
toppingsPanel.add(extraCheese);
toppingsPanel.add(mushrooms);
toppingsPanel.add(olives);
toppingsPanel.add(bacon);
add(toppingsPanel, BorderLayout.EAST);
orderPanel = new JPanel();
orderBorder = new TitledBorder("Your Order");
orderBorder.setTitleJustification(TitledBorder.CENTER);
orderBorder.setTitlePosition(TitledBorder.TOP);
orderPanel.setBorder(orderBorder);
orderTextArea = new JTextArea();
JScrollPane orderSP = new JScrollPane(orderTextArea);
orderSP.setPreferredSize( new Dimension( 300, 100 ) );
orderPanel.add(orderSP);
add(orderPanel, BorderLayout.SOUTH);
buttonsPanel = new JPanel();
quitButton = new JButton("Quit");
clearButton = new JButton("Clear");
orderButton = new JButton("Order");
buttonsPanel.add(quitButton);
buttonsPanel.add(clearButton);
buttonsPanel.add(orderButton);
add(buttonsPanel, BorderLayout.PAGE_END);
}
}
According to the JavaDoc for PAGE_END
For Western, left-to-right and top-to-bottom orientations, this is equivalent to SOUTH.
BorderLayout "areas" can only contain one component, so if you call add() multiple times using the same "area", only the last one is shown.
One way to get the layout you want is by creating another Panel, give it a BorderLayout, add orderPanel to the new Panel's NORTH, buttonsPanel to the new Panel's SOUTH, and then add the new Panel to the existing pizzaOrderFrame's SOUTH.
When Eclipse compiles this code everything works fine except the GUI freezes after the user clicks the "add" button. The answer is displayed and the work is shown. Can anyone shine some light on this problem and maybe give me some advice for the layout as well?
import Aritmathic.MathEquation;
public class GUI extends JFrame implements ActionListener{
private JTextField field1;
private JTextField field2;
private JButton add, subtract, multiply, divide;
private JLabel lanswer, label1, label2;
private String input1, input2, sanswer;
private int answer = 0;
JPanel contentPanel, answerPanel;
public GUI(){
super("Calculator");
field1 = new JTextField(null, 15);
field2 = new JTextField(null, 15);
add = new JButton("add");
subtract = new JButton("subtract");
multiply = new JButton("multiply");
divide = new JButton("divide");
lanswer = new JLabel("", SwingConstants.CENTER);
label1 = new JLabel("Value 1:");
label2 = new JLabel("Value 2:");
add.addActionListener(this);
Dimension opSize = new Dimension(110, 20);
Dimension inSize = new Dimension(200, 20);
lanswer.setPreferredSize(new Dimension(200,255));
field1.setPreferredSize(inSize);
field2.setPreferredSize(inSize);
add.setPreferredSize(opSize);
subtract.setPreferredSize(opSize);
multiply.setPreferredSize(opSize);
divide.setPreferredSize(opSize);
contentPanel = new JPanel();
contentPanel.setBackground(Color.PINK);
contentPanel.setLayout(new FlowLayout());
answerPanel = new JPanel();
answerPanel.setPreferredSize(new Dimension(230, 260));
answerPanel.setBackground(Color.WHITE);
answerPanel.setLayout(new BoxLayout(answerPanel, BoxLayout.Y_AXIS));
contentPanel.add(answerPanel);
contentPanel.add(label1); contentPanel.add(field1);
contentPanel.add(label2); contentPanel.add(field2);
contentPanel.add(add); contentPanel.add(subtract); contentPanel.add(multiply); contentPanel.add(divide);
this.setContentPane(contentPanel);
}
public void actionPerformed(ActionEvent e) {
JButton src = (JButton)e.getSource();
if(src.equals(add)){
add();
}
}
private void add(){
input1 = field1.getText();
input2 = field2.getText();
MathEquation problem = new MathEquation(input1, input2);
Dimension lineSize = new Dimension(10, 10);
JPanel line1 = new JPanel(); line1.setBackground(Color.WHITE);
JPanel line2 = new JPanel(); line2.setBackground(Color.WHITE);
JPanel line3 = new JPanel(); line3.setBackground(Color.WHITE);
JPanel line4 = new JPanel(); line4.setBackground(Color.WHITE);
JPanel line5 = new JPanel(); line4.setBackground(Color.WHITE);
JLabel[] sumLabels = problem.getSumLabels();
JLabel[] addend1Labels = problem.getAddend1Labels();
JLabel[] addend2Labels = problem.getAddend2Labels();
JLabel[] carriedLabels = problem.getCarriedLabels();
for(int i = 0; i < carriedLabels.length; i++){
line1.add(carriedLabels[i]);
}
for(int i = 0; i < addend1Labels.length; i++){
line2.add(addend1Labels[i]);
}
for(int i = 0; i < addend2Labels.length; i++){
line3.add(addend2Labels[i]);
}
String answerLine = "__";
for(int i = 0; i < sumLabels.length; i++){
answerLine += "__";
}
line4.add(new JLabel(answerLine));
for(int i = 0; i < sumLabels.length; i++){
line5.add(sumLabels[i]);
}
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(line1);
answerPanel.add(line1);
answerPanel.add(line2);
answerPanel.add(line3);
answerPanel.add(line4);
answerPanel.add(line5);
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
this.setContentPane(answerPanel);
}
}
You have to revalidate your JFrame after you change the content pane.
After
this.setContentPane(answerPanel);
add
revalidate();
Java docs about revalidate()
Your add() method should now look like:
private void add(){
input1 = field1.getText();
input2 = field2.getText();
MathEquation problem = new MathEquation(input1, input2);
Dimension lineSize = new Dimension(10, 10);
JPanel line1 = new JPanel(); line1.setBackground(Color.WHITE);
JPanel line2 = new JPanel(); line2.setBackground(Color.WHITE);
JPanel line3 = new JPanel(); line3.setBackground(Color.WHITE);
JPanel line4 = new JPanel(); line4.setBackground(Color.WHITE);
JPanel line5 = new JPanel(); line4.setBackground(Color.WHITE);
JLabel[] sumLabels = problem.getSumLabels();
JLabel[] addend1Labels = problem.getAddend1Labels();
JLabel[] addend2Labels = problem.getAddend2Labels();
JLabel[] carriedLabels = problem.getCarriedLabels();
for(int i = 0; i < carriedLabels.length; i++){
line1.add(carriedLabels[i]);
}
for(int i = 0; i < addend1Labels.length; i++){
line2.add(addend1Labels[i]);
}
for(int i = 0; i < addend2Labels.length; i++){
line3.add(addend2Labels[i]);
}
String answerLine = "__";
for(int i = 0; i < sumLabels.length; i++){
answerLine += "__";
}
line4.add(new JLabel(answerLine));
for(int i = 0; i < sumLabels.length; i++){
line5.add(sumLabels[i]);
}
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(line1);
answerPanel.add(line1);
answerPanel.add(line2);
answerPanel.add(line3);
answerPanel.add(line4);
answerPanel.add(line5);
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
this.setContentPane(answerPanel);
this.revalidate();//
}
When I tested this it works. By works I mean did not freeze and set the content pane to the answerPanel.
I need help creating a Java swing form. The form is dynamically created and asks the user for various inputs. The inputs vary and could be Textfields, RadioButton, ComboBox. I'm trying to determine what is the best layout for such a form. Currently, I have something like:
JPanel pnlForm = new JPanel(new SpringLayout());
for (Parameter p : globals) {
JLabel lblName = new JLabel(p.getName() + ": ", JLabel.TRAILING);
pnlForm.add(lblName);
// The input field depends on parameter type
if (p.getType().equals("filename")) {
JPanel pnlFileChooser = new JPanel();
JTextArea txtArea = new JTextArea(p.getValue());
JButton btnFileChooser = new JButton("Browse");
pnlFileChooser.add(txtArea);
pnlFileChooser.add(btnFileChooser);
pnlForm.add(pnlFileChooser);
} else if (p.getType().equals("textbox")) {
JTextArea txtArea = new JTextArea(p.getValue());
pnlForm.add(txtArea);
} else if (p.getType().equals("checkbox")) {
// not yet implemented
} else if (p.getType().equals("radio")) {
ButtonGroup bgRadios = new ButtonGroup();
for(String option : p.getSelections()){
JRadioButton btnOption = new JRadioButton(option);
btnOption.setMnemonic(KeyEvent.VK_B);
btnOption.setActionCommand(option);
bgRadios.add(btnOption);
pnlForm.add(btnOption);
}
} else {
JLabel lblError = new JLabel("ERROR! Unknown type!" + p.getType());
lblName.setLabelFor(lblError);
pnlForm.add(lblError);
}
//Lay out the panel.
SpringUtilities.makeCompactGrid(pnlDetails,
globals.size() - 1, 2, //rows, cols
1, 1, //initX, initY
5, 5); //xPad, yPad
This is currently coming up very choppy (the radio buttons wont stay in the same area). Any thoughts on how I could make this layout better?
Thanks!
[edit]
Adding the following diagram as to what this may look like. The gray lines can be ignored, just there to show where a JPanel might be. Each row is dynamically generated based on some user input. How can I make a form that looks like this?
I ended up getting this working using the SpringLayout with two panels on each row. The left panel contains the label and the right contains the input field. This seems to work well:
for (Parameter p : params) {
// The label for this parameter
JLabel pname = new JLabel(p.getName() + ": ", JLabel.TRAILING);
// Setup the sub panels for this layout, aligned to point each other
JPanel pnlLeft = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel pnlRight = new JPanel(new FlowLayout(FlowLayout.LEFT));
// The value field for this parameter, depends on param type
if (p.getType().equals("filename")) {
JButton btnBrowse = new JButton("Browse");
btnBrowse.setActionCommand(pfilepath + p.getId());
btnBrowse.addActionListener(this);
JTextField pvalue = new JTextField(p.getValue(),50);
pnlRight.add(pvalue);
pnlRight.add(btnBrowse);
} else if (p.getType().equals("directory")) {
JButton btnBrowse = new JButton("Browse");
btnBrowse.setActionCommand(pdirpath + p.getId());
btnBrowse.addActionListener(this);
JTextField pvalue = new JTextField(p.getValue(),50);
pnlRight.add(pvalue);
pnlRight.add(btnBrowse);
} else if (p.getType().equals("textbox")) {
JTextField pvalue = new JTextField(p.getValue(),50);
pnlRight.add(pvalue);
} else if (p.getType().equals("checkbox")) {
for(String option : p.getSelections()){
JCheckBox chkbox = new JCheckBox(option);
if (p.getValue().contains(option)){
chkbox.setSelected(true);
}
chkbox.setName(p.getId() + "_" + option);
chkbox.setActionCommand(pchkbox + p.getId() + "_" + option);
chkbox.addActionListener(this);
pnlRight.add(chkbox);
}
} else if (p.getType().equals("radio")) {
ButtonGroup bgRadios = new ButtonGroup();
for(String option : p.getSelections()){
JRadioButton radio = new JRadioButton(option);
if (p.getValue().equals(option)){
radio.setSelected(true);
}
radio.setName(p.getId() + "_" + option);
radio.setActionCommand(pradio + p.getId() + "_" + option);
radio.addActionListener(this);
bgRadios.add(radio);
pnlRight.add(radio);
}
} else {
JTextField pvalue = new JTextField(p.getValue(),50);
pvalue.setText("ERROR! Invalid global parameter type!" + p.getType());
pvalue.setEditable(false);
pnlRight.add(pvalue);
}
// Add subpanels to this main panel and set labeling
pnlLeft.add(pname);
pname.setLabelFor(pnlRight);
add(pnlLeft);
add(pnlRight);
}
// Correctly setup SpringLayout grid for this main panel
SpringUtilities.makeCompactGrid(this,
params.size(), 2, //rows, cols
1, 1, //initX, initY
1, 1); //xPad, yPad
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.