Since im a beginner and i don't want to get involved with the layout managers, i was simply adding a JPanel into my main JFrame and giving spesific location to each component in the panel. But somehow the output appears way too wrong..
frame = new JFrame(email + " (Offline)");
frame.setSize(400, 400);
frame.setLocation(0, 0);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
// out.println("BYE");
// out.flush();
frame.dispose();
thread.stop();
}
});
panel = new JPanel();
frame.add(panel);
chat = new JTextArea();
chat.setSize(400, 200);
chat.setLocation(0, 0);
chat.setEditable(false);
panel.add(chat);
panel.validate();
JLabel you = new JLabel("You:");
you.setSize(you.getPreferredSize());
you.setLocation(0, 210);
panel.add(you);
panel.validate();
input = new JTextArea();
input.setSize(200, 200);
input.setLocation(0, 220 + chat.getSize().height);
panel.add(input);
panel.validate();
send = new JButton("Send");
send.setSize(send.getPreferredSize());
send.setLocation(210, 220 + chat.getSize().height);
panel.add(send);
panel.validate();
frame.setVisible(true);
The outcome of this frame is that text areas are invisible, a You: label in the middle and next to the right of it the button.. What am i missing here?
Again, don't use null layout since it makes updating and maintaining your GUI much more difficult than it should be, and can lead to ugly GUI's if you plan on having them run on multiple platforms. Instead
Use several JPanels, each one holding a core group of components and each using its best layout manager
Nest these JPanels in other JPanels that use the best layout manager to display them
and that will allow your GUI to be resizeable without need of extra code.
Put your JTextAreas in JScrollPanes so that you can see all text even if it goes beyond the text area.
Never set the size of the JTextArea as that will not allow it to scroll. Instead set its columns and rows.
As a very simple example, run this to see what I mean:
import java.awt.*;
import javax.swing.*;
public class FooSwing2 {
public static void main(String[] args) {
JTextArea chatArea = new JTextArea(8, 40);
chatArea.setEditable(false);
chatArea.setFocusable(false);
JScrollPane chatScroll = new JScrollPane(chatArea);
JPanel chatPanel = new JPanel(new BorderLayout());
chatPanel.add(new JLabel("Chat:", SwingConstants.LEFT), BorderLayout.PAGE_START);
chatPanel.add(chatScroll);
JTextField inputField = new JTextField(40);
JButton sendBtn = new JButton("Send");
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
inputPanel.add(inputField);
inputPanel.add(sendBtn);
JPanel youLabelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
youLabelPanel.add(new JLabel("You:"));
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.add(chatPanel);
mainPanel.add(Box.createVerticalStrut(10));
mainPanel.add(youLabelPanel);
mainPanel.add(inputPanel);
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
This would result in a simple (non-functioning) GUI that looked like this:
Now say you want to change this and add another button, an "exit" JButton to the right of the send JButton. If you used null layout, you'd have to resize your GUI, you'd have to move the send button over to the left and make sure that your math was without error, etc. If you used layout managers, you'd need just two new lines of code (to change the display, not the functionality of course):
JTextField inputField = new JTextField(40);
JButton sendBtn = new JButton("Send");
JButton exitBtn = new JButton("Exit"); // ***** added
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
inputPanel.add(inputField);
inputPanel.add(sendBtn);
inputPanel.add(exitBtn); // ***** added
That's it, and this would display:
Related
I try to program a GUI like this. When a button clicked every time a new button is created and placed at specific position but after adding some buttons in jscrollpane, scrollbar not activated, so I unable to see all created buttons.
My code is here:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test{
private JFrame frame;
private JPanel panel1,panel2;
private JScrollPane pane;
private JButton button;
int i = 1, y = 10;
public Test()
{
panel2 = new JPanel(null);
panel2.setBounds(0,0,280,300);
button = new JButton("Add Button");
button.setBounds(90,10,120,30);
pane = new JScrollPane();
pane.setBounds(10,50,280,300);
panel1 = new JPanel(null);
panel1.setPreferredSize(new Dimension(300,400));
panel1.setBackground(Color.WHITE);
frame = new JFrame("Test");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
panel1.add(pane);
panel1.add(button);
pane.add(panel2);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
i += 1;
y += 35;
}
});
}
public static void main(String[] args) {
new Test();
}
}
Don't use a null layout. Don't use setBounds().
The scrollbars will only appear automatically when the preferred size of the panel is greater that the size of the scroll pane.
It is the job of the layout manager to:
set the location of a component
set the size of a component
calculate the preferred size of the panel.
So the solution is to use the appropriate layout manager on your panel.
So for example you can use a BoxLayout:
//panel2 = new JPanel(null);
panel2 = new JPanel();
panel2.setLayout( new BoxLayout(panel2, BoxLayout.Y_AXIS) );
And then when you add components to a visible frame you need to revalidate() the panel to invoke the layout manager:
//panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
panel2.add(new JButton("Button "+i));
panel2.revalidate();
There is no need for panel1. Just add the components to the frame:
//panel1.add(pane);
//panel1.add(button);
frame.add(button, BorderLayout.PAGE_START);
frame.add(pane, BorderLayout.CENTER);
But there are other issues:
pane = new JScrollPane();
You actually need to add the panel to the scroll pane. So the code should be:
pane = new JScrollPane(panel2);
Since a component can only have a single parent, you need to remove:
pane.add(panel2);
Since the panel2 has been added to the scroll pane.
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
The above logic is wrong.
You should only invoked pack() and setVisible( true ) AFTER all the component have been added to the frame.
So most of the code posted is wrong.
Start by reading the section from the Swing turtorial on Layout Managers. Download the working demo code and learn how to better structure your code. The modify the code for your specific example.
Looked at some previous posts pertaining to my subject but too no avail.
Trying to align components using BoxLayout but I cannot get it to work. I have tinkered with it for some time now with different results but I can't figure it out. I have used the default FlowLayout with no problems, I am trying to learn and expand my knowledge and BoxLayout will be better for my program. I want everything to stay in alignment if the User resizes their application window. I've adjusted all the sizes this way after just trying to get it to work and failing.
package GUI;
import javax.swing.*;
import java.awt.*;
/**
* Created by Thunderfoot on 7/31/2016. Keep Growing!
* Graphical User Interface
* Needs 3 JPanels(Text area + scroll pane)(2 Buttons) (1 Button), a JTextArea, JScrollPane, and 3 JButtons
*/
public class PrimaryFrame extends JFrame {
//Class variables
private static JPanel panel1, panel2, panel3;
public static JTextArea output;
//Constructor
public PrimaryFrame() {
//Frame component attributes
final Dimension FRAME_SIZE = new Dimension(400, 400);
final Dimension PANEL1_SIZE = new Dimension(400, 250);
final Dimension PANEL2_SIZE = new Dimension(400, 40);
final Dimension PANEL3_SIZE = new Dimension(400, 40);
//JFrame is PrimaryFrame
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(FRAME_SIZE);
setMaximumSize(FRAME_SIZE);
setTitle("Fighting Game");
//JPanel for Text
panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.PAGE_AXIS));
panel1.setMinimumSize(PANEL1_SIZE);
panel1.setPreferredSize(PANEL1_SIZE);
panel1.setMaximumSize(PANEL1_SIZE);
panel1.setBackground(Color.BLACK);
//JPanel for Attack and Kick Buttons
panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, BoxLayout.LINE_AXIS));
panel2.setMinimumSize(PANEL2_SIZE);
panel2.setPreferredSize(PANEL2_SIZE);
panel2.setMaximumSize(PANEL2_SIZE);
panel2.setBackground(Color.BLUE);
//JPanel for Power Attack Button
panel3 = new JPanel();
panel3.setLayout(new BoxLayout(panel3, BoxLayout.PAGE_AXIS));
panel3.setMinimumSize(PANEL3_SIZE);
panel3.setPreferredSize(PANEL3_SIZE);
panel3.setMaximumSize(PANEL3_SIZE);
panel3.setBackground(Color.ORANGE);
panel3.add(Box.createHorizontalGlue());
panel3.add(Box.createVerticalGlue());
//JTextArea & JScrollPane
output = new JTextArea();
output.setEditable(false);
JScrollPane outputScroller = new JScrollPane(output, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outputScroller.setMaximumSize(new Dimension(375, 250));
outputScroller.setBorder(BorderFactory.createLineBorder(Color.RED));
panel1.add(outputScroller);
panel1.add(Box.createHorizontalGlue());
panel1.add(Box.createVerticalGlue());
//Attack Button
JButton attackButton = new JButton(" ATTACK ");
attackButton.setMaximumSize(new Dimension(75, 30));
attackButton.setBorderPainted(true);
//Kick Button
JButton kickButton = new JButton(" KICK ");
kickButton.setMaximumSize(new Dimension(75, 30));
kickButton.setBorderPainted(true);
//Add components
panel2.add(attackButton);
panel2.add(Box.createHorizontalGlue());
panel2.add(Box.createVerticalGlue());
panel2.add(kickButton);
panel2.add(Box.createHorizontalGlue());
panel2.add(Box.createVerticalGlue());
//Power Attack Button
JButton powAttButton = new JButton(" POWER ATTACK ");
powAttButton.setMaximumSize(new Dimension(150, 30));
powAttButton.setBorderPainted(true);
panel3.add(powAttButton);
panel3.add(Box.createHorizontalGlue());
}
public void buildGUI() {
//Add components and build GUI Frame
this.add(panel3);
this.add(panel2);
this.add(panel1);
//Set attributes
//Pack components together inside of frame
pack();
//Center of screen
setLocationRelativeTo(null);
//Make frame visible
setVisible(true);
}
}
You have to set the Layout of your PrimaryFrame.
I suggest you add an additional line to your buildGUI() method:
public void buildGUI() {
//defines the Layout for the main Frame
this.setLayout(new GridLayout(3,1)) //its up to you wich Layout you use
//Add components and build GUI Frame
this.add(panel3);
this.add(panel2);
this.add(panel1);
//Set attributes
//Pack components together inside of frame
pack();
//Center of screen
setLocationRelativeTo(null);
//Make frame visible
setVisible(true);
}
Notice GridLayout(3,1) will generate a layout with three rows and one column
Below is a simplified version of my Java program.
It works fine until I add the line
JComboBox comboBox = new JComboBox(options);
After adding that line nothing no longer shows on the window (no buttons, no labels, no colors and so on...).
Can someone please help me figure out what is wrong with that line of code (it shows no syntax error).
import java.awt.*;
import javax.swing.*;
public class JavaApplication23 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setTitle("Test program");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setVisible(true);
JLabel label = new JLabel("Hello");
JButton button = new JButton("Click");
String[] options = new String[] {"Cat", "Dog"};
JComboBox comboBox = new JComboBox(options); //It goes wrong when I add this line
JPanel topPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel bottomPanel = new JPanel();
topPanel.add(label);
bottomPanel.add(button);
centerPanel.add(comboBox);
frame.add(topPanel, BorderLayout.PAGE_START);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.add(centerPanel, BorderLayout.CENTER);
}
}
You can do 2 things :
Add frame.setVisible(true); at the end or after adding comboBox in your code instead of amid.
or
Add frame.getRootPane().updateUI(); at the end or after adding comboBox in your code.
To add the above code when you are done with adding or changing components in tree is preferred i.e. in your case at the end of your method.
I am expecting that the reason for the problem in you code is clear. But let me know if not.
import javax.swing.*;
import java.awt.*;
public class SQlUI {
public static void main(String[] args){
SQlUI user=new SQlUI();
user.go();
}
public void go(){
//Creating a Frame
JFrame frame=new JFrame();
//Creating three Panels
JPanel panel0=new JPanel();
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
//Creating three Buttons
JButton button0=new JButton("INSERT");
JButton button1=new JButton("UPDATE");
JButton button2=new JButton("DELETE");
//Adding panel0 to the frame which contains three butoon objects
frame.getContentPane().add(BorderLayout.SOUTH,panel0);
panel0.add(button0);
panel0.add(button1);
panel0.add(button2);
//Creating four textbox
JTextField textbox0 = new JTextField(120);
JTextField textbox1 = new JTextField(120);
JTextField textbox2 = new JTextField(120);
JTextField textbox3 = new JTextField(120);
//Adding panel1 to the frame which contains four textbox objects
frame.getContentPane().add(BorderLayout.EAST,panel1);
//Using BoxLayout managaer for panel1 objects
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
panel1.add(textbox0);
panel1.add(textbox1);
panel1.add(textbox2);
panel1.add(textbox3);
//Adding panel2 to the frame which contains four label objects
frame.getContentPane().add(BorderLayout.WEST,panel2);
//Using BoxLayout managaer for panel1 objects
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
//Creating four labels
JLabel label0=new JLabel("Name");
label0.setSize(50,50);
label0.setVisible(true);
JLabel label1=new JLabel("ID");
label1.setSize(50,50);
label1.setVisible(true);
JLabel label2=new JLabel("AGE");
label2.setSize(50,50);
label2.setVisible(true);
JLabel label3=new JLabel("ADDRESS");
label3.setSize(50,50);
label3.setVisible(true);
//Adding labels to panel2
panel2.add(label0);
panel2.add(label1);
panel2.add(label2);
panel2.add(label3);
//Setting frame size and visiblity
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Details about the GUI- I am trying to create a GUI which have four textbox where user can enter his details and there are three buttons available on GUI by which user can send the data or store the data. The GUI also contains labels which tells the user which textbox is for which type of data.
Now the allignment of the objects are not coming the way i wanted it. All the labels are coming at one place and the size of box is very big. Tried to find a solution on stalkoverflow but got nothing.
i want something like this----
Name- textbox0
ID- textbox1
AGE- textbox2
ADDRESS- textbox3
Insert Update Delete
but getting something like----
textbox0
textbox1
Name
ID
AGE
Address textbox2
textbox3
Insert Update Delete
This is not the best looking thing you can do, but it's simple and a good start for you.
public class SQlUI {
public static void main(String[] args) {
SQlUI user = new SQlUI();
user.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel buttonsPanel = new JPanel();
JButton insert = new JButton("INSERT");
JButton update = new JButton("UPDATE");
JButton delete = new JButton("DELETE");
buttonsPanel.add(insert);
buttonsPanel.add(update);
buttonsPanel.add(delete);
frame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel("Name");
JTextField nameField = new JTextField(120);
namePanel.add(nameLabel);
namePanel.add(nameField);
JPanel idPanel = new JPanel();
JLabel idLabel = new JLabel("ID");
JTextField idField = new JTextField(120);
idPanel.add(idLabel);
idPanel.add(idField);
centerPanel.add(namePanel);
centerPanel.add(idPanel);
frame.getContentPane().add(centerPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Notice that I call frame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH); with the panel as the first argument and the position second, you did it the other way around.
Not sure why you need text fields of length 120.
Call frame.pack() instead of setting the size yourself.
See what indentation does to the code.
You can complete the rest of the panels by yourself.
I suggest reading up on different layouts here. It'll give you more of an idea how you can lay your items out. You can then experiment to find out which one you actually want.
That said I find it far easier to design a GUI graphically, and IntelliJ has a pretty good GUI builder that I've often used. You'll then be able to play around with layout managers and JPanels to get the effect you actually want.
I've been at this for a good while now, but I cannot seem to get a hand of it. I'm trying to produce a JPanel that has a JTextArea above and two JLabels below, but my JLabel ends up on the left side of my JTextArea and I cannot make the other appear.
Here's my code (sorry for the display stuff- just filler really):
public JPanel contentPane() {
JPanel something = new JPanel();
String information = "Please";
info = new JTextArea(information, 4, 30);
info.setEditable(false);
info.setLineWrap(true);
info.setWrapStyleWord(true);
JPanel one = new JPanel(new BorderLayout());
one.setBackground(Color.WHITE);
one.setLocation(10, 10);
one.setSize(50, 50);
one.add(info, BorderLayout.CENTER);
something.add(one, BorderLayout.NORTH);
JPanel two = new JPanel(new BorderLayout());
two.setBackground(null);
two.setLocation(220, 10);
two.setSize(50, 50);
two.add(new JLabel("Please work"), BorderLayout.EAST);
two.add(new JLabel("Oh gosh, please"), BorderLayout.WEST);
something.add(two, BorderLayout.SOUTH);
something.setOpaque(true);
return something;
}
public static void GUI() {
JFrame frame = new JFrame("You Guessed It!");
DisplayStudent panel = new DisplayStudent();
frame.setContentPane(panel.contentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 150);
frame.setVisible(true);
}
Please and thank you to anyone who takes the time to help.
When you create you something, you don't specify any layout manager, but later on you attempt to add one to something using BorderLayout constants -- which will not work, since the default layout manager for a JPanel is FlowLayout.
Try this instead;
JPanel something = new JPanel(new BorderLayout());