Why is my first panel running twice? - java

I am working on my final project and we are making a quiz to find out what kind of parties people like... but I can't get mine to run sequentially and with this right panels!
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.*;
import javax.swing.ImageIcon;
import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JOptionPane;
import java.applet.Applet;
//This class is where we set up all the questions.
class party{
int num_questions = 10;
int panel_number = 0;
int party_score = 0;
JFrame frame = new JFrame();
String AnswerA;
String AnswerB;
String AnswerC;
String AnswerD;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
String target_word;
String user_text;
String label_text;
JLabel question_frame;
JPanel pane;
JPanel panel;
public void image_question(){
//This panel will display four images that the user will choose from.
panel = new JPanel();
panel.setLayout(new BorderLayout());
label_text = "Which party appeals to you the most?";
question_frame = new JLabel(label_text);
question_frame.setFont(new Font("Calibri", Font.PLAIN, 20));
panel.add(question_frame, BorderLayout.NORTH);
button1 = new JButton();
JPanel inner = new JPanel();
inner.setLayout(new GridLayout(0, 2));
button1.setIcon(new ImageIcon("ball.jpg")); //img1
button1.setPreferredSize(new Dimension(100, 100));
button1.setActionCommand("1");
inner.add(button1);
button2 = new JButton();
button2.setIcon(new ImageIcon("christmas_party.jpg"));
button2.setPreferredSize(new Dimension(100, 100));
button2.setActionCommand("2");
inner.add(button2);
button3 = new JButton();
button3.setIcon(new ImageIcon("college_party.jpg"));
button3.setPreferredSize(new Dimension(100, 100));
button3.setActionCommand("3");
inner.add(button3);
button4 = new JButton();
button4.setIcon(new ImageIcon("kid_party.jpg"));
button4.setPreferredSize(new Dimension(100, 100));
button4.setActionCommand("4");
inner.add(button4);
panel.add(inner, BorderLayout.CENTER);
//ImageIcon icon = new ImageIcon("Alex.jpg");
//frame.getContentPane().add(new JLabel(icon), BorderLayout.EAST);
//frame.setVisible(true);
frame.add(panel);
ActionListener al = new click();
button1.addActionListener(al);
button2.addActionListener(al);
button3.addActionListener(al);
button4.addActionListener(al);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setBackground(Color.white);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void multiple_choice_question(){
//This panel displays a 4 answer multiple choice question that they user will choose from.
pane = new JPanel();
pane.setLayout(new BorderLayout());
label_text = "What music would you prefer at a party?";
question_frame = new JLabel(label_text);
pane.add(question_frame, BorderLayout.NORTH);
JPanel center = new JPanel();
GridLayout grid = new GridLayout(0,2);
center.setLayout(grid);
pane.add(center, BorderLayout.CENTER);
AnswerA = "1";
AnswerB = "2";
AnswerC = "3";
AnswerD = "4";
ActionListener al = new click();
addAButton(AnswerA, center, al, "1");
addAButton(AnswerB, center, al, "2");
addAButton(AnswerC, center, al, "3");
addAButton(AnswerD, center, al, "4");
frame.add(pane);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void input_question(){
//This panel will display a question and chance for the user to input their answer.
user_text = JOptionPane.showInputDialog(null, "Describe your ideal party");
target_word = "music";
if (user_text.indexOf(target_word) >=0){
System.out.println("ho ho ho");
}
}
public void party() {
panel_number++;
if (panel_number == 1){
image_question();
}
if(panel_number == 2){
multiple_choice_question();
}
if(panel_number == 3){
input_question();
}
/* else if (panel_number == 4){
image_question();
}
else if(panel_number == 5){
multiple_choice_question();
}
else if(panel_number == 6){
input_question();
}*/
}
private static void addAButton(String text, Container container, ActionListener al, String actionCommand) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
container.add(button);
button.addActionListener(al);
button.setActionCommand(actionCommand);
}
public static void main(String args[]) {
party myGUI = new party();
myGUI.party();
}
class ClassParty{
//This class will read txt documents created by users and suggest a party that everyone would enjoy!
}
class click implements ActionListener{
public void actionPerformed(ActionEvent event){
party partier = new party();
if (event.getActionCommand().equals("1")){
party_score++;
}
else if (event.getActionCommand().equals("2")){
party_score++;
}
else if (event.getActionCommand().equals("3")){
party_score++;
}
else if (event.getActionCommand().equals("4")){
party_score++;
}
System.out.println(panel_number);
frame.dispose();
party();
//System.out.println(party_score);
/* creates a GUI that presents the user with a question with clickable answers that gives you the next question
when you finish answering. It plays jeapordy theme music and has a picture Alex Trabeck. It has a status bar
that tells you how close you are to finishing the program. */
}
}
}
When I run my code it runs the image_question twice and then runs input_question and quits. I can't get the multiple_choice_question to work.

I fixed it using debug and stepping through each command. Debug works great, you should try it. Debug was key because it showed that multiple_choice_question() was actually getting reached, even though the GUI looked like the first GUI. It narrowed down the source of the bug.
public void multiple_choice_question(){
frame=new JFrame(); <----add this and everything seems to be working
pane = new JPanel();
pane.setLayout(new BorderLayout());
label_text = "What music would you prefer at a party?";
...

Related

Why can't I add buttons to my GridLayout JPanel?

I am trying to add 24 JButtons to the GridLayout of my JPanel buttonPanel, but when I run it, I see that no buttons are added. (At least, they are not visible!). I tried giving the buttonPanel a background color, and it
was visible.
Does anyone know what I'm doing wrong?
This is my code (there is an other class):
package com.Egg;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class NormalCalc implements ActionListener {
static JPanel normalCalcPanel = new JPanel();
JPanel buttonPanel = new JPanel(new GridLayout(6,4,10,10));
Font font = new Font("Monospaced Bold", Font.BOLD, 18);
JButton powB = new JButton("^");
JButton sqrtB = new JButton("sqrt(");
JButton hOpenB = new JButton("(");
JButton hCloseB = new JButton(")");
JButton delB = new JButton("DEL");
JButton acB = new JButton("AC");
JButton mulB = new JButton("*");
JButton divB = new JButton("/");
JButton addB = new JButton("+");
JButton minB = new JButton("-");
JButton decB = new JButton(".");
JButton equB = new JButton("=");
JButton negB = new JButton("(-)");
JButton[] numberButtons = new JButton[10];
JButton[] functionButtons = new JButton[13];
public NormalCalc() {
functionButtons[0] = powB;
functionButtons[1] = delB;
functionButtons[2] = acB;
functionButtons[3] = sqrtB;
functionButtons[4] = mulB;
functionButtons[5] = divB;
functionButtons[6] = hOpenB;
functionButtons[7] = addB;
functionButtons[8] = minB;
functionButtons[9] = hCloseB;
functionButtons[10] = decB;
functionButtons[11] = negB;
functionButtons[12] = equB;
for (int i=0; i<10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].setFocusable(false);
numberButtons[i].setFont(font);
numberButtons[i].addActionListener(this);
}
for (int i=0; i <13; i++) {
functionButtons[i].setFocusable(false);
functionButtons[i].setFont(font);
functionButtons[i].addActionListener(this);
}
normalCalcPanel.setBounds(0, 0, 500, 700);
buttonPanel.setBounds(50, 200, 400, 400);
// Adding the buttons;
buttonPanel.add(functionButtons[0]);
buttonPanel.add(numberButtons[7]);
buttonPanel.add(numberButtons[8]);
buttonPanel.add(numberButtons[9]);
buttonPanel.add(functionButtons[1]);
buttonPanel.add(functionButtons[2]);
buttonPanel.add(functionButtons[3]);
buttonPanel.add(numberButtons[4]);
buttonPanel.add(numberButtons[5]);
buttonPanel.add(numberButtons[6]);
buttonPanel.add(functionButtons[4]);
buttonPanel.add(functionButtons[5]);
buttonPanel.add(functionButtons[6]);
buttonPanel.add(numberButtons[1]);
buttonPanel.add(numberButtons[2]);
buttonPanel.add(numberButtons[3]);
buttonPanel.add(functionButtons[7]);
buttonPanel.add(functionButtons[8]);
buttonPanel.add(functionButtons[9]);
buttonPanel.add(numberButtons[0]);
buttonPanel.add(functionButtons[10]);
buttonPanel.add(functionButtons[11]);
buttonPanel.add(functionButtons[12]);
buttonPanel.repaint();
normalCalcPanel.add(buttonPanel);
normalCalcPanel.add(MainMath.exitButton);
MainMath.frame.add(normalCalcPanel);
MainMath.frame.repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Other (main) class:
package com.Egg;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MainMath implements ActionListener {
static JFrame frame = new JFrame("Math Tools");
static JButton exitButton = new JButton("Exit");
JPanel mainPanel = new JPanel();
JLabel mainLabel = new JLabel("Select your tool.", SwingConstants.CENTER);
JButton nB = new JButton("Normal Calc.");
JButton tB = new JButton("Right Triangle Calc.");
JButton eB = new JButton("Equations Calc.");
public MainMath() {
frame.setBounds(300, 300, 500, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setResizable(false);
mainPanel.setLayout(null);
mainPanel.setBounds(0, 0, 500, 700);
mainLabel.setBounds(100, 25, 300, 50);
mainLabel.setFont(new Font("Monospaced Bold", Font.BOLD, 18));
nB.setBounds(100, 100, 300, 40);
tB.setBounds(100, 150, 300, 40);
eB.setBounds(100, 200, 300, 40);
nB.setFocusable(false);
tB.setFocusable(false);
eB.setFocusable(false);
nB.addActionListener(this);
tB.addActionListener(this);
eB.addActionListener(this);
mainPanel.add(mainLabel);
mainPanel.add(nB);
mainPanel.add(tB);
mainPanel.add(eB);
frame.add(mainPanel);
frame.setVisible(true);
exitButton.setBounds(16, 10, 80, 35);
exitButton.setFocusable(false);
exitButton.addActionListener(this);
}
public static void main(String[] args) {
new MainMath();
System.out.println("");
}
public void setMainScreen() {
frame.remove(exitButton);
frame.remove(NormalCalc.normalCalcPanel);
frame.add(mainPanel);
frame.repaint();
}
public static JFrame getFrame() {
return frame;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitButton)
setMainScreen();
if (e.getSource() == nB) {
frame.remove(mainPanel);
new NormalCalc();
}
if (e.getSource() == tB)
new TriangleCalc();
if (e.getSource() == eB)
new EquationCalc();
}
}
I see multiple issues in your code:
Your arrangement of your buttons is weird looking at first glance.
normalCalcPanel is static, why? It should never be
setBounds(...) when using layout managers, those statements are ignored, so no need for them
repaint() unless you've added / removed any element AFTER you've displayed your GUI, these calls are unnecessary, and should come with revalidate() as well.
MainMath.exitButton another static component, STOP
MainMath.frame.add(normalCalcPanel) implies that your JFrame called frame is static as well, which again, shouldn't be
And (I'm gonna guess here) more than probably you're creating a second instance inside MainMath, but because we don't have the code from that class we don't know what's going on
I ran your code and it looks ok, so that's why I believe your MainMath is creating another instance of JFrame
Here's an example of a calculator arrangement, that should help you to structure your code similarly, not the GUI but the components and classes
Edit
Okay, I understand now that I should not use static things, but how can I add a panel to a frame which I created in another class? I used 'static', because it seemed to work
Let's make an analogy for this case, imagine that your JFrame is a book, and that your JPanels are the sheets of that book, when you write on those sheets, you don't add / paste the book to the sheets, you add the sheets to the book.
So, in this case it's the same, your main class should create the JPanels and add those to your JFrame, your JPanel classes shouldn't have knowledge of your JFrame
In the case of the book, your sheets don't need to know to which book the belong, you know that and the book knows which sheets belong to it, not viceversa.
I made an example to show you what I mean by this, I didn't recreate your GUI but made it as simple as I could for you to get the idea:
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class AnotherCalculator {
private JFrame frame;
private CalculatorPanel calculatorPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new AnotherCalculator()::createAndShowGUI);
}
private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName());
calculatorPanel = new CalculatorPanel();
frame.add(calculatorPanel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class CalculatorPanel extends JPanel {
private String[] operations = {"+", "-", "*", "/", "DEL", "AC", "(", ")", "-", "^", "SQRT", ".", "+/-", "="};
private static final int NUMBER_OF_DIGITS = 10;
private JButton[] buttons;
public CalculatorPanel() {
this.setLayout(new GridLayout(0, 4, 5, 5));
buttons = new JButton[operations.length + NUMBER_OF_DIGITS];
for (int i = 0; i < buttons.length; i++) {
if (i < NUMBER_OF_DIGITS) {
buttons[i] = new JButton(String.valueOf(i));
} else {
buttons[i] = new JButton(operations[i - NUMBER_OF_DIGITS]);
}
this.add(buttons[i]);
}
}
}

How can I get the contents of my GUI to look a certain way? (Java)

So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:

How do you add a XChart PieChart to an existing Java GUI?

Recently I asked a question similar to this but didn't give enough info and my code was too long for a code review. I have written a new file with the same bare bones as my previous post. Here I'm reaching the same issues once again.
When I attempt to click the Show Graph button, I get the following Error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.knowm.xchart.XChartPanel.<init>(XChartPanel.java:65)
at testMain$1.actionPerformed(testMain.java:78)"
Here is my code:
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.DefaultTableModel;
import org.knowm.xchart.PieChart;
import org.knowm.xchart.PieChartBuilder;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XChartPanel;
import org.knowm.xchart.style.PieStyler.AnnotationType;
import org.knowm.xchart.style.Styler.ChartTheme;
import org.knowm.xchart.style.Styler.LegendPosition;
public class testMain extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel gui, choiceBar,insertPanel;
private XChartPanel chartPanel;
private JButton showGraph;
private PieChart chart;
public testMain() {
this.setTitle("Test Frame");
this.setSize(500, 500);
JPanel gui = new JPanel(new BorderLayout());
//choice bar testing
choiceBar = new JPanel(new FlowLayout());
// Radio button group
JRadioButton halfhalf = new JRadioButton("Split half");
JRadioButton quarters = new JRadioButton("Split quarters");
ButtonGroup group1 = new ButtonGroup();
group1.add(halfhalf); group1.add(quarters);
//add to choice bar
choiceBar.add(halfhalf); choiceBar.add(quarters);
//Side panel for inserting user values
insertPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(insertPanel);
groupLayout.setAutoCreateGaps(true);
groupLayout.setAutoCreateContainerGaps(true);
//Display Button
JButton showGraph = new JButton("Show Graph");
JLabel showGraphLabel = new JLabel("Finish");
//JTextfield for inserting value
JTextField value = new JTextField("value");
JLabel valueLabel = new JLabel("Insert value here:");
// Grouping JTextFields
GroupLayout.SequentialGroup groupH = groupLayout.createSequentialGroup();
GroupLayout.SequentialGroup groupV = groupLayout.createSequentialGroup();
groupH.addGroup(groupLayout.createParallelGroup().addComponent(valueLabel).addComponent(showGraphLabel));
groupH.addGroup(groupLayout.createParallelGroup().addComponent(value).addComponent(showGraph));
groupLayout.setHorizontalGroup(groupH);
groupV.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(valueLabel).addComponent(value));
groupV.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(showGraphLabel).addComponent(showGraph));
groupLayout.setVerticalGroup(groupV);
showGraph.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String valueText = value.getText();
double valueAmount = Double.parseDouble(valueText);
if (halfhalf.isSelected()) {
chartPanel = new XChartPanel(chart);
chart = new PieChartBuilder().width(600).height(400).title("Split By").theme(ChartTheme.GGPlot2).build();
chart.getStyler().setLegendVisible(false);
chart.getStyler().setAnnotationType(AnnotationType.LabelAndPercentage);
chart.getStyler().setAnnotationDistance(1.15);
chart.getStyler().setPlotContentSize(.7);
chart.getStyler().setStartAngleInDegrees(90);
chart.addSeries("1", valueAmount/2);
chart.addSeries("2", valueAmount/2);
new SwingWrapper(chart).displayChart();
gui.add(chartPanel, BorderLayout.SOUTH);
gui.validate();
gui.repaint();
}
else {
chartPanel = new XChartPanel(chart);
chart = new PieChartBuilder().width(600).height(400).title("Split By").theme(ChartTheme.GGPlot2).build();
chart.getStyler().setLegendVisible(false);
chart.getStyler().setAnnotationType(AnnotationType.LabelAndPercentage);
chart.getStyler().setAnnotationDistance(1.15);
chart.getStyler().setPlotContentSize(.7);
chart.getStyler().setStartAngleInDegrees(90);
chart.addSeries("1",valueAmount/4);
chart.addSeries("2", valueAmount/4);
chart.addSeries("3", valueAmount/4);
chart.addSeries("4", valueAmount/4);
new SwingWrapper(chart).displayChart();
gui.add(chartPanel, BorderLayout.SOUTH);
gui.validate();
gui.repaint();
}
}
});
// add to gui
gui.add(choiceBar, BorderLayout.NORTH);
gui.add(insertPanel, BorderLayout.WEST);
this.add(gui);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
testMain frame = new testMain();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
});
}
}
`
I'm trying to write a Java GUI where once the user clicks the button, the graph shows up on the same GUI. I still would like to implement this using nested layouts as I like the clean look. Someone mentioned that I could use cardLayout but I think that would be too cluttered.
Thanks, and any help is apprecaited.

How can I properly align my labels?

More help needed with this little project of mine again, this time trying to get two labels that are inside a panel in certain positions. Those positions being one on the left and then a separation of spaces (like a tab) and then the second label to make way for entries being added below them when a button is pressed which I am also unsure how to start.
I've uploaded an image of the current program running :
As you can see I have two buttons (may change to one at some point) and then a separate results panel with currently two labels inside that I want to move. I want 'Name' to be on the left side and 'Grade' slightly more to the right (separated by about a tabs worth of space). I'm also unsure what the two little lines are so if someone could explain that to me it would be great.
Where I plan to go with this is then for a button entry to lead to a name entry being entered below these labels and a grade entry being entered below these labels which keeps updating with each button press. If anyone could guide me in the right direction for this it would be great. I have provided the code for the panel below.
Thanks for taking the time to read this!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
//Bottom Panel
JPanel GradePanel = new JPanel();
GradePanel.setBorder(BorderFactory.createTitledBorder("Students/Results"));
GradePanel.setOpaque(false);
GradePanel.setPreferredSize(new Dimension(0 , 100));
GradePanel.add(resultField);
resultField.setAlignmentX(LEFT_ALIGNMENT);
GradePanel.add(nameResult);
GradePanel.add(gradeResult);
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(GradePanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and then the driver class:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
Take time to read this the most flexible Layout Manager that commonly used by programmer :)
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
Btw I separate your class Bottom Panel It's a little bit confused while reading it. Much better try the Nested Classes to look your code clean and easy to read.
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GradePanel2 extends JPanel {
private JButton addEntry, calculate;
private JLabel name, grade, nameResult, gradeResult;
private JTextField nameField, gradeField, resultField;
public GradePanel2() {
// Button to add entry to list
addEntry = new JButton("Add entry to list");
addEntry.addActionListener(new buttonListener());
// Button to print all entries in correct format
calculate = new JButton("Print all user grades");
calculate.addActionListener(new buttonListener());
//Create Labels
name = new JLabel("Enter student name: ");
nameField = new JTextField(10);
nameField.addActionListener(new buttonListener());
grade = new JLabel("Enter students mark: ");
gradeField = new JTextField(5);
gradeField.addActionListener(new buttonListener());
//Bottom segment for result
resultField = new JTextField();
resultField.setOpaque(false);
resultField.setEditable(false);
setLayout(new BorderLayout());
GridBagConstraints nameResultConstraints = new GridBagConstraints();//Constraints
GridBagConstraints gradeResultConstraints = new GridBagConstraints();//Constraints
//Button Panel
JPanel ButtonPane = new JPanel();
ButtonPane.setLayout(new BoxLayout(ButtonPane, BoxLayout.PAGE_AXIS));
addEntry.setAlignmentX(CENTER_ALIGNMENT);
calculate.setAlignmentX(CENTER_ALIGNMENT);
ButtonPane.add(addEntry);
ButtonPane.add(Box.createVerticalStrut(10));
ButtonPane.add(calculate);
//Label Panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new BoxLayout(labelPane, BoxLayout.PAGE_AXIS));
labelPane.add(name);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(nameField);
labelPane.add(Box.createRigidArea(new Dimension (0,2)));
labelPane.add(grade);
labelPane.add(Box.createRigidArea(new Dimension (5,0)));
labelPane.add(gradeField);
myBottomPanel mybottompanel = new myBottomPanel();//Object
//Add all panels to the main panel
add(labelPane, BorderLayout.NORTH);
add(ButtonPane, BorderLayout.CENTER);
add(mybottompanel, BorderLayout.SOUTH);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(400, 300));
}
public class myBottomPanel extends JPanel{
public myBottomPanel()
{
this.setLayout(new GridBagLayout());
//Result Labels
nameResult = new JLabel("NAME");
gradeResult = new JLabel("GRADE");
//Constraints
GridBagConstraints nameResultConstraints = new GridBagConstraints();
GridBagConstraints gradeResultConstraints = new GridBagConstraints();
//Bottom Panel
setBorder(BorderFactory.createTitledBorder("Students/Results"));
setOpaque(false);
setPreferredSize(new Dimension(0 , 100));
nameResultConstraints.anchor = GridBagConstraints.LINE_START;
nameResultConstraints.weightx = 0.5;
nameResultConstraints.weighty = 0.5;
add(nameResult,nameResultConstraints);
add(gradeResult);
}
}
public class buttonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String studentName;
int studentMark;
studentName = nameField.getText();
String intMark = gradeField.getText();
studentMark = Integer.parseInt(intMark);
}
}
}
and here is your Frame.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Grade2{
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Grade Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GradePanel2 panel = new GradePanel2();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}}
OUTPUT
Hope this helps. :)
If you want data displayed in a column then you need to use an appropriate layout manager to achieve the effect you want.
Maybe you can use a GridBagLayout. You can have columns and spaces between the columns, but you need to use the appropriate constraints. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.
However, the easier option would be to use a JTable which is a component designed for display data in rows/columns. Again check out the Swing tutorial on How to Use Tables.

Java: How to display card JPanel fully when using CardLayout

I'm having trouble with this JApplet. At the moment I have a CardLayout JPanel which contains two BorderLayout JPanels. Whenever I run it, the components added to each 'card' (a JButton to go back to the other JPanel) don't display unless I use setVisible(true) for each LayoutManager. Furthermore, none of my ActionListeners work. I'm assuming because they only use show() and there's something else I have to do that's alluding me.
Must I use setVisible(true)? It seems from other questions that there's a way of doing this without that. Here's the code I'm having trouble with:
/*
*Java Version: 1.8.0_25
*Author: Peadar Ó Duinnín
*Student Number: R00095488
*/
package As1;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AUIJApplet extends JApplet implements ActionListener {
private final int WIDTH = 600;
private final int HEIGHT = 400;
private int highScore;
private int currentScore;
JPanel panelCont = new JPanel();
JPanel startPanel = new JPanel();
JPanel gamePanel = new JPanel();
JButton newGameButton = new JButton("New Game");
JButton endGameButton = new JButton("End Game");
JLabel highScoreLabel;
JLabel currentScoreLabel;
CardLayout cl = new CardLayout();
BorderLayout bl = new BorderLayout();
public AUIJApplet() {
highScore = 0;
}
#Override
public void init() {
setSize(WIDTH, HEIGHT);
panelCont.setLayout(cl);
startPanel.setLayout(bl);
gamePanel.setLayout(bl);
startPanel.add(newGameButton, BorderLayout.SOUTH);
gamePanel.add(endGameButton, BorderLayout.SOUTH);
startPanel.setBackground(Color.BLUE);
gamePanel.setBackground(Color.GREEN);
panelCont.add(startPanel, "Start Applet Screen");
panelCont.add(gamePanel, "New Game Screen");
newGameButton.addActionListener((e) -> {
newGame();
});
endGameButton.addActionListener((e) -> {
quitGame();
});
cl.show(panelCont, "Start Applet Screen");
this.add(panelCont);
}
public void newGame() {
cl.show(panelCont, "New Game Screen");
showScores(gamePanel);
}
public void quitGame() {
cl.show(panelCont, "Start Applet Screen");
if (currentScore > highScore) {
highScore = currentScore;
}
currentScore = 0;
}
public void showScores(JPanel currentPanel) {
currentPanel.add(new JLabel("High Score:") , BorderLayout.EAST);
currentPanel.add(highScoreLabel, BorderLayout.EAST);
currentPanel.add(new JLabel("Current Score:"), BorderLayout.EAST);
currentPanel.add(currentScoreLabel, BorderLayout.EAST);
}
#Override
public void actionPerformed(ActionEvent ae) {
}
}
I have made the a little similar code to perform same operation it works for me try to write the code from scratch. Here is my code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JApplet;
import javax.swing.*;
public class Example extends JApplet {
JPanel panel1,panel2,mainPanel;
JButton start,stop;
CardLayout cl = new CardLayout();
#Override
public void init() {
panel1 = new JPanel();
panel1.setBackground(Color.red);
panel1.setLayout(new BorderLayout());
panel2 = new JPanel();
panel2.setBackground(Color.blue);
panel2.setLayout(new BorderLayout());
start = new JButton("Start");
stop = new JButton("stop");
panel1.add(start,BorderLayout.SOUTH);
panel2.add(stop,BorderLayout.SOUTH);
mainPanel = new JPanel();
mainPanel.setLayout(cl);
mainPanel.add(panel1,"First Panel");
mainPanel.add(panel2, "Second Panel");
start.addActionListener((ActionEvent e) -> {
newGame();
});
stop.addActionListener((ActionEvent e) ->{
endGame();
});
this.add(mainPanel);
}
public void newGame()
{
cl.show(mainPanel, "Second Panel");
}
public void endGame()
{
cl.show(mainPanel,"First Panel");
}
}

Categories

Resources