sqwert sqwert - 1 year ago 126
Java Question

How to Get these JLabels to be Displayed in my JFrame?

I am attempting to make a "sentence randomizer" that, when a button is pressed, makes a grammatically correct sentence, that may not make any sense, by looping different types of words from a separate folder and separate files. It also alternates colors in each panel. I so far am able to get the JButton to show up, but I can't seem to figure out how to get the panels to appear? Here is my code so far for the UI:

package user_interface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import code.sentence;
import user_interface.RandomButtonListener;

public class sentenceUI {

private sentence _s;
private JButton _rando;

public sentenceUI() {
_s = new sentence(this);
JFrame f = new JFrame("Ryan Ellis' Lab 9");
f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));

JPanel topPanel = new JPanel();

JPanel lowerPanel = new JPanel();

_rando = new JButton("Random Sentence");
_rando.addActionListener(new RandomButtonListener(_s, this));

Color c1 = Color.BLUE;
Color c2 = new Color( 255 - c1.getRed(), 255 - c1.getGreen(), 255 - c1.getBlue());
for(int i = 0; i < 8; i++){
JLabel _l = new JLabel();
Color temp = c1;
c1 = c2;
c2 = temp;
_l.setFont(new Font("Comic Sans", Font.BOLD, 18));

ArrayList<String> _slst = new ArrayList<String>();

ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
int i = 0;
list.get(i % 5);

f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);



private void createRButton(String string, JPanel lowerPanel) {
createRButton("Random", lowerPanel);


Answer Source

You're adding topPanel twice to the JFrame, here

JPanel topPanel = new JPanel();

and here:

f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);

and in the 2nd addition, you're adding it as if the JFrame currently used a BorderLayout, but it's not since you've given it a BoxLayout.

Instead, only add the topPanel once, and in a logical way. Also consider giving your JLabel's some dummy text, such as " " so that they have some size when you first pack() your GUI.

Also, your labels are being added but they have no size and are non-opaque and so can't be seen. For example try this within your for loop to see for yourself:

JLabel _l = new JLabel("Label " + i);  // to give labels size 
_l.setOpaque(true);   // so you can see the background color
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download