JTabbedPane won't let me change the layout - java

I'm probably just an idiot. Anyways, I was trying out multiple things and eventually I got my code to work but my panel won't let me place the buttons and components where I want them to go. Since I'm new, all I've really used are the basics such as content pane, set size, and flow layout.
Anyways, here's what's happening:
without the frame pack
I feel it's something simple but I've been looking online for answers and either I already came across it and didn't realize, it's a small mistake, or I forgot a line somewhere.
Either way, thanks to those who can help me.
Code Below:
package CourseProject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EngineerCalculator extends JFrame {
//Frame
JFrame frame = new JFrame();
//Create the object
JTabbedPane jtp = new JTabbedPane();
//panel
JPanel panel = new JPanel();
Pools pools = new Pools();
HotTubs hotTubs = new HotTubs();
public EngineerCalculator() {
//This creates the template on the windowed application that we will be using
frame.getContentPane().add(jtp);
//Tab Creation
JPanel pTemperature = new JPanel();
JPanel pLength = new JPanel();
JPanel pEdit = new JPanel();
JPanel pCustInfo = new JPanel();
JPanel pCoInfo = new JPanel();
JPanel pGeneral = new JPanel();
//Label additions
JLabel lTemperature = new JLabel();
JLabel lLength = new JLabel();
JLabel lEdit = new JLabel();
JLabel lCustInfo = new JLabel();
JLabel lCoInfo = new JLabel();
JLabel lGeneral = new JLabel();
//Label editing
lGeneral.setText("Date, time, and job informaiton will go here");
pGeneral.add(lGeneral);
//Adds the first tabs to our tab pane objects
jtp.addTab("Pools", pools);
jtp.addTab("Hot Tub", hotTubs);
jtp.addTab("Temp Convert", pTemperature);
jtp.addTab("Length Convert", pLength);
jtp.addTab("Edit", pEdit);
jtp.addTab("Customers", pCustInfo);
jtp.addTab("Company", pCoInfo);
jtp.addTab("General", pGeneral);
//This will create the title you see in the upper left of the window
setTitle("Engineer Specifications Calculator");
//Set size
frame.setSize(345, 400);
frame.setVisible(true);
}
public static void main (String []args){
EngineerCalculator tab = new EngineerCalculator();
Temperature temperature = new Temperature();
Length length = new Length();
Edit edit = new Edit();
CustInfo custInfo = new CustInfo();
CoInfo coInfo = new CoInfo();
General general = new General();
}
}

Related

How to add to a JPanel from another class

I've been spending the past few hours trying to figure out how to use a panel in my GUI class from a class named algorithms. I know this question has been asked before, But I cant seem to figure out how to incorporate it into my code, so I would appreciate any form of guidance.
Specifically, in my algorithms class I was testing trying to change the JLabel named title by creating a instance of my GUI class and then trying to use title.setText(), however it returns a Null Pointer Exception.
The title JLabel is located on my JPanel named topPanel
I know I'm not doing something right, I've struggled with this for the past few hours and cant seem to make any progress. Like I said, any guidance would be appreciated.
GUI.java
import javax.swing.*;
import java.awt.*;
import java.util.Date;
public class GUI extends JFrame {
public JFrame myFrame;
public JPanel firstFitDisplay,topPanel;
public JLabel title;
public Timer timer;
public int count=0;
public GUI(){
}
public void initGUI(){
JFrame myFrame = new JFrame();
myFrame.setTitle("CIS 452 Dynamic Memory Allocation Project");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setResizable(true);
myFrame.setLayout(new BorderLayout(6,6));
myFrame.setSize(1000,700);
myFrame.setVisible(true);
//myFrame.getContentPane().setBackground(Color.white);
//setup panels
JPanel infoPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel topPanel = new JPanel();
JPanel bottom = new JPanel();
infoPanel.setBackground(Color.cyan);
centerPanel.setBackground(Color.red);
topPanel.setBackground(Color.yellow);
bottom.setBackground(Color.pink);
infoPanel.setPreferredSize(new Dimension(200,1000));
centerPanel.setPreferredSize(new Dimension(500,500));
topPanel.setPreferredSize(new Dimension(750,20));
bottom.setPreferredSize(new Dimension(750,25));
//setup layout for panels, so that we can add subpanels
infoPanel.setLayout(new BoxLayout(infoPanel,BoxLayout.PAGE_AXIS));
//add panels to main frame
myFrame.add(infoPanel,BorderLayout.WEST);
myFrame.add(centerPanel,BorderLayout.CENTER);
myFrame.add(topPanel,BorderLayout.NORTH);
myFrame.add(bottom,BorderLayout.SOUTH);
// setup sub panels for infoPanel
JPanel infoSubPanel = new JPanel();
infoSubPanel.setBackground(Color.pink);
infoSubPanel.setPreferredSize(new Dimension(50,90));
infoPanel.add(infoSubPanel);
//setting up text for infoSubPanel
JLabel subPanelTitle = new JLabel("Next Process Size to be allocated");
JLabel firstFitNextUpLabel = new JLabel("First:0");
JLabel bestFitNextUpLabel = new JLabel("Best:0");
JLabel worstFitNextUpLabel = new JLabel("Worst:0");
infoSubPanel.add(subPanelTitle);
infoSubPanel.add(firstFitNextUpLabel);
infoSubPanel.add(bestFitNextUpLabel);
infoSubPanel.add(worstFitNextUpLabel);
//subClockPanel
JPanel infoSubClockPanel = new JPanel();
infoSubClockPanel.setBackground(Color.GRAY);
infoSubClockPanel.setPreferredSize(new Dimension(50,90));
infoPanel.add(infoSubClockPanel);
//setting up text for sub clock panel
JLabel clockText = new JLabel("Seconds passed: ");
int ten = 10;
JLabel clockCounter = new JLabel("0");
infoSubClockPanel.add(clockText);
infoSubClockPanel.add(clockCounter);
//logic for running timer;
timer = new Timer(1000, e -> {
clockCounter.setText(String.valueOf(count++));
});
timer.start();
//setting up sub panels for the main center panel
centerPanel.setLayout(new FlowLayout());
JPanel firstFitDisplay = new JPanel();
JPanel bestFitDisplay = new JPanel();
JPanel worstFitDisplay = new JPanel();
firstFitDisplay.setPreferredSize(new Dimension(200,500));
bestFitDisplay.setPreferredSize(new Dimension(200,500));
worstFitDisplay.setPreferredSize(new Dimension(200,500));
centerPanel.add(firstFitDisplay);
centerPanel.add(bestFitDisplay);
centerPanel.add(worstFitDisplay);
//center components
centerPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
firstFitDisplay.setAlignmentX(Component.CENTER_ALIGNMENT);
//setup title
JLabel title = new JLabel("Dynamic Memory Allocation Simulator");
topPanel.add(title);
}
}
and here is algorithms.java
import javax.swing.*;
import java.awt.*;
public class algorithms {
public static void main(String[] args) {
GUI f = new GUI();
f.initGUI();
f.title.setText("HHHHHHHHHHH");
}
}
so your mistake is that you never define title in your GUI class. I think you intended to with this line:
JLabel title = new JLabel("Dynamic Memory Allocation Simulator");
This actually creates a new local variable called title instead of defining the global one. So the global variable is still null. To fix this simply change that to like to this:
this.title = new JLabel("Dynamic Memory Allocation Simulator");
Now it will define the global variable! This shouldn't give a null pointer exception now.

JDialog is not showing up

I have this problem over and over again when i call my JDialog class is not showing anything this is the code for the JDialog interface:
public JMovie() {
JFrame f = new JFrame();
JDialog jmovie = new JDialog(f,"JMovie Dialog");
jmovie.setLayout(new BorderLayout());
okbutton = new JButton("Ok");
cancelbutton = new JButton("Cancel");
title = new JLabel("Title", SwingConstants.RIGHT);
date = new JLabel("Date made on ", SwingConstants.RIGHT);
price = new JLabel("Price", SwingConstants.RIGHT);
inputdate = new JLabel("dd/mm/yyyy");
Ttitle = new JTextField(null, 15);
TMadeon = new JTextField(null, 10);
TPrice = new JTextField(null, 6);
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jb = new JPanel();
jl = new JPanel();
okbutton.addActionListener(this);
cancelbutton.addActionListener(this);
Ttitle.setName("Title");
TMadeon.setName("Date Made on");
TPrice.setName("Price");
jb.add(okbutton);
jb.add(cancelbutton);
title.setAlignmentX(Component.RIGHT_ALIGNMENT);
date.setAlignmentX(Component.RIGHT_ALIGNMENT);
price.setAlignmentX(Component.RIGHT_ALIGNMENT);
JPanel south = new JPanel(new FlowLayout());
south.add(jb, BorderLayout.SOUTH);
JPanel west = new JPanel(new GridLayout(3,1));
west.add(title,BorderLayout.WEST);
west.add(date,BorderLayout.WEST);
west.add(price,BorderLayout.WEST);
JPanel center = new JPanel(new GridLayout(3,1));
center.add(jp3,FlowLayout.LEFT);
center.add(jp2,FlowLayout.LEFT);
center.add(jp1,FlowLayout.LEFT);
inputdate.setEnabled(false);
jmovie.setSize(350, 150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
}
This is the code of the interface JMovie DIalog and i call it here in another class.
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(btnMAdd))
{
JMovie ne = new JMovie();
ne.setVisible(true);
}
}
when i run it is showing this:
First of all, variable names should NOT start with an upper case character. Some variables are correct, others are not. Follow Java conventions and be consistent!
jmovie.setSize(350, 150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
Component should be added to the dialog BEFORE the dialog is made visible.
So the code should be:
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
jmovie.setSize(350, 150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
You should be using pack() instead of setVisible(...). This will allow all the components to be displayed at their preferred size.
JFrame f = new JFrame();
Also, you should not be create a JFrame. The parameter you want to pass to the JDialog, is the current visible JFrame.
So in your ActionListener you can get the current frame with logic like:
Window window = SwingUtilities.windowForComponent( btnMAdd );
Now when you create your dialog you pass the window as a parameter:
JMovie ne = new JMovie(window);
and you use this value to specify the parent window of your dialog.

Text boxes squished in Swing layout

I have a frame that opens when you click file>new user, but the text fields are all squished together.
I'm trying to have them all stacked vertically so I use new GridLayout(3, 2) as my LayoutManager. However, the stuff for the new window is all the way at the bottom.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class App extends JFrame implements ActionListener
{
private final int WIDTH = 300;
private final int HEIGHT = 550;
private int control = 0;
String[] username = new String[10];
String[] pass = new String[10];
private String tempName;
private String tempPass;
Container con = getContentPane();
JPanel panel = new JPanel();
private JTextField name = new JTextField();
private JPasswordField password = new JPasswordField();
JMenuBar mainBar = new JMenuBar();
JMenu menu1 = new JMenu("File");
JMenu menu2 = new JMenu("Edit");
JMenuItem newUser = new JMenuItem("New User");
JButton but1 = new JButton("Log In");
JButton but2 = new JButton("test");
JLabel error = new JLabel("Login info not corret\n Or user not registered.");
JLabel success = new JLabel("Success!");
/////////////stuff for dialog///////////////////
JPanel panel2 = new JPanel();
JTextField newModalUser = new JTextField();
JPasswordField newModalPass = new JPasswordField();
JPasswordField newModalPassCon = new JPasswordField();
JButton register = new JButton("Register");
////////////////////////////////////////////////
public static void main(String[] args)
{
App frame = new App();
}
public App()
{
//just settin some stuff up
super("For The Bold");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//setResizable(false);
setVisible(true);
//add menubar
setJMenuBar(mainBar);
mainBar.add(menu1);
menu1.add(newUser);
//background of main JFrame
setContentPane(new JLabel(new ImageIcon("//Users//ryanchampin//Desktop//GUI app//image.png")));
//test names in the arrays
username[0] = "ryan";
pass[0] = "test";
//main stuff in the middle
//panel.setBackground(Color.RED);
panel.setSize(300,300);
panel.add(name);
panel.add(password);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS ));
panel.add(but1);
panel.add(but2);
add(panel,new GridBagConstraints());
setLayout(new GridBagLayout());
//assign action listener
but1.addActionListener(this);
newUser.addActionListener(this);
register.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
tempName = name.getText();
tempPass = password.getText();
if(source == but1)
{
for(int x = 0; x < username.length; x++)
{
if(tempName.equalsIgnoreCase(username[x]) && tempPass.equals(pass[x]))
{
//display success JLabel
add(success);
System.out.println("success");
break;
}
else
{
success.setText(null);
add(error);
name.setText(null);
password.setText(null);
}
}
}
else
if(source == newUser)
{
panel.setVisible(false);
setLayout(new GridLayout(3,2));
add(panel2);
panel2.add(newModalUser);
panel2.add(newModalPass);
panel2.add(newModalPassCon);
panel2.add(register);
}
else if(source == register)
System.out.println("yay it worked");
}
}
Avoid using setSize(...) or setPreferredSize(...) if possible.
Instead let the components and their layout managers set their own sizes.
Use a CardLayout to swap views instead of what you're doing. If you do this, the CardLayout will size its container to fit all the "cards" that it has been given.
Don't forget to call pack() on the GUI after adding all components
Don't forget to call setVisible(true) after adding all components and after calling pack.
When creating new JTextFields and JPasswordFields, pass in an int for the number of columns into the constructors.
Edit
You ask:
whats pack() used for?
The pack() method tells the GUI to have all the layout managers of its constituent containers to lay out their components, and then to set the best size of the GUI after every component has been properly placed.
If you want spacing in a GridLayout, you can use the setHgap(int) and setVgap(int) methods to set the number of pixels of space that will appear between each element in the grid.
In your code, there are two ways you could do this: construct a GridLayout and call the two setter methods on it, then pass it into the setLayout(LayoutManager) method:
GridLayout layout = new GridLayout(3, 2);
layout.setHgap(5); // or whatever number of pixels you want
layout.setVgap(5); // same
setLayout(layout);
Alternatively, you could cast the LayoutManager you would get from calling getLayout() and call the two methods on it:
setLayout(new GridLayout(3, 2));
((GridLayout) getLayout()).setHgap(5);
((GridLayout) getLayout()).setVgap(5);
if you want them stacked vertically, wouldn't it be easier to keep using BoxLayout?

My GUI window doesn't show anything

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.

GUI not showing as intended

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);
}
}

Categories