How to implement layout? - java

I have a GUI program which includes JLabels and JButtons and basically I want a layout that would help me display them as follows:
Label1 Button1
Label2 Button2
Label3 Button3
.....
Is there a layout that would allow me to achieve the above result?
I have looked at this example but is too complex and was wondering if there is anything automated that I can use?

This is one of the few things for which I'd recommend (a utility method and) GroupLayout as seen in this answer.

You can use GridLayout. Documentation here.

This is just for simplicity, and for your question. GUI is really dependent on what you would like to do and is really a thing that can be hardly automated..., and i don't think you only want those 6 elements on your GUI, but theoretically this will do it:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUITest {
private Box labelbox = new Box(BoxLayout.Y_AXIS);
//Y_AXIS means they are placed vertically in the box
private Box buttonbox = new Box(BoxLayout.Y_AXIS);
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public void makeGUI1() {
for (int i = 1; i <= 3; i++) {
//if you want to save the references, you should make
//an ArrayList<JLabel> and add each of them to it
JLabel label = new JLabel("Label " + i);
labelbox.add(Box.createVerticalStrut(5));
//these are for giving the labels some extra space
//between them vertically to be in line with the buttons
labelbox.add(label);
labelbox.add(Box.createVerticalStrut(10)); //these are too
}
for (int i = 1; i <= 3; i++) {
//if you want to save the references, you should make
//an ArrayList<JButton> and add each of them to it
JButton button = new JButton("Button " + i);
buttonbox.add(button);
}
panel.add(labelbox, BorderLayout.EAST);
//you can find picture of each constant:
//http://download.java.net/jdk7/archive/b123/docs/api/java/awt/BorderLayout.html
panel.add(buttonbox, BorderLayout.WEST);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GUITest guitest = new GUITest();
guitest.makeGUI1();
}
});
}
}

You can also use obj.setBounds(LeftSpaceParameter,TopSpaceParameter) with which you can place the gui elements or objects at any position of your choice. You need to put the default layout to null
yet gridLayout is much easier. .

Related

Attempting to set the layout to BoxLayout

I can't seem to find a solution online for why I'm getting this error on attempted run
I'm working on making a simple test system for a different program when are button press will yield value in a text box. I would like them to be on different lines to make it cleaner, so I looked into layouts. I decided a Box Layout would fit me best. I looked at different examples before attempting this and my code ended up looking like this, (apologies for the messy code)
Update
Got the box layout error to disappear but the code will not center them on the panel/frame. The label and button align left while the textfield becomes very large. I don't need it todo that
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import static javax.swing.BoxLayout.Y_AXIS;
import static javax.swing.SwingConstants.CENTER;
public class button extends JFrame {
static JFrame f;
static JButton b;
static JLabel l;
// main class
public static void main(String[] args)
{
// create a new frame to stor text field and button
f = new JFrame("panel");
BoxLayout layout = new BoxLayout(f, BoxLayout.Y_AXIS);
f.setLayout(layout);
// create a label to display text
l = new JLabel("panel label");
b = new JButton("button1");
JTextField textArea = new JTextField(5);
textArea.setEditable(false);
//textArea.append("Hello World");
// create a panel to add buttons
JPanel p = new JPanel();
// add buttons and textfield to panel
f.add(p);
f.setSize(300, 300);
p.add(l);
p.add(b);
p.setBackground(Color.white);
p.add(textArea);
f.show();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
textArea.setText(String.valueOf(r));
}
});
}
}
Error
Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared
at java.desktop/javax.swing.BoxLayout.checkContainer(BoxLayout.java:461)
at java.desktop/javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:245)
at java.desktop/javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:278)
at java.desktop/java.awt.Container.addImpl(Container.java:1152)
at java.desktop/java.awt.Container.add(Container.java:1029)
at java.desktop/javax.swing.JFrame.addImpl(JFrame.java:553)
at java.desktop/java.awt.Container.add(Container.java:436)
at button.main(button.java:36)
I would like the three items to all to be stacked one on top of another with a space between them. The order doesn't matter right now.
Swing was first added to the JDK in 1998 and has undergone a lot of changes since. Unfortunately, when you read Web pages about Swing, it is not obvious when that page was last updated. Consequently you may be learning outdated techniques for writing Swing code.
First of all, according to the code you posted, class button does not need to extend class JFrame since you use a static variable as your application's JFrame. Also, JFrame is a top-level container which makes it a special kind of container and not the same kind of continer as a JPanel. You need to set the layout manager for your JPanel and then add the JLabel, JTextField and JButton to that JPanel. And then add the JPanel to the JFrame.
Calling method pack() of class JFrame will automatically set the preferred sizes for the components inside the JFrame. It appears in the code below.
Please also look at Java coding conventions which allows others to more easily read and understand your code. And note that, according to these conventions, I renamed your class from button to Buttons and also because there are already several class in the JDK named Button.
Here is my rewrite of your code...
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Buttons implements Runnable {
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
JFrame f = new JFrame("Box");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel p = new JPanel();
BoxLayout layout = new BoxLayout(p, BoxLayout.Y_AXIS);
p.setLayout(layout);
JLabel l = new JLabel("panel label");
JTextField textField = new JTextField(5);
JButton b = new JButton("button1");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Random r = new Random();
textField.setText(String.valueOf(r.nextBoolean()));
}
});
p.add(l);
p.add(textField);
p.add(b);
f.add(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
Buttons instance = new Buttons();
EventQueue.invokeLater(instance);
}
}

Java components replacement JPanel

I'm trying to create an application in 3 parts : 3 labels and 3 gridlayouts. When we click on a label, the corresponding gridlayout disappear and the frame replace automatically the components at the right place. I created a simple snippet :
import java.awt.Button;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestLayout extends JFrame{
private JPanel content;
private JLabel[] lbl;
private JPanel[] pnl;
private Boolean[] ih;
public TestLayout(){
setTitle("Test");
setSize(new Dimension(300, 400));
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
lbl = new JLabel[3];
pnl = new JPanel[3];
ih = new Boolean[3];
content = new JPanel(new GridLayout(6, 1));
for(int i=0; i<3; i++){
lbl[i] = new JLabel("Label" + i);
lbl[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
for(int i=0; i<3; i++){
if(e.getSource() == lbl[i]){
//pnl[i].setVisible(!pnl[i].isVisible());
if(ih[i]) content.remove(pnl[i]);
else content.add(pnl[i]);
ih[i] = !ih[i];
}
}
}
});
pnl[i] = new JPanel(new GridLayout(3, 3));
}
for(int i=0; i<9; i++){
pnl[0].add(new Button("" + (i+1)));
pnl[1].add(new Button("" + (i+10)));
pnl[2].add(new Button("" + (i+19)));
}
for(int i=0; i<3; i++){
content.add(lbl[i]);
content.add(pnl[i]);
ih[i] = true;
}
add(content);
setVisible(true);
}
public static void main(String[] args){
new TestLayout();
}
}
The first problem is the use of a global gridlayout which resize all the components at the same size, but I think it would be better if labels could be smaller than the grilayouts.
The second problem is that even if the gridlayout is removed or setVisible(false), it still take a blank place in the global container.
What I get :
What I was expecting :
The only thing I don't wanna use is a GridBagLayout.
I was thinking about create a method init() which one remove all components of the global container then re add all the labels and all the panels, then create another method which do the exact same as the init() method but take a number as parameter (for example 2) then re add all the components excepting the second gridlayout. But I think it's a dirty way to do that because the container will content an empty case at the end and I think there is a better way than removing and re adding all the components (which basically doesn't solve the first problem of label's size)
How can I avoid theses problems ?
Try using a vertical BoxLayout.
Read the section from the Swing tutorial on How to Use BoxLayout for more information and working examples.

How can I get my labels into the inner frame I have created? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have been given an assignment whereby I need to create a tool that analyses a field of text and then outputs a couple of statistics about said body of text via a button click. I seem to have most of the basic framework up but am struggling with getting my two labels that are averageLength and totalWords inside my JPanel and also on getting said JPanel below where I enter my body of text. Any help would be much appreciated. Code is here:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextStatisticsPanel extends JPanel
{
//Field for block of text
private JTextArea userText;
//Button to calculate Statistics
private JButton stats;
//Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
public TextStatisticsPanel(){
//creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
//create button
stats = new JButton("Update Text Statistics");
//Listener for button
stats.addActionListener(new ButtonListener());
//Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
//Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension (350, 400));
scroller.setBorder(BorderFactory.createTitledBorder ("Enter the text below"));
//Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
totalWords = new JLabel("The total number of words: ");
//add GUI
add(statPanel);
add(scroller);
add(averageLength);
add(totalWords);
setBackground(new java.awt.Color(202, 225, 255));
setPreferredSize(new Dimension (400, 600));
add(stats);
}
// When button is pressed do :
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == stats){
//Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate()
{
//Grab text user inputed
String text = userText.getText();
//Split the text by each space to find the number of words
String[] words = text.split(" ");
//Calculation for average
float average = (text.length() - words.length)/words.length;
//
averageLength.setText(String.valueOf(average));
totalWords.setText(String.valueOf(words.length));
System.out.println(averageLength);
System.out.println(totalWords);
}
}
}
OK so as to try and use MCVE, this is part of the relevent code however I am still unable to work out the root of the problem.
The code for my second panel is :
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
SO as per my understanding this is me creating a second panel among my app. The problem however is that this is being placed in a seemingly random location and is not wrapping around the two labels I wish to be inside this panel and I am unsure how to fix this problem.
The main class code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JFrame;
public class TextStatistics {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatisticsPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Providing a visual example to show the code I believe is the problem and the problem I am encountering
Problem Visualised
Here's the GUI I put together.
These are the major changes I made.
I put the JFrame code in a Runnable, so I could start the Swing application with a call to the SwingUtilities invokeLater method. The invokeLater method ensures that the Swing components are created and updated on the Event Dispatch thread. Oracle and I require that everyone starts their Swing applications on the Event Dispatch thread.
I defined several new JPanels in your TextStatisticsPanel class and used two Swing layout managers, BorderLayout and BoxLayout. Study the link in the previous sentence. By study, I mean spend at least two to three weeks of 8 hour days absorbing all of the ins and outs of the Swing layout managers.
I added JTextFields to hold the calculated values. That's what JTextFields are for.
I fixed the integer division in your statUpdate method.
Here's the code. I put everything together in one file so it would be easier to upload. You should put the classes in separate files.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TextStatistics {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatistics().new TextStatisticsPanel();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
public class TextStatisticsPanel extends JPanel {
private static final long serialVersionUID = 9049744714586970558L;
// Field for block of text
private JTextArea userText;
// Button to calculate Statistics
private JButton stats;
// Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
private JTextField averageLengthField, totalWordsField;
public TextStatisticsPanel() {
// creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
// create button
stats = new JButton("Update Text Statistics");
stats.setAlignmentX(JButton.CENTER_ALIGNMENT);
// Listener for button
stats.addActionListener(new ButtonListener());
// Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory
.createTitledBorder("Text Statistics"));
statPanel.setLayout(new BoxLayout(statPanel, BoxLayout.PAGE_AXIS));
statPanel.setOpaque(false);
// Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension(350, 400));
scroller.setBorder(BorderFactory
.createTitledBorder("Enter the text below"));
// Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
averageLength.setOpaque(false);
averageLengthField = new JTextField(10);
averageLengthField.setEditable(false);
averageLengthField.setOpaque(false);
totalWords = new JLabel("The total number of words: ");
totalWords.setOpaque(false);
totalWordsField = new JTextField(10);
totalWordsField.setEditable(false);
totalWordsField.setOpaque(false);
// add GUI
setLayout(new BorderLayout());
statPanel.add(stats);
statPanel.add(Box.createVerticalStrut(10));
JPanel lengthPanel = new JPanel();
lengthPanel.setOpaque(false);
lengthPanel.add(averageLength);
lengthPanel.add(averageLengthField);
statPanel.add(lengthPanel);
statPanel.add(Box.createVerticalStrut(10));
JPanel wordsPanel = new JPanel();
wordsPanel.setOpaque(false);
wordsPanel.add(totalWords);
wordsPanel.add(totalWordsField);
statPanel.add(wordsPanel);
add(statPanel, BorderLayout.SOUTH);
add(scroller, BorderLayout.CENTER);
setBackground(new java.awt.Color(202, 225, 255));
}
// When button is pressed do :
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == stats) {
// Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate() {
// Grab text user inputed
String text = userText.getText();
// Split the text by each space to find the number of words
String[] words = text.split(" ");
// Calculation for average
float average = ((float) text.length() - words.length)
/ words.length;
//
averageLengthField.setText(String.valueOf(average));
totalWordsField.setText(String.valueOf(words.length));
}
}
}
}

JList not showing as a list, just a dot...maybe a graphic dot?

Trying to list the nodes in a JList so I can choose one from the list.
I have this code (and a lot more)...
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JLabel flabel = new JLabel("Förbindelse från " + n1 +" till " + n2, JLabel.CENTER);
JScrollPane scroll = new JScrollPane(JLista);
DefaultListModel<Edge<Node>> Jlistan = new DefaultListModel<Edge<Node>>();
List<Edge<Node>> listan = listGraph.getEdgesBetween(n1,n2);
for (Edge<Node> listEdge : listan) {
Jlistan.addElement(listEdge);
}
JLista = new JList<Edge<Node>> (Jlistan);
JLista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLista.setLayoutOrientation(JList.HORIZONTAL_WRAP);
JLista.setVisibleRowCount(5);
JLista.setSize(100, 100);
getJlistVal();
row2.add(scroll);
row1.add(flabel);
add(row1);
add(row2);
}
...
public Edge<Node> getJlistVal(){
return JLista.getSelectedValue();
}
But when listing, i just get a little spot on the Jpanel, i think its a graphical dot, or a very very litte Jlist. :( cant publish a picture yet...
I thought it had to do with pixelsize but dont think so??
Do i have to specify size of the list??
The list to be displayed is a generic LIST as type Node. I have a method that i call, is the return type ok?
//thank you
-Help me StackOverflow. You are my only hope...
You create scroll instance with null list.
JScrollPane scroll = new JScrollPane(JLista);
Just move the line after
JLista = new JList<Edge<Node>> (Jlistan);
Not sure what you're doing wrong because your example won't compile without your other classes, But When I use the above code, adding in a bit of my own, it works. The only difference is I used a Box instead of BoxLayout, which is pretty much the same thing, just a Box uses a JPanel under the hood. I had to do this because it wasn't allowing be to use this from the JFrame subclass. You can test it
import javax.swing.Box;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
/**
*
* #author Paul SamSotha
*/
public class TestList extends JFrame {
public TestList() {
String[] list = {"Hello", "Jello", "Wello"};
JList JLista = new JList(list);
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JLabel flabel = new JLabel("Förbindelse från ", JLabel.CENTER);
JScrollPane scroll = new JScrollPane(JLista);
JLista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLista.setLayoutOrientation(JList.HORIZONTAL_WRAP);
JLista.setVisibleRowCount(5);
JLista.setSize(100, 100);
row2.add(scroll);
row1.add(flabel);
Box box = Box.createVerticalBox();
box.add(row1);
box.add(row2);
add(box);
}
public static void createAndShowGui() {
JFrame frame = new TestList();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
"Do i have to specify size of the list??"
No, you can just call .pack() on the frame and let the pack do its magic
What you could do is, get the value in the getJlistVal() and return the value as a String.
String selected = jList1.getSelectedItem().toString();
and try to return that value. Tell me if it prints. I can't test it myself right now.
Just a suggestion to try, let me know how it goes.
Currently what your method getJListVal() is doing is, returning the value as an Element. Which may be your problem. Try returning it as a String, int or generic variable type, then try displaying it.

JCheckBox not showing (text appears, but without check box)

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SideNotes {
public static JPanel panel = new JPanel();
private List<String> notes = new ArrayList<String>();
private static JButton add = new JButton("Add note");
public SideNotes() {
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
loadNotes();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addNote();
}
});
}
public void addNote() {
String note = JOptionPane.showInputDialog("Enter note: ", null);
notes.add(note);
JLabel label = new JLabel(note);
panel.add(label);
panel.revalidate();
panel.repaint();
}
private void loadNotes() {
for (int i = 0; i < notes.size(); i++) {
JCheckBox jcb = new JCheckBox(notes.get(i), false);
panel.add(jcb);
panel.revalidate();
panel.repaint();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 400);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new SideNotes();
}
}
Why isn't my JCheckBox showing up? The text shows up but not the actual box. What's the deal?
I have edited my post to contain all of my code in case that helps solve the issue.
needmoretextneedmoretextneedmoretextneedmoretextneedmoretextneedmoretextneedmoretext
Possible reasons:
panel has not been added to GUI
panel has been added but for some reason is not visible.
panel is too small to show the child component. This can happen for instance if you set a component's size or preferredSize or if you place it in a FlowLayout-using container without thought.
panel uses null layout.
panel's layout manager is not one that easily accepts a new component -- think GroupLayout for this one.
There are other unspecified layout manager problems going on. Do you call pack() on your GUI? Do you use null layout or absolute positioning anywhere? Do you need to put panel in a JScrollPane?
Consider creating and posting an sscce for better help.
Edit
Your posted code doesn't ever add any JCheckBoxes to the JPanel, just JLabels. To prove this is so, click on the labels and you'll see that they don't respond to clicks.
Your code grossly over-uses static fields. Get rid of all static modifiers on all variables. They should all be instance variables. The only static anything in your code above should be the main method, and that's it. If this causes errors, then fix the errors, but not by making fields static.
Give your SideNotes class a method, getPanel() that returns the panel field.
Create a SideNotes instance in the beginning of your main method. Then call the above method on the instance to get the JPanel for the JFrame. i.e., frame.add(sideNotes.getPanel());.
Don't add JLabels to your GUI (I've no idea why you're doing this). Add JCheckBoxes in the actionPerformed method.
Every time you press the button, a new Note (JLabel) is added to the panel. But you never call loadNotes() after adding a new Note. So the JLabel is added but not its respective JCheckBox as intended.
Besides of this I'd suggest you make this change:
public void addNote() {
String note = JOptionPane.showInputDialog("Enter note: ", null);
if(notes != null) {
notes.add(note);
JLabel label = new JLabel(note);
panel.add(label);
panel.add(new JCheckBox(note, false));
panel.revalidate();
panel.repaint();
}
}
So you don't need to call loadNotes() and update the GUI just once.

Categories