1

Here is what my program is suppose to look like:

Program Example

but I can't seem to get my radio buttons and my JLabel to be aligned properly. How do I align my radio buttons on the right and stacked? Also, how do I get my JLabel and JTextField to show stacked? Here is my code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SeriesCalc extends JFrame {

private final int WIDTH = 300;
private final int HEIGHT = 300;
private JFrame frame = new JFrame("Recursion");
private JPanel panel = new JPanel();
private JPanel labels = new JPanel();
private JPanel buttons = new JPanel();
private JPanel radioButtonsPanel = new JPanel();
private JLabel inputLabel = new JLabel("Enter i:");
private JLabel resultLabel = new JLabel("Result:");
private JTextField inputField = new JTextField(15);
private JTextField resultField = new JTextField(15);
private JButton compute = new JButton("Compute");
private JRadioButton iterative, recursive;

public SeriesCalc() {
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    radioButtonsPanel.add(iterative = new JRadioButton("Iterative"));
    radioButtonsPanel.add(recursive = new JRadioButton("Recursive"));
    add(radioButtonsPanel);
    ButtonGroup radioButtons = new ButtonGroup();
    radioButtons.add(iterative);
    radioButtons.add(recursive);

    iterative.addActionListener(new Calculations());
    recursive.addActionListener(new Calculations());
    compute.addActionListener(new Calculations());

    resultField.setEditable(false);

    panel.setLayout(new GridLayout(4, 1));
    labels.add(inputLabel);
    labels.add(inputField);
    labels.add(resultLabel);
    labels.add(resultField);
    buttons.add(compute);
    panel.add(radioButtonsPanel);
    panel.add(labels);
    panel.add(buttons);
    frame.getContentPane().add(panel);
}

public void display() {
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
}

public class Calculations implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        Object calc = e.getSource();
        try {
            if (calc == compute) {
                if (iterative.isSelected()) {
                    double n = Double.parseDouble(inputField.getText());
                    double product = 1;
                    for (int i = 3; i < n; i++) {
                        product *= i;
                    }
                    resultField.setText(Double.toString(product));
                } else if (recursive.isSelected()) {
                    double i = Double.parseDouble(inputField.getText());
                    double y = 0;
                    if (i == 1) {
                resultField.setText(Double.toString(i / (2. * i +     1)));
                    } else {
             resultField.setText(Double.toString(i / (2. * i + 1)+ (i -1)));
                    }
                }
            }
        } catch (NumberFormatException nfe) {
            System.err.println(nfe.getMessage());
        }
    }
}

public static void main(String[] args) {
    SeriesCalc calculator = new SeriesCalc();
    calculator.display();
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

2

I see some errors in your program:

  1. You're extending JFrame and creating an instance of it in the same program. Use one or the other (I recommend the latter), See Using extends vs calling it inside of class.

  2. You're setting frame.setSize() while this isn't an error it's always better to call frame.pack() in your program. It will respect the minimum size where all the components are shown in their preferredSizes. If you need an exact size for your window override getPreferredSize() method instead.

  3. You're not placing your program on the Event Dispatch Thread (EDT), this could cause threading issues in the future as Swing is not thread safe, this can be solved with:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Call your constructor here
            }
        });
    }
    

but I can't seem to get my radio buttons and my JLabel to be aligned properly

This is because a JPanel's default layout manager is FlowLayout and thus it will place your components in a single row.

My idea to get to your desired GUI was to use a single GridLayout with 0 rows (it will add as many as needed) and 2 columns, and where you need a "blank" space you can add empty JLabels.

I didn't placed an ActionListener on my code as this question is about the GUI design not the logic inside it.

I think I'm not missing anything, this is the output that the below code creates:

enter image description here

import java.awt.GridLayout;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class SeriesCalc {

    private JFrame frame;

    private JRadioButton iterative;
    private JRadioButton recursive;
    private ButtonGroup group;

    private JLabel label;
    private JLabel resultLabel;

    private JTextField field;
    private JTextField resultField;

    private JButton computeButton;

    private JPanel pane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SeriesCalc().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        pane = new JPanel();
        pane.setLayout(new GridLayout(0, 2, 2, 5));

        iterative = new JRadioButton("Iterative");
        recursive = new JRadioButton("Recursive");

        group = new ButtonGroup();

        group.add(iterative);
        group.add(recursive);

        computeButton = new JButton("Compute");

        label = new JLabel("Enter \"i\": ");
        resultLabel = new JLabel("Result: ");

        field = new JTextField(5);
        resultField = new JTextField(5);
        resultField.setEnabled(false);

        pane.add(new JLabel(""));
        pane.add(iterative);

        pane.add(new JLabel(""));
        pane.add(recursive);

        pane.add(label);
        pane.add(field);

        pane.add(new JLabel(""));
        pane.add(computeButton);

        pane.add(resultLabel);
        pane.add(resultField);

        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
-1

I don´t know if you are using an IDE like Eclipse or NetBeans. In Eclipse for example, you can open this class with windowbuilder and you could visualize how your Frame will appear. Obviously you can move element in this view (window builder) and put all objects where you want and the size you want. In the next image you could see the view of an edit of a Frame if you open it with window builder in mode design in Eclipse. In this mode (design) you can put absolute layout to these objects and they can be put where you want with that layout. I recommend you to use an IDE like eclipse for Java Developing, it is very useful and it has a lot of facilities. I hope I could help you: enter image description here enter image description here

enter image description here

enter image description here

  • This project does not allow me to use the GUI in NetBeans, I am to use java.awt – beginnerDeveloper Feb 08 '17 at 19:34
  • IF you are to use AWT (a bad idea - it has been obsolete for decades), the why are you using Swing instead> – FredK Feb 08 '17 at 19:37
  • What I understand is that you want to setBounds of the JLabels and Radio Buttons, well you could do that with the next code: inputLabel.setBounds(17, 24, 386, 16); This way you can align manually all objects of the frame. Obviously this is much more work and difficult than using a window builder, but it could be a solution. – uheredero001 Feb 08 '17 at 19:43
  • My professor is asking us to use AWT and javax.swing. I'm a bit confused on the subject currently. – beginnerDeveloper Feb 08 '17 at 19:44
  • 2
    @uheredero001 Using a null layout is almost always a bad idea; since you may not know the default insets of all components, it can make it very difficult to layout components properly,and will lead to nightmares if you ever want to change fonts, etc. Best to use the proper layout manager in the first place. – FredK Feb 08 '17 at 19:49
  • I agree with you @FredK but I was trying to give a solution, obviously that is a bad solution, but the only one I´ve got for this case. – uheredero001 Feb 08 '17 at 19:52
  • @uheredero001 for some reason, adding that code didn't change my outcome... – beginnerDeveloper Feb 08 '17 at 19:53
  • 1
    I strongly agree with @FredK: Absolute Layout / Null Layout are the same, please stop suggesting its use. See [Null layout is evil](http://www.leepoint.net/GUI/layouts/nulllayout.html) and [Why is it frowned upon to use a null layout?](http://stackoverflow.com/questions/6592468/why-is-it-frowned-upon-to-use-a-null-layout-in-swing). Also your code should be in a code-formatted text inside your answer not in an image. OP can't copy-paste the code inside it... – Frakcool Feb 08 '17 at 20:28
  • 1
    ... *"obviously that is a bad solution"* Please stop giving "bad solutions" until you learn to use the [Layout managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) first – Frakcool Feb 08 '17 at 20:28
  • @pCaMp *"My professor is asking us to use AWT and javax.swing"* - But you're using Swing components? – MadProgrammer Feb 08 '17 at 20:32