positioning different component in java GUI - java

im trying to design java GUI frame which contains labels, textfields, radio buttons and button..
i want to position each component in specific place tried setBounds() but it didn't work..
also im trying to change background color of the frame using getContentPane().setBackground(Color.white) and setBackground(Color.white) but didnt work too.
how to do it ?
this is my code :
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class test extends JFrame{
public static void main(String[] args) {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("WHO IS THE WINNER");
guiFrame.setSize(700,500);
guiFrame.setLocationRelativeTo(null);
final JPanel first = new JPanel();
JLabel un = new JLabel("UserName:");
JTextField textField = new JTextField(20);
JLabel sn = new JLabel("Server Name:");
JTextField textField2 = new JTextField(20);
un.setLabelFor(textField);
sn.setLabelFor(textField2);
first.add(un);
first.add(textField);
first.add(sn);
first.add(textField2);
final JPanel second = new JPanel();
JLabel level = new JLabel("Level:");
JLabel score = new JLabel("Score:");
JLabel question = new JLabel("Question:");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox radio1 = new Checkbox("True", radioGroup,false);
Checkbox radio2 = new Checkbox("False", radioGroup,true);
second.add(score);
second.add(level);
second.add(question);
second.add(radio1);
second.add(radio2);
JButton next = new JButton( "Next");
next.addActionListener(
new ActionListener() {
#Override public void actionPerformed(ActionEvent event) {
first.setVisible(false);
} });
guiFrame.add(first, BorderLayout.NORTH);
guiFrame.add(second, BorderLayout.CENTER);
guiFrame.add(next,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
for the positioning for example i want the first label and text field under them the other label and text field not beside them.. same for other labels and radio buttons i don't want them it be beside each other i want o give them a specific position to be in..
can someone please help ?
Thanks :)

This answer is just for Eclipse IDE.
An easy way to place all the widgets is doing it from the Design tab, placed at the bottom-left side of the window. Just change from Source perspective to Design perspective. It will open a simple panel with everything you need. Just drag the different widgets and place them in their position.
To change the background of the frame, do it from the properties of the frame in the Design tab or add the following code to the constructor of the panel:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);

Related

Java GUI - Buttons not showing up in JPanel

I'm learning how to make GUIs in Java. Right now what I'm trying to do is make a small box with 2 buttons next to each other (with maybe.. 10px of padding between them) inside a JPanel. When I run this program in JGrasp I just get an empty window. What am I doing wrong?
MyButtons.java
import javax.swing.*;
import java.awt.*;
public class MyButtons extends JFrame{
public MyButtons(){
JPanel pnlMain = new JPanel();
this.setTitle("MyButtons");
JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");
pnlMain.add(btn1);
pnlMain.add(btn2);
this.add(pnlMain);
}
}
TestMyButtons.java
import javax.swing.*; // for JFrame, JPanel, JLabel, JTextField,
import java.awt.*; // for BorderLayout
public class TestMyButtons {
public static void main(String[] args) {
MyButtons test = new MyButtons();
test.setVisible(true);
test.setSize(1000,300);
test.setLocation(200,300);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
EDIT: Revised to show the correct code. Answer marked below. All I did was add one line to the bottom of MyButtons.Java >.<
You must also add the pnlMain to the JFrame's content pane or set it as content pane of the frame.
Create Button's Object as given below.
JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");

How do I lay out Input panel with multiple textfields and OK, CANCEL buttons?

I am trying to achieve the following effect in Java:
However, I am not sure what layout to use and how. FlowLayout obviously doesn't work. GridLayout won't work either because the first 4 rows are supposed to be 1 column rows, but the 5th row needs to have 2 columns.
This is my code so far:
public class DepositPanel extends JPanel
{
private JLabel cashL, checksL;
private JTextField cashTF, checksTF;
private JButton ok, cancel;
DepositPanel()
{
JPanel depositP = new JPanel();
depositP.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 2));
depositP.setPreferredSize(new Dimension(250, 85));
JTextField cashTF = new JTextField(22);
JTextField checksTF = new JTextField(22);
JLabel cashL = new JLabel("Cash:");
JLabel checksL = new JLabel("Checks:");
ok = new JButton("OK");
cancel = new JButton("CANCEL");
depositP.add(cashL);
depositP.add(cashTF);
depositP.add(checksL);
depositP.add(checksTF);
depositP.add(ok);
depositP.add(cancel):
}
}
You could try with combinations of Layouts, 2 JPanels, 1 for buttons and 1 for fields, button panel with FlowLayout and fields panel with BoxLayout. And adding them to the frame. (I did a JFrame for testing, but you can change it to a JPanel and add that panel to your JFrame). Just be sure to have only 1 JFrame, see The use of multiple JFrames, Good / Bad Practice.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class DepositExample {
JFrame frame;
JPanel buttonPane, fieldsPanel;
JLabel cash, checks;
JTextField cashField, checksField;
JButton ok, cancel;
DepositExample() {
frame = new JFrame("Deposit");
buttonPane = new JPanel();
fieldsPanel = new JPanel();
cash = new JLabel("Cash");
checks = new JLabel("Checks");
cashField = new JTextField("");
checksField = new JTextField("");
ok = new JButton("OK");
cancel = new JButton("Cancel");
fieldsPanel.setLayout(new BoxLayout(fieldsPanel, BoxLayout.PAGE_AXIS));
buttonPane.setLayout(new FlowLayout());
fieldsPanel.add(cash);
fieldsPanel.add(cashField);
fieldsPanel.add(checks);
fieldsPanel.add(checksField);
buttonPane.add(ok);
buttonPane.add(cancel);
frame.add(fieldsPanel, BorderLayout.PAGE_START);
frame.add(buttonPane, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new DepositExample();
}
}
To get some more spacing between components you can add EmptyBorders as recommended by #LuxxMiner in his comment below.
In this case you can use a JOptionPane to build a simple panel for you:
JTextField firstName = new JTextField(10);
JTextField lastName = new JTextField(10);
Object[] msg = {"First Name:", firstName, "Last Name:", lastName};
result = JOptionPane.showConfirmDialog(
frame,
msg,
"Use default layout",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
The only problem with this approach is that the focus will be on a button, not the first name text field.
So to solve this problem you can check out the RequestFocusListener found in Dialog Focus which will cause focus to be placed on the first name text field once the dialog is displayed.
JTextField firstName = new JTextField(10);
firstName.addAncestorListener( new RequestFocusListener() );
Although for more complex layouts it is better to create one or more panels each using an appropriate layout manager for the requirement.
There are many ways to achieve a layout like this. The first thing you need to get used to, is that its often simpler to split up different requirements into different containers using different layout managers.
If you separate the two buttons into their own panel and treat that panel with the buttons as "just another line" in the window, you can basically just use a GridLayout with a single column. The panel with the buttons could then use a FlowLayout to place the buttons side by side.
Try this:
public class Window extends JFrame{
....
}
JLabel example;
//Constructor
public Window(){
example = new JLabel("Sample text");
example.setBounds(x,y,width,height)
//JComponent...
setLayout(null);
setSize(width,height);
setVisible(true);
}
Without the JPanel you can specify the x and y coordinates

New to creating GUIs. How would I combine text area and radio buttons

I understand how to create radio buttons and I understand how to create a text area. What I have trouble with is combing the two onto one frame.
Can anyone help me or show me how to do so? Do I have to layout a grid with boarders?
Here I was trying to follow my text book on ways to combine the two but I sort of failed. :(
I've tried other ways but none have worked for me. When I attempt to do the text area and radio buttons separately, they work.
This isn't my final code. My finish product should allow me to keep track of how many times a certain student is picked, like a vote, and printing out the totals in the text area each time.
Getting this part to work will help me further advance in my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class AsnTwo extends JFrame
{
private JRadioButton jrbS1 = new JRadioButton("Student 1");
private JRadioButton jrbS2 = new JRadioButton("Student 2");
private JRadioButton jrbS3 = new JRadioButton("Student 3");
private JTextArea jtaT = new JTextArea("Hello");
public static void main(String[] args)
{
AsnTwo frame = new AsnTwo();
JPanel panel = new JPanel();
frame.pack();
frame.setTitle("Assignment Two");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public AsnTwo()
{
JPanel jpTextArea = new JPanel();
jpTextArea.setLayout(new GridLayout(2,1));
jtaT.setEditable(false);
jtaT.setLineWrap(true);
jtaT.setText("Something");
add(jpTextArea, BorderLayout.EAST);
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(3,1));
jpRadioButtons.add(jrbS1);
jpRadioButtons.add(jrbS2);
jpRadioButtons.add(jrbS3);
add(jpRadioButtons, BorderLayout.WEST);//Adds buttons to GUI
ButtonGroup group = new ButtonGroup();
group.add(jrbS1);
group.add(jrbS2);
group.add(jrbS3);
}
public void printTextField(String text)
{
jtaT.setText("Hello");
}
}
Never mind. I got it. I just had to change
add(jpTextArea, BorderLayout.EAST);
to
add(jtaT, BorderLayout.EAST);

JAVA - Can't add Text Field and Button to container

I'm trying to do a little program that use some buttons and text field.
I was able to create window with JPanel but don't have idea how to add button and text field
The code I'm using is:
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,SZEROKOSC,WYSOKOSC);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
panel.add(this);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextField pole = new JTextField(10);
JButton przycisk = new JButton("teasda");
przycisk.setPreferredSize(new Dimension(300, 350));
przycisk.setLayout(new BorderLayout());
panel.add(przycisk);
przycisk.setVisible(true);
pole.setBounds (300,300,200,200);
pole.setLayout(null);
pole.setVisible(true);
panel.add(pole);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
// addMouseListener(this);
}
You need to use the layout properly, when using border layout you need to tell it which border to use (, BorderLayout.NORTH or something), check out the tutorials at oracles page.
P.S. Think of how your naming your fields etc. Naming something "przycisk" just gives me a reason not to read the code further.
Thank You for help and sorry for Polish names(fixed already).
I was able to add Text Area with scroll.
Looks like problem was in panel.add(this); putted before button and text field.
From my understanding if panel.add(this) is set before panel.add(pole); then panel.add(this) is set in front and pole is added but not seen.
Below my actual working code:
...
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,WIDTH,HEIGHT);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextArea pole = new JTextArea();
pole.setLayout(null);
pole.setLineWrap(true);
//pole.setBackground(Color.BLACK);
pole.setEditable(false);
JScrollPane scroll = new JScrollPane(pole);
scroll.setBounds(25,250,500,300);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll);
panel.add(this);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
addMouseListener(this);
}
...
This code is from this site: Example of Java GUI
//Imports are listed in full to show what's being used
//could just import javax.swing.* and java.awt.* etc..
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GuiApp1 {
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
new GuiApp1();
}
public GuiApp1()
{
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Example GUI");
guiFrame.setSize(300,250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//Options for the JComboBox
String[] fruitOptions = {"Apple", "Apricot", "Banana"
,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
//Options for the JList
String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish", "Shallot", "Spinach", "Swede"
, "Turnip"};
//The first JPanel contains a JLabel and JCombobox
final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Fruits:");
JComboBox fruits = new JComboBox(fruitOptions);
comboPanel.add(comboLbl);
comboPanel.add(fruits);
//Create the second JPanel. Add a JLabel and JList and
//make use the JPanel is not visible.
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
JList vegs = new JList(vegOptions);
vegs.setLayoutOrientation(JList.HORIZONTAL_WRAP);
listPanel.add(listLbl);
listPanel.add(vegs);
JButton vegFruitBut = new JButton( "Fruit or Veg");
//The ActionListener class is used to handle the
//event that happens when the user clicks the button.
//As there is not a lot that needs to happen we can
//define an anonymous inner class to make the code simpler.
vegFruitBut.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
//When the fruit of veg button is pressed
//the setVisible value of the listPanel and
//comboPanel is switched from true to
//value or vice versa.
listPanel.setVisible(!listPanel.isVisible());
comboPanel.setVisible(!comboPanel.isVisible());
}
});
//The JFrame uses the BorderLayout layout manager.
//Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
guiFrame.add(listPanel, BorderLayout.CENTER);
guiFrame.add(vegFruitBut,BorderLayout.SOUTH);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
}
For the future i will recommend you to use the extends JFrame so you can only write a gui like this without initialize a JFrame:
public class CalculatorGUI extends JFrame {
public CalculatorGUI() {
setTitle("Calculator");
setBounds(300, 300, 220, 200);
}}
I suggest you check out a couple of tutorials about how to create a Java Gui or sth.

Display using JPanels/JFrames?

I have code done, but still have not managed to get what I am working for.
My current code shows this:
with this code:
/*
*/
package reader;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
//import java.lang.Process;
/**
*/
class readerGUI extends JFrame
{
JMenuBar menuBar;
JMenu menu1, menu2, menu3, menu4;
JMenuItem menuItem, menuItem1, menuItem2, menuItem3, menuItem4;
ImageIcon logo;
JLabel loguin1, loguin2, title;
JTextArea readerArea;
JPanel rightSide, leftSide, bottomSide, middleSide;
String text;
JButton importBook, removeBook, listBook, searchBook;
JTextField searchField;
readerGUI()
{
super("Text \n");
String cad = "logo.png";
//setBackground(Color.blue);
setLayout(new FlowLayout());
menuBar = new JMenuBar();
title = new JLabel(" Text ");
add(title);
menu1 = new JMenu("Link");
menuItem = new JMenuItem("Option");
menu2 = new JMenu("Link");
menuItem1 = new JMenuItem("Option In");
menuItem2 = new JMenuItem("Option Out");
menu3 = new JMenu("Link");
menuItem3 = new JMenuItem("Option");
menuBar.add(menu1);
menuBar.add(menu2);
menuBar.add(menu3);
menu1.add(menuItem);
menu2.add(menuItem1);
menu2.add(menuItem2);
menu3.add(menuItem3);
add(menuBar);
logo = new ImageIcon(cad);//create icon
loguin1 = new JLabel(logo);//create label
loguin2 = new JLabel(logo);//create label
//loguin.setBounds(150,30,100,100);//where?
add(loguin1); //add
add(loguin2);
rightSide = new JPanel(); //PANEL for buttons
rightSide.add(new JLabel("Text:"));
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement("Text1");
model.addElement("Text2");
model.addElement("Text3");
JComboBox comboBox = new JComboBox(model);
rightSide.add(comboBox);
searchField = new JTextField("", 10);
rightSide.add(searchField);
searchBook = new JButton("Search");
rightSide.add(searchBook);
add(rightSide);
text = "\n\t\t LORE IPSUM \n\n"
+ "commodo nisi. In hac habitasse platea dictumst.\n";
middleSide = new JPanel(); //PANEL for buttons
add(middleSide);
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setBackground(sas, Color.RED);
StyledDocument doc;
/* --------- SIDE Menu Panel for Options ----------*/
title = new JLabel("Options ");
add(title);
leftSide = new JPanel(); //PANEL for buttons
importBook = new JButton("Button1");
leftSide.add(importBook);
removeBook = new JButton("Button2");
leftSide.add(removeBook);
add(leftSide);
JPanel main = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel child = new JPanel();
child.add(new JLabel("Options \n"));
//main.add(child);
main.add(leftSide);
add(main);
ActionEventHandler manejador = new ActionEventHandler();
menuItem.addActionListener(manejador);
}
private class ActionEventHandler implements ActionListener
{
#Override
public void actionPerformed( ActionEvent evento)
{
if (evento.getSource() == menuItem)
System.exit(0);
}
}
}
And would like my code to display something along these lines:
I know im not that far from obtaining it, but I get confused with JPanels and JFrames.. help?
Generally speaking, FlowLayout probably isn't the best choice of layout manager in this case.
You're off to a good start by separating each area into separate components, but you should be focusing on their layout requirements as well.
To start with, I see the base layout as a BorderLayout. This will allow you to place the "title" in the BorderLayout.NORTH position, the "menu" in the BorderLayout.WEST position and the content into the BorderLayout.CENTER position
For the title, I see the use of GridBagLayout, as this will allow you to give the "Title" more weight (space) then the other components.
The menu is a little more complex, you might be able to do this with a GridBagLayout or, by separating the "Menu Options" from the buttons (in separate containers), use a BorderLayout as the base (placing "Menu Options" in the BorderLayout.NORTH and the buttons in the BorderLayout.CENTER position) and using something like a GridLayout for the buttons, for example...
For the "main content", you could use either a GridLayout or GridBagLayout depending on your needs
Take a look through Laying Out Components Within a Container for more ideas...

Categories

Resources