I'm trying to use a grid layout to make a GUI window. I add all my components and it compiles but when it runs it doesn't show anything. I'm trying to make a simple layout grouped and stacked like this.
{introduction message}
{time label
time input text}
{gravity label
gravity input text}
{answer label
answer text box}
{calculate button clear button}
Here is my code
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
setTitle("Falling Distance Calculator");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 5));
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setVisible(true);
}
public static void main(String[] args)
{
new TurnerRandyFallingGUI();
}
}
You've added nothing to the JFrame that your class above extends. You need to add your components to containers whose hierarchy eventually leads to the top level window, to the this if you will. In other words, you have no add(someComponent) or the functionally similar this.add(someComponent)method call in your code above.
Consider adding all of your JPanels to a single JPanel
Consider adding that JPanel to the JFrame instance that is your class by calling add(thatJPanel).
Even better would be to not extend JFrame and just to create one when needed, but that will likely be the subject of another discussion at another time.
Before setVisible (true) statement add following statements:
add (introP);
add (timeP);
add (gravityP);
add (answerP);
add (buttonsP);
There is nothing in your JFrame. That is the reason
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setLayout(new GridLayout(5, 1));
this.add(introP);
this.add(timeP);
this.add(gravityP);
this.add(answerP);
this.add(buttonsP);
setTitle("Falling Distance Calculator");
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.validate();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TurnerRandyFallingGUI();
}
});
}
}
Consider the following
In GridLayout, the first parameter is Rows, Second is columns
Never set the size of JFrame manually. Use pack() method to decide
the size
Use SwingUtilities.InvokeLater() to run the GUI in another thread.
Related
As stated in the title i need to move the label for the text box to be above the box and not to the side. attached i have a picutres of what i mean. what i have vs what i want i have tried searching for it but i cannot seem to find the answer im looking for/not exactly sure what to look up. I have tried using JFrame but it made a separate window unless i need to make the entire GUI a JFrame for me to get the result i want?
Also the actionPerformed method has things but it is irrelevant to the question but displays correctly still.
import java.awt.event.\*;
import javax.swing.\*;
import java.text.DecimalFormat;
public class Project4 extends JFrame implements ActionListener {
private JTextArea taArea = new JTextArea("", 30, 20);
ButtonGroup group = new ButtonGroup();
JTextField name = new JTextField(20);
boolean ch = false;
boolean pep = false;
boolean sup = false;
boolean veg = false;
DecimalFormat df = new DecimalFormat("##.00");
double cost = 0.0;
public Project4() {
initUI();
}
public final void initUI() {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
getContentPane().add(panel1, "North");
getContentPane().add(panel2, "West");
getContentPane().add(panel3, "Center");
getContentPane().add(panel4, "East");
panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
getContentPane().add(panel5, "South");
JButton button = new JButton("Place Order");
button.addActionListener(this);
panel5.add(button);
JButton button2 = new JButton("Clear");
button2.addActionListener(this);
panel5.add(button2);
panel3.add(taArea);
JCheckBox checkBox1 = new JCheckBox("Cheese Pizza") ;
checkBox1.addActionListener(this);
panel4.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Pepperoni Pizza");
checkBox2.addActionListener(this);
panel4.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox("Supreme Pizza");
checkBox3.addActionListener(this);
panel4.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox("Vegetarian Pizza");
checkBox4.addActionListener(this);
panel4.add(checkBox4);
JRadioButton radioButton1 = new JRadioButton("Pick Up");
group.add(radioButton1);
radioButton1.addActionListener(this);
panel1.add(radioButton1);
JRadioButton radioButton2 = new JRadioButton("Delivery");
group.add(radioButton2);
radioButton2.addActionListener(this);
panel1.add(radioButton2);
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
panel5.add(name_label);
panel5.add(name);
setSize(600, 300);
setTitle("Pizza to Order");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent action) {
}
public static void main(String[] args) {
Project4 ex = new Project4();
ex.setVisible(true);
}
}
You can use a nested JPanel with another layout in order to achieve that. I would go with BorderLayout here. You can also other layouts that allow vertical orientation. Visiting the visual guide to Layout Managers will help you spot them.
JLabel name_label = new JLabel("Name on Order");
name.addActionListener(this);
JPanel verticalNestedPanel = new JPanel(new BorderLayout());
verticalNestedPanel.add(name_label, BorderLayout.PAGE_START);
verticalNestedPanel.add(name, BorderLayout.PAGE_END);
panel5.add(verticalNestedPanel);
This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.
package test;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("");
textfield = new JTextField("enter text here");
JPanel bottom = new JPanel(new BorderLayout());
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel (new BorderLayout());
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom, BorderLayout.PAGE_END);
centre.add(subCentre, BorderLayout.CENTER);
}
}
Your code is a bit over-complicated. You only need two panels, centre, and buttons. There are two reasons your UI is not showing up:
You never added the panels to the frame
You never set visible to true(Achieve this by using setVisible(true)), unless you did this in the class you ran it in.
One simple way to achieve your desired UI is like so(I added a main method to show the window):
import javax.swing.*;
import java.awt.*;
public class test extends JFrame {
public Test() {
super("test");
JPanel buttons = new JPanel();
JPanel centre = new JPanel();
add(buttons, BorderLayout.SOUTH); //these lines add the
add(centre, BorderLayout.CENTER); //panels to the frame
JButton clear = new JButton("Clear"); // No need
JButton copy = new JButton("Copy"); // to declare
JLabel label = new JLabel("Label"); // these
JTextField textfield = new JTextField("enter text here"); // privately
buttons.add(copy);
buttons.add(clear);
centre.add(label);
centre.add(textfield);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//added main method to run the UI
public static void main(String[] args) {
new Experiments();
} //end main
} //end class
And it shows the window:
I got closer but its not pretty code, the JFrame is 500x500 so this works based on that... any better suggestions than what I have?
package lab6;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("label");
textfield = new JTextField("enter text here");
JPanel masterPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel();
top.setPreferredSize(new Dimension(100, 200));
JPanel bottom = new JPanel();
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel ();
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom);
centre.add(subCentre);
masterPanel.add(bottom, BorderLayout.PAGE_END);
masterPanel.add(top, BorderLayout.PAGE_START);
masterPanel.add(centre, BorderLayout.CENTER);
add(masterPanel);
}
}
There are two things that I am trying to figure out. First thing, I want to figure out how to make a Jcomponent background transparent. When placing a JPanel into another JPanel that has a color set as the background, the JPanel that is set within the other JPanel has a white background that I can't seem to get rid of. I tried using the firstpanel.setOpache function and repaint but it doesn't do anything.
And second, I noticed that putting a JPanel within another JPanel thats within another JPanel compresses it size. The images below will show what I am trying to describe. I want to know what to do to avoid compressing the JPanel size and still able to put it within two levels of other JPanels . The code below is what I am practicing with.
import javax.swing.*;
import java.awt.*;
public class LearningFrame extends JFrame {
private JLabel userLabel;
private LearningFrame(){
JPanel backGroundPanel = new JPanel();
JPanel mainPanel = new JPanel();
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
userLabel = new JLabel("User");
userLabel.setFont(new Font("Arial",1 ,24));
backGroundPanel.setBackground(new Color(247,211,53));
// backGroundPanel.setLayout(new BoxLayout(backGroundPanel,BoxLayout.Y_AXIS));
setContentPane(backGroundPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1200,800);
setLocationRelativeTo(null);
//backGroundPanel.setLayout(null);
mainPanel.setLayout(new GridLayout(1,2));
firstPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
secondPanel.setLayout(new BoxLayout(secondPanel,BoxLayout.Y_AXIS));
// firstPanel.setBackground(new Color(211,43,185));
secondPanel.setBackground(new Color(34,233,44));
JButton button = new JButton("Click");
JButton button2 = new JButton("Click");
JButton button3 = new JButton("Click");
JButton button4 = new JButton("Click");
firstPanel.add(button);
firstPanel.add(button2);
firstPanel.add(userLabel);
secondPanel.add(button3);
secondPanel.add(button4);
mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
backGroundPanel.add(mainPanel);
setVisible(true);
}
public JPanel logPanel() {
JPanel logInPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JTextField userTextField = new JTextField(14);
JTextField passTextField = new JTextField(14);
userLabel = new JLabel("Username: ");
JLabel passLabel = new JLabel("Password: ");
passLabel.setFont(new Font("Arial", Font.BOLD, 24));
userLabel.setFont(new Font("Arial", Font.BOLD, 24));
logInPanel.add(userLabel);
logInPanel.add(userTextField);
logInPanel.add(passLabel);
logInPanel.add(passTextField);
logInPanel.setOpaque(true);
logInPanel.repaint();
return logInPanel;
}
public static void main(String[] args){
LearningFrame x = new LearningFrame();
}
}
Just use
firstPanel.setOpaque(false);
This is will make the background of the component invisible, but you will still be able to see any components that are positioned inside it.
I'm currently doing a quite simple GUI and was wondering how I could get the button in question out from the GridLayout and put it in its own say BorderLayout, if that's a bit vague I'll attach images to show you what I mean:
With that picture I would like the button to not be with the grid layout and for it to fill all the way across at the bottom of the program as it would in a border layout. My code is as follows:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Write a description of class HW4GUI here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class HW4GUI extends JFrame implements ActionListener
{
private JButton jbtAction;
private JTextField jtfFName;
private JTextField jtfLName;
private JTextField jtfLibNo;
private int nextLibNo;
private JPanel textPanel;
/**
* The constructor for the GUI, also initalises nextLibNo number
*/
public HW4GUI()
{
super("Adding a borrower");
makeFrame();
showFrame();
nextLibNo = 1001;
}
/**
*
*/
private void makeFrame()
{
setLayout(new GridLayout(4,0));
setResizable(false);
textPanel = new JPanel();
//textPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
textPanel.setLayout(new BorderLayout());
jtfFName = new JTextField(15);
JLabel fNLbl = new JLabel("First Name: ");
add(fNLbl);
add(jtfFName);
// add(textPanel);
fNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfFName.setEditable(true);
jtfLName = new JTextField(15);
JLabel lNLbl = new JLabel("Last Name: ");
add(lNLbl);
add(jtfLName);
//add(textPanel);
lNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLName.setEditable(true);
jtfLibNo = new JTextField(15);
JLabel lNOLbl = new JLabel("Library Number: ");
add(lNOLbl);
add(jtfLibNo);
// add(textPanel);
lNOLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLibNo.setEditable(false);
jbtAction = new JButton("Add Borrower");
add(jbtAction, BorderLayout.SOUTH);
jbtAction.addActionListener(this);
}
/**
* displays the frame window where you can set the size of it and also other variables
*/
private void showFrame()
{
setSize(400,200);
setResizable(false);
setLocationRelativeTo( null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String fn = jtfFName.getText();
String ln = jtfLName.getText();
boolean valid = true;
if (e.getActionCommand().equals("Add Borrower"))
{
if (fn.equals("") && (ln.equals("")))
{
jtfLibNo.setText("No Names");
valid = false;
}
else if (fn.equals("") )
{
jtfLibNo.setText("No First Name");
valid = false;
}
else if (ln.equals(""))
{
jtfLibNo.setText("No Last Name");
valid = false;
}
else
if (valid == true)
{
String lib = Integer.toString(nextLibNo++);
jtfLibNo.setText(lib);
jbtAction.setText("Confirm");
}
}
if (e.getActionCommand().equals("Confirm"))
{
jtfLibNo.setText("");
jbtAction.setText("Add Borrower");
}
}
}
As you have said that you want the Button outside your GridLayout, you can do:
Declare a new Panel, like mainPanel or something like that.
JPanel mp = new JPanel();
Set its layout to 3x1 using GridLayout.
mp.setlayout(new GridLayout(3,1));
Add you labels and text-fields to that panel.
mp.add(fNLbl);// and the rest.
Add this panel to your frame.
add(mp, BorderLayout.CENTER);
Then add the Button at the end, using, BorderLayout.SOUTH.
add(jbtAction, BorderLayout.SOUTH);
But as far as my knowledge goes, then your button will occupy the width of the whole frame. So, instead, you can add the button to a panel, and then add that panel to it. Like:
add( new JPanel(){{ add(jbtAction);}}, BorderLayout.SOUTH); // this is double-brace initialization.
The following code works fine:
private void makeFrame()
{
JPanel mp = new JPanel();
mp.setLayout(new GridLayout(3,1));
setResizable(false);
textPanel = new JPanel();
//textPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
textPanel.setLayout(new BorderLayout());
jtfFName = new JTextField(15);
JLabel fNLbl = new JLabel("First Name: ");
mp.add(fNLbl);
mp.add(jtfFName);
// add(textPanel);
fNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfFName.setEditable(true);
jtfLName = new JTextField(15);
JLabel lNLbl = new JLabel("Last Name: ");
mp.add(lNLbl);
mp.add(jtfLName);
//add(textPanel);
lNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLName.setEditable(true);
jtfLibNo = new JTextField(15);
JLabel lNOLbl = new JLabel("Library Number: ");
mp.add(lNOLbl);
mp.add(jtfLibNo);
// add(textPanel);
lNOLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLibNo.setEditable(false);
jbtAction = new JButton("Add Borrower");
add(mp, BorderLayout.CENTER);
add( new JPanel(){{ add(jbtAction);}}, BorderLayout.SOUTH);
jbtAction.addActionListener(this);
}
With that picture I would like the button to not be with the grid layout and for it to fill all the way across at the bottom of the program as it would in a border layout
Then use a BorderLayout. The default layout manager for a JFrame is a BorderLayout. So you would do somethinglike:
Create a panel using a GridLayout. Add the first 5 components to this panel. Then add the panel to the "CENTER" of the frame.
Create your button. Add the button the the "PAGE_END" of the frame.
The idea of layout managers is that you can nest panels with different layouts to achieve your final layout.
I also agree, the main panel with multiple buttons should probably be a GridBagLayout as it will size each column to the width of the widest component in the column instead of making every column width identical, which will make the panel look better. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.
I'm trying to draw a gui like shown in the figure, but somehow I'm not able to place the objects in right place (I guess that the problem is with the layout) the textArea is suppose to go in the middle... but is not showing at all
package Chapter22Collections;
import javax.swing.*;
import java.awt.*;
public class Exercise226 extends JFrame {
private JButton jbSort;
private JButton jbReverse;
private JButton jbAdd;
private JButton jbShuffle;
private JLabel jlAddnum;
private JTextArea jTextDisplay;
private JTextField jTextAdd;
public Exercise226() {
jbSort = new JButton("Sort");
jbReverse = new JButton("Reverse");
jbShuffle = new JButton("Shuffle");
jbAdd = new JButton("Add");
jlAddnum = new JLabel("Add number here: ");
jTextDisplay = new JTextArea();
jTextAdd = new JTextField(8);
setLayout(new BorderLayout());
JPanel p1 = new JPanel(new GridLayout(1,3));
p1.add(jlAddnum);
p1.add(jTextAdd);
p1.add(jbAdd);
JPanel p2 = new JPanel(new GridLayout(1,3));
p2.add(jbSort);
p2.add(jbReverse);
p2.add(jbShuffle);
add(p1, BorderLayout.NORTH);
add(jTextDisplay, BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);
}
public static void main(String... args) {
Exercise226 gui = new Exercise226();
gui.setTitle("Numbers");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 200);
gui.setLocationRelativeTo(null);
gui.setVisible(true);
}
}
The JTextArea is actually where you expect it to be but has no outline border. It is usual to place the component in a JScrollPane which will give this effect:
add(new JScrollPane(jTextDisplay), BorderLayout.CENTER);
or simply
add(new JScrollPane(jTextDisplay));
To make the textArea re-size with the window, try BoxLayout. Box is "A lightweight container that uses a BoxLayout object as its layout manager."
Box p1 = new Box(BoxLayout.X_AXIS);
How could I add spacing/padding between the elements in the frame? So the text area is more visible and centered.
Borders and padding. E.G.
Compared with:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Exercise226 {
private JButton jbSort;
private JButton jbReverse;
private JButton jbAdd;
private JButton jbShuffle;
private JLabel jlAddnum;
private JTextArea jTextDisplay;
private JTextField jTextAdd;
private JPanel gui;
public Exercise226() {
gui = new JPanel(new BorderLayout(5,5));
jbSort = new JButton("Sort");
jbReverse = new JButton("Reverse");
jbShuffle = new JButton("Shuffle");
jbAdd = new JButton("Add");
jlAddnum = new JLabel("Add number here: ");
// set the size constraints using columns/rows
jTextDisplay = new JTextArea("Here I am!", 6,20);
jTextAdd = new JTextField(8);
JPanel p1 = new JPanel(new GridLayout(1,3,3,3));
p1.add(jlAddnum);
p1.add(jTextAdd);
p1.add(jbAdd);
JPanel p2 = new JPanel(new GridLayout(1,3,3,3));
p2.add(jbSort);
p2.add(jbReverse);
p2.add(jbShuffle);
JPanel textAreaContainer = new JPanel(new GridLayout());
textAreaContainer.add(new JScrollPane(jTextDisplay));
textAreaContainer.setBorder(new TitledBorder("Text Area Here"));
gui.add(p1, BorderLayout.PAGE_START);
gui.add(textAreaContainer, BorderLayout.CENTER);
gui.add(p2, BorderLayout.PAGE_END);
gui.setBorder(new EmptyBorder(4,4,4,4));
}
public Container getGui() {
return gui;
}
public static void main(String... args) {
JFrame f = new JFrame();
Exercise226 gui = new Exercise226();
f.setContentPane(gui.getGui());
f.setTitle("Numbers");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
}
This code:
Primarily provides 'white space' in the GUI using different constructors for the layouts that accept 2 int arguments for horizontal & vertical spacing.
Also adds 2 borders:
An empty border around the entire GUI to provide some spacing between it and the frame decorations.
A titled border around the text area, to make it very obvious.
Does implement a change for one unnecessary part of the original code. Instead of extending frame, it simply retains an instance of one.
Uses the JScrollPane container for the text area, as suggested by #Reimeus. It adds a nice beveled border of its own to an element that needs no scroll bars.
Creates a textAreaContainer specifically so that we can set a titled border to surround the scroll pane - without interfering with its existing border. It is possible to use a CompoundBorder for the scroll pane that consists of the existing border (scroll.getBorder()) & the titled border. However that gets complicated with buttons & other elements that might change borders on selection or action. So to set an 'outermost border' for a screen element (like the text area here) - I generally prefer to wrap the entire component in another container first.
Does not create and show the GUI on the EDT. Swing GUIs should be created and modified on the EDT. Left as an exercise for the user. See Concurrency in Swing for more details.
Old Code
The original code on this answer that provides the 'comparison GUI image' seen above. IT is closely based on the original code but with the text area wrapped in a scroll pane (and gaining a beveled border because of that) & given some text to display.
import javax.swing.*;
import java.awt.*;
public class Exercise226 extends JFrame {
private JButton jbSort;
private JButton jbReverse;
private JButton jbAdd;
private JButton jbShuffle;
private JLabel jlAddnum;
private JTextArea jTextDisplay;
private JTextField jTextAdd;
public Exercise226() {
jbSort = new JButton("Sort");
jbReverse = new JButton("Reverse");
jbShuffle = new JButton("Shuffle");
jbAdd = new JButton("Add");
jlAddnum = new JLabel("Add number here: ");
// set the size constraints using columns/rows
jTextDisplay = new JTextArea("Here I am!", 6,20);
jTextAdd = new JTextField(8);
setLayout(new BorderLayout());
JPanel p1 = new JPanel(new GridLayout(1,3));
p1.add(jlAddnum);
p1.add(jTextAdd);
p1.add(jbAdd);
JPanel p2 = new JPanel(new GridLayout(1,3));
p2.add(jbSort);
p2.add(jbReverse);
p2.add(jbShuffle);
add(p1, BorderLayout.NORTH);
add(new JScrollPane(jTextDisplay), BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);
}
public static void main(String... args) {
Exercise226 gui = new Exercise226();
gui.setTitle("Numbers");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//gui.setSize(300, 200);
gui.pack();
//gui.setLocationRelativeTo(null);
gui.setLocationByPlatform(true);
gui.setVisible(true);
}
}