Java GUI - Possible to store JPanels inside a single main JPanel? - java

I am working on a semester project that I have and I was wondering if it was possible to store 3-4 JPanels instead one single "main" JPanel. The reason for me asking this is because I a trying to make a GUI checkbook program and my checkbook has 7 buttons that should open a new window once I click on it. To switch between each window I'm going to have to use the CardLayout, but my understand of the CardLayout is that I can only assign one single JPanel to that card so I can't assign multiple JPanels to a single Card layout so when the user clicks on a different card 3-4 different JPanels appear.
The reason that I am asking this is because I asked for help earlier and received help for creating my first window in this project, it produces the output I want PERFECTLY, but uses more than 1 JPanel in doing so. Since this prevents me from continuing on to the other steps of my 7 GUI Windows, I am stuck.
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class checkbook extends JPanel implements ActionListener {
private static final String title = "Use The Buttons Below To Manage Transactions";
private static final String[] bottomButtons = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
static JButton Button[] = new JButton[8];
static ActionListener AL = new checkbook();
public checkbook() {
JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 18));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JTextField textfield = new JTextField();
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(4));
accountBalancePanel.add(new JLabel("Balance:"));
textfield = new JTextField("0.0", 10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
accountBalancePanel.add(textfield);
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
southBtnPanel.add(Button[i]);
Button[i].addActionListener(AL);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(100, 100))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
checkbook mainPanel = new checkbook();
JFrame frame = new JFrame("Checkbook");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button[7]) {
System.exit(0);
}
}
}
Credit goes to Hovercraft Full Of Eels for showing me the above example
If there is anything that is unclear about my question, please ask and I will do the best I can to fix it.
Here is what the code produces:
http://i.stack.imgur.com/WY0c3.png

Related

addactionListener(this) How do I place this line of code in correctly?

So I am designing a chatroom and before I can read up on sockets I need to finish up this GUI. Basically I am mostly using TextDemo as my guide. I like how it displays so I figured it'd be an easy spot to start with my code. In my code it breaks whenever I try to put in:
input.addActionListener(this);
When I comment out that line it goes back to displaying/running perfectly. Due to my errors, it looks like I'm putting it in the wrong location. I've tried moving it around a bit but I don't seem to have the problem solving skills to fix this yet. Can someone help correct me and explain what I am doing wrong here?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JPanel implements ActionListener
{
private final static String newline = "\n";
///// CREATING THE GUI /////
JFrame frame = new JFrame("Chatroom");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JPanel chatpanel = new JPanel();
JPanel inputpanel = new JPanel();
JPanel sendpanel = new JPanel();
JTextArea chat = new JTextArea(19, 49);
JTextArea input = new JTextArea(3, 40);
JScrollPane chatscroll = new JScrollPane(chat,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JScrollPane inputscroll = new JScrollPane(input,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JButton connectbutton = new JButton("Connect");
JButton disconnectbutton = new JButton("Disconnect");
JButton send = new JButton("Send");
JLabel label = new JLabel();
///// GUI CONSTRUCTOR /////
public GUI()
{
chatroomGUI();
}
public void chatroomGUI()
{
///// GUI DISPLAY /////
frame.setVisible(true);
frame.setSize(800, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setBackground(Color.GRAY);
panel2.setBackground(Color.lightGray);
chatpanel.setBackground(Color.lightGray);
inputpanel.setBackground(Color.lightGray);
sendpanel.setBackground(Color.lightGray);
///// ACTION LISTENER /////
//input.addActionListener(this);
chat.setEditable(false);
chat.setFont(new Font("Dialog", Font.PLAIN, 12));
chat.setLineWrap(true);
chat.setWrapStyleWord(true);
input.setFont(new Font("Fialog", Font.PLAIN, 12));
input.setLineWrap(true);
input.setWrapStyleWord(true);
sendpanel.setLayout(new BorderLayout(0, 0));
sendpanel.setPreferredSize(new Dimension(95, 50));
chatpanel.setLayout(new FlowLayout());
chatpanel.setPreferredSize(new Dimension(565, 320));
///// ADD AREA /////
chatpanel.add(chatscroll);
inputpanel.add(inputscroll);
inputpanel.add(sendpanel, BorderLayout.EAST);
sendpanel.add(send, BorderLayout.CENTER);
panel.add(connectbutton);
panel.add(disconnectbutton);
panel.add(label);
panel2.add(chatpanel);
panel2.add(inputpanel);
frame.add(panel, BorderLayout.WEST);
frame.add(panel2);
}
///// ACTION PERFORMED /////
/*The following will take any text that is typed inside of
the "input" area and display it in the "chat" screen area.*/
public void actionPerformed(ActionEvent evt)
{
String text = input.getText();
chat.append(text + newline);
input.selectAll();
chat.setCaretPosition(chat.getDocument().getLength());
}
}
Note: My main is in another class. That code just simply looks like:
public class Chatroom
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GUI();
}
});
}
}
JTextArea does not support the ActionListener API, so it does not have a addActionListener method. You should consult the JavaDocs and tutorials first
Depending on what you are trying to do, you might consider using a DocumentListener or a DocumentFilter or use the key bindings API, for example

How to clear JFrame area by clicking another sub menu of JMenuBar in java Swing?

the code is there for clearing the Frame area by clicking the sub menu(sub_menu_purchase and sub_menu_sale) of main menu.
public void clear()
{
Graphics g = getGraphics();
Dimension d = getSize();
g.setColor(Color.WHITE);
g.fillRect(0,0,d.width,d.height);
}
void sale()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblform =new JLabel("From Party : ");
lblto =new JLabel("To Party : ");
txtto=new JTextField();
txtfrom=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblto.setBounds(50,135,80,25);
txtto.setBounds(140,135,200,25);
lblform.setBounds(50,170,80,25);
txtfrom.setBounds(140,170,100,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblto);
add(lblform);
add(txtto);
add(txtfrom);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
void purchase()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblparty =new JLabel("Party Name: ");
txtparty=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblparty.setBounds(50,135,80,25);
txtparty.setBounds(140,135,200,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblparty);
add(txtparty);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
public void actionPerformed(ActionEvent event) //set up actionlistening
{
Object source=event.getSource();
if (source.equals(sub_menu_purchase))
{ clear();
purchase();
}
if (source.equals(sub_menu_sale))
{ clear();
sale();
}
}
But it is not clear the area and override to one another.
what code should I write?
There's a lot I would do differently from what you're doing, including
Don't get a component's Graphics via getGraphics(). The Graphics object thus obtained will not persist, and so it is not useful for making stable changes to a GUI's appearance.
Don't clear the GUI's graphics but rather change the view. Even if your code worked, the components would not have been removed from the GUI with your code. They would still exist and still sit on the GUI -- not good.
A CardLayout would work well for allowing you to swap a container's view, and is often used to swap JPanels, each holding its own GUI.
Avoid null layout and using setBounds(...) as this will lead to creation of GUI's that are a "witch" to upgrade and maintain and that look bad on all platforms except for one. Better to nest JPanels, each using its own simple layout, to achieve complex, beautiful and easy to maintain and improve GUI's.
Read/study the Swing tutorials as all of this is well explained there.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UglyGui2 {
private static final String SALE = "Sale";
private static final String PURCHASE = "Purchase";
private JMenuItem sub_menu_sale = new JMenuItem(SALE);
private JMenuItem sub_menu_purchase = new JMenuItem(PURCHASE);
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
public UglyGui2() {
cardPanel.add(new JLabel(), "");
cardPanel.add(createSalePanel(), SALE);
cardPanel.add(createPurchasePanel(), PURCHASE);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(new JButton("Reset"));
buttonPanel.add(new JButton("Save"));
buttonPanel.add(new JButton("Print"));
buttonPanel.add(new JLabel());
buttonPanel.add(new JButton("Cancel"));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.add(cardPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.PAGE_END);
}
private JComponent createSalePanel() {
JPanel salePanel = new JPanel(new GridBagLayout());
salePanel.add(new JLabel("Sales"));
salePanel.add(new JTextField(10));
return salePanel;
}
private JComponent createPurchasePanel() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Purchases"));
topPanel.add(new JTextField(10));
JPanel purchasePanel = new JPanel(new BorderLayout());
purchasePanel.add(topPanel, BorderLayout.PAGE_START);
purchasePanel.add(new JScrollPane(new JTextArea(30, 60)), BorderLayout.CENTER);
return purchasePanel; }
private Component getMainPanel() {
return mainPanel;
}
private JMenuBar getJMenuBar() {
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, e.getActionCommand());
}
};
sub_menu_purchase.addActionListener(aListener);
sub_menu_sale.addActionListener(aListener);
JMenu menu = new JMenu("Menu");
menu.add(sub_menu_purchase);
menu.add(sub_menu_sale);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
private static void createAndShowGui() {
UglyGui2 uglyGui = new UglyGui2();
JFrame frame = new JFrame("Ugly Gui Example");
frame.setJMenuBar(uglyGui.getJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(uglyGui.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Adding elements (i.e. JLabels) outside of the set layout

As part of a project we've got to have 9 boxes, here I've just implemented alternating colors as an example in place of the images we should be using. But whilst I want these 9 JLabels in this grid layout (3,3), I also want to have a message at the top (a JLabel) that I can just centralize, like a welcoming message as well as having around four JButtons underneath? Can somebody please point me in the right direction as to how to achieve this?
Thank you!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class HomeController extends JPanel implements MouseListener
{
HomeController()
{
setLayout(new GridLayout(3,3));
JLabel apl1 = new JLabel("");
apl1.setBackground(Color.WHITE);
apl1.setOpaque(true);
this.add(apl1);
JLabel apl2 = new JLabel("");
apl2.setBackground(Color.BLACK);
apl2.setOpaque(true);
this.add(apl2);
JLabel apl3 = new JLabel("");
apl3.setBackground(Color.WHITE);
apl3.setOpaque(true);
this.add(apl3);
JLabel apl4 = new JLabel("");
apl4.setBackground(Color.BLACK);
apl4.setOpaque(true);
this.add(apl4);
JLabel apl5 = new JLabel("");
apl5.setBackground(Color.WHITE);
apl5.setOpaque(true);
this.add(apl5);
JLabel apl6 = new JLabel("");
apl6.setBackground(Color.BLACK);
apl6.setOpaque(true);
this.add(apl6);
JLabel apl7 = new JLabel("");
apl7.setBackground(Color.WHITE);
apl7.setOpaque(true);
this.add(apl7);
JLabel apl8 = new JLabel("");
apl8.setBackground(Color.BLACK);
apl8.setOpaque(true);
this.add(apl8);
JLabel apl9 = new JLabel("");
apl9.setBackground(Color.WHITE);
apl9.setOpaque(true);
this.add(apl9);
JLabel message = new JLabel("hello world");
this.add(message);
}
}
You can combine multiple panels with different layouts. For details take a look at A Visual Guide to Layout Managers.
For example, default layout of JFrame is BorderLayout. Using BorderLayout, you can place the title at BorderLayout.NORTH, panel with buttons at BorderLayout.SOUTH and panel with grid of labels at BorderLayout.CENTER. Each panel may have its own more complex layout. For example, grid of labels is using GridLayout, and buttons panel is using FlowLayout.
Here is a very simple example based on the posted code that demonstrates this approach:
import java.awt.*;
import javax.swing.*;
public class TestGrid {
public TestGrid() {
final JFrame frame = new JFrame("Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new GridLayout(3, 3));
for (int idx = 0; idx < 9; idx++) {
JLabel label = new JLabel();
label.setBackground(idx % 2 == 0 ? Color.WHITE : Color.BLACK);
label.setOpaque(true);
mainPanel.add(label);
}
mainPanel.setPreferredSize(new Dimension(200, 200));
frame.add(mainPanel, BorderLayout.CENTER);
frame.add(new JLabel("Title", JLabel.CENTER), BorderLayout.NORTH);
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(new JButton("Start"));
buttonsPanel.add(new JButton("Stop"));
frame.add(buttonsPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGrid();
}
});
}
}

Add Jpanel to Jframe NetBeans

Hi all, I was in a development of my college mini project. It was a Library Management system , which i should do in Java swing using Net-beans IDE. First I was doing manual coding. It takes time.
In manual coding I create single JFrame with Menu bar and and items, on all action performed I wrote codes for all Jpanels. It made the file and code huge. and confusing too.
Now I need your help.
I have created a Main JFrame with Menu
A JPanel - ADD Book
another Jpanel - On add book success (demo! , for Actions happening in ADD Book )
I had made action listener
addBook addbk = new addBook();
this.getContentPane().add(addbk);
wrote this code.
I doesn't make sense.
Friends, As a new to java, What i need to study is
1.) How cal and Show an external Jpanel an action performed
2.) How to show another JPanel to same root JFrame if any event has occurred in external JPanel.
In sort, something like Iframe in HTML
Thank you all.
http://compilr.com/abelkbil/openlib/OpenLibMainGUI.java
http://compilr.com/abelkbil/openlib/addBook.java
http://compilr.com/abelkbil/openlib/bookAdded.java
CardLayout, is exactly what you need for this situation. And do learn Java Naming Conventions and stick to them, as you are a beginner, so to be on the right track from the start is always GOOD.
Here is one example, that you can look at :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel panel2;
private MyPanel panel3;
private JComboBox choiceBox;
private String[] choices = {
"Panel 1",
"Panel 2",
"Panel 3"
};
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
choiceBox = new JComboBox(choices);
panel1 = new MyPanel(contentPane
, Color.RED.darker().darker(), this);
panel2 = new MyPanel(contentPane
, Color.GREEN.darker().darker(), this);
panel3 = new MyPanel(contentPane
, Color.DARK_GRAY, this);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComboBox getChoiceBox()
{
return choiceBox;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
private JComboBox choiceBox;
public MyPanel(JPanel panel, Color c, CardLayoutExample cle)
{
contentPane = panel;
backgroundColour = c;
choiceBox = cle.getChoiceBox();
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
Else you can have a look at this example also.

Elements in Layouts in Java all in same position

I'm coding in Java Swing and for some reason, when I add two elements to a gridlayout, they both assume the same position. I have tried simplifying it into something that would not fail and then building up from there, but alas, it's still not working.
The misbehaving code within the program is:
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JTextArea one = new JTextArea("Hi");
one.setLineWrap(true);
one.setSize(100, 100);
JTextArea two = new JTextArea("Goodbye");
two.setLineWrap(true);
two.setSize(100, 100);
bodyPanelMain.add(one);
bodyPanelMain.add(two);
bodyPanelMain.repaint();
If I make JTextArea's width 200 and background a different color, it's clear that it's visible behind it, so it's most certainly adding all the proper elements, their positions are just wrong.
EDIT: Here's a very very short version of what I am trying to do.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class minimessageboard extends Applet implements ActionListener {
JPanel mainPanel;
JPanel buttonPanel;
JButton announcements, websites;
JPanel bodyPanel, bodyPanelMain;
public minimessageboard() {
this.setSize(600, 400);
mainPanel = new JPanel(new BorderLayout());
mainPanel.setPreferredSize(new Dimension(this.getWidth(), this.getHeight()));
this.add(mainPanel);
buttonPanel = new JPanel(new GridLayout(6, 1, 10, 10));
mainPanel.add(buttonPanel, BorderLayout.WEST);
announcements = new JButton("Announcements");
this.formatButton(announcements);
announcements.setActionCommand("announcements");
buttonPanel.add(announcements);
websites = new JButton("Websites");
this.formatButton(websites);
websites.setActionCommand("websites");
buttonPanel.add(websites);
bodyPanel = new JPanel(new BorderLayout());
bodyPanel.setSize(200, 500);
bodyPanel.setPreferredSize(new Dimension(200, 500));
mainPanel.add(bodyPanel, BorderLayout.CENTER);
bodyPanelMain = new JPanel(new BorderLayout());
bodyPanel.add(bodyPanelMain, BorderLayout.CENTER);
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JButton one = new JButton("Roar");
bodyPanelMain.add(one);
bodyPanelMain.revalidate();
bodyPanelMain.repaint();
}
public static void main(String args[]) {
JFrame overall = new JFrame();
overall.pack();
overall.setVisible(true);
overall.add(new minimessageboard());
}
public void formatButton(JButton b){
b.setPreferredSize(new Dimension(150, 33));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
String action = arg0.getActionCommand();
bodyPanelMain.removeAll();
if (action.equals("websites")){
System.out.println("Fires!");
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JButton one = new JButton("Hi");
JButton two = new JButton("Goodbye");
bodyPanelMain.add(one);
bodyPanelMain.add(two);
bodyPanelMain.revalidate();
}
bodyPanelMain.repaint();
}
}
Basically, when you click on websites, "Hi" and "Bye" should show up. If I move the code within the block in the websites if statement (if (action.equals("websites")) up to the original constructor, it appears perfectly fine. The code outputs "Fires!", so I am 100% certain it gets to that part. For note, I changed it from JTextArea to JButton because I will be using JButtons, not JTextArea.
Don't set the size of a JTextArea as it won't work well when your text extends beyond the text area size and you find that it just won't scroll. Instead set the preferred row and column values, and then let the JTextArea size itself. On to your problem: are you adding these components after the GUI has rendered itself? If so, do you call revalidate() on the bodyPanelMain after it receives the JTextAreas? If this doesn't help, consider creating and posting an sscce.
For example, this works fine for me:
import java.awt.GridLayout;
import javax.swing.*;
public class SwingFoo {
private static final int ROWS = 10;
private static final int COLS = 16;
private static void createAndShowGui() {
JPanel bodyPanelMain = new JPanel();
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JTextArea one = new JTextArea("Hi", ROWS, COLS);
one.setLineWrap(true);
// one.setSize(100, 100);
JTextArea two = new JTextArea("Goodbye", ROWS, COLS);
two.setLineWrap(true);
// two.setSize(100, 100);
bodyPanelMain.add(new JScrollPane(one));
bodyPanelMain.add(new JScrollPane(two));
// bodyPanelMain.repaint();
JFrame frame = new JFrame("SwingFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(bodyPanelMain);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories

Resources