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.
Related
I'm currently self-studying Java. I'm learning Graphical User Interface(GUI) programming.
I want JPanels to be arranged from top to bottom in a JFrame.First of all,I have a JLabel added to the first JPanel. The second JPanel has 5 JRadioButtions. The third JPanel has a JButton and a JLabel.
When the JButton is pressed,the JLabel in the 3rd JPanel shows some text.
I used BoxLayout(BoxLayout.X_AXIS) for all the JPanels and added all 3 of them into a JFrame which has FlowLayout(). Here is a small piece of code:
class GUI extends JFrame implements ActionListener {
JPanel pan1,pan2,pan3; //3 JPanels
JRadioButton rad1,rad2,rad3,rad4,rad5; //5 RadioButtons
JButton button; //A JButton
JLabel label; //A JLabel
public GUI(String header)
{
super(header);
setLayout(new FlowLayout()); //set FlowLayout to JFrame
setBounds(350,325,600,125);
setResizable(false);
creator();
adder();
commander();
add(pan1);
add(pan2);
add(pan3); //Add all 3 panels to JFrame
}
private void adder()
{
pan1.setLayout(new BoxLayout(pan1,BoxLayout.X_AXIS));
pan2.setLayout(new BoxLayout(pan2,BoxLayout.X_AXIS));
pan3.setLayout(new BoxLayout(pan3,BoxLayout.X_AXIS)); //Layout for all 3 JPanels
pan1.add(new JLabel("Choose a Security Level"));
ButtonGroup group=new ButtonGroup();
group.add(rad1);
group.add(rad2);
group.add(rad3);
group.add(rad4);
group.add(rad5);
pan2.add(rad1);
pan2.add(rad2);
pan2.add(rad3);
pan2.add(rad4);
pan2.add(rad5);
pan3.add(button);
pan3.add(label);
}
private void creator()
{
pan1=new JPanel();
pan2=new JPanel();
pan3=new JPanel();
rad1=new JRadioButton("Security Level 1");
rad2=new JRadioButton("Security Level 2");
rad3=new JRadioButton("Security Level 3");
rad4=new JRadioButton("Security Level 4");
rad5=new JRadioButton("Security Level 5");
button=new JButton("Move On");
label=new JLabel();
}
private void commander()
{
rad1.addActionListener(this);
rad2.addActionListener(this);
rad3.addActionListener(this);
rad4.addActionListener(this);
rad5.addActionListener(this);
rad1.setActionCommand("radio1");
rad2.setActionCommand("radio2");
rad3.setActionCommand("radio3");
rad4.setActionCommand("radio4");
rad5.setActionCommand("radio5");
button.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
//When button is pressed,the text in label changes
if(evt.getActionCommand().equals("radio1"))
label.setText("Very Easy to bypass");
else if(evt.getActionCommand().equals("radio2"))
label.setText("Easy to bypass");
else if(evt.getActionCommand().equals("radio3"))
label.setText("Can bypass Sometimes");
else if(evt.getActionCommand().equals("radio4"))
label.setText("Hard to bypass");
else if(evt.getActionCommand().equals("radio5"))
label.setText("Very Hard to bypass");
else
{ //Code here
}
repaint();
//More code here....
}
}
This is the output I'm getting when I select the first radiobutton(Forget the green colour):
I want the "Very easy to Bypass" text to be placed above the "Move on" button and below all the JRadioButtons. I can increase the size of the JFrame so that there will be enough space. My questions are:
Which Layout should I use to achieve this?
Should this layout be applied just for the JFrame or all 3 JPanels?
you must use GridLayout
Its very easy to use it, just add it like this. Take care of the import commands. :)
JFrame frame = new JFrame(new GridLayout(3,5));
Use GridLayout
GridLayout layout = new GridLayout(0, 1, 0, 5);
setLayout(layout);
What I would do to add 5 JPanels:
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PanelAdd extends JFrame {
JPanel [] panels ;
public PanelAdd() {
GridLayout layout = new GridLayout(0, 1, 0, 5);
setLayout(layout);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setSize(400, 350);
}
public static void main(String [] args) {
PanelAdd add = new PanelAdd();
add.addPanels();
add.setVisible(true);
}
private void addPanels() {
panels = new JPanel[5];
for (int i = 0 ; i < panels.length ; i++) {
panels[i] = new JPanel();
panels[i].add(new JLabel("This Is Panel "+i));
add(panels[i]);
}
}
}
In this example, I made an array of 5 JPanels and add them through a loop.
I used GridLayout for the job.
This is just a hint for your answer
when you call add method from jframe,you can also give specified position to your panel in frame
like this:
JPanel pan1,pan2,pan3; //3 JPanels
JRadioButton rad1,rad2,rad3,rad4,rad5; //5 RadioButtons
JButton button; //A JButton
JLabel label; //A JLabel
public GUI(String header)
{
super(header);
setLayout(new FlowLayout()); //set FlowLayout to JFrame
setBounds(350,325,600,125);
setResizable(false);
creator();
adder();
commander();
add(pan1,BorderLayout.NORTH);
add(pan2,BorderLayout.CENTER);
add(pan3,,BorderLayout.SOUTH); //Add all panels to JFrame
}
good luck
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?
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.
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);
}
}
Right, I have a JTabbedPane that has a JPanel that contains a JLabel and a JTextField.
my code
JTabbed Pane declaration :
this.tabPane = new JTabbedPane();
this.tabPane.setSize(750, 50);
this.tabPane.setLocation(10, 10);
tabPane.setSize(750,450);
tabPane.add("ControlPanel",controlPanel);
textfield declaration :
this.channelTxtFld = new JTextField("");
this.channelTxtFld.setFont(this.indentedFont);
this.channelTxtFld.setSize(200, 30);
this.channelTxtFld.setLocation(200, 10);
JLabel :
this.channelLabel = new JLabel("Channel name : ");
this.channelLabel.setSize(150, 30);
this.channelLabel.setLocation(10,10);
private void createPanels() {
controlPanel = new JPanel();
controlPanel.setSize(650,500);
}
private void fillPanels() {
controlPanel.add(channelLabel);
controlPanel.add(channelTxtFld);
}
So what my plan is, was to have a tabbed pane that has a JPanel where I have some Labels, textfields and buttons on fixed positions, but after doing this this is my result:
http://i.stack.imgur.com/vXa68.png
What I wanted was that I had the JLabel and next to it a full grown JTextfield on the left side not in the middle.
Anyone any idea what my mistake is ?
thank you :)
What kind of Layout Manager are you using for your controlPanel, you probably want BorderLayout, putting the Label in the West, and the TextField in the center.
BTW, setting the size and position of various components doesn't make sense unless you are using a Null Layout, which isn't a good idea. So i'd remove all that stuff and let the Layout Manager do it for you.
Use a LayoutManager and consider also the methods setPreferredSize, setMinimumSize, setMaximumSize to adjust components bounds according on which is your desired effect.
Assuming the default JPanel layout, FlowLayout, give the JTextField a non-zero number of columns, and give the JLabel a JLabel.LEFT constraint.
Addendum:
a full grown JTextField
Something like this?
import java.awt.*;
import javax.swing.*;
/**
* #see http://stackoverflow.com/questions/5773874
*/
public class JTabbedText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.setPreferredSize(new Dimension(400, 200));
jtp.addTab("Control", new MyPanel("Channel"));
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
private static class MyPanel extends JPanel {
private final JLabel label = new JLabel("", JLabel.LEFT);
private final JTextField text = new JTextField();
public MyPanel(String name) {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
label.setText(name);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
text.setAlignmentY(JTextField.TOP_ALIGNMENT);
this.add(label);
this.add(text);
}
}
}