I am trying to create a form manually with code rather than the designer, I have already created using the designer.
This is the manual code that I came up with so far but I am having problem aligning the label and textfield side by side
mport java.awt.*;
import javax.swing.*;
/**
*
* #author jackandjill
*/
public class summinup_copy extends JFrame
{
private JLabel lblTitle, lblOctal, lblDecimal, lblMessage ;
private JTextField txtOctal, txtDecimal;
private JButton calculate_btn;
public summinup_copy()
{
JPanel panel = (JPanel)this.getContentPane();
panel.setLayout(new BorderLayout());
JPanel panCentre = new JPanel();
panCentre.setLayout(new GridLayout(3,3));
lblTitle = new JLabel("Area of Triangle");
lblTitle.setFont(new Font("Arial", 1, 20));
lblTitle.setHorizontalAlignment(JLabel.CENTER);
lblOctal = new JLabel("Octal");
lblOctal.setHorizontalAlignment(JLabel.CENTER) ;
//lblDecimal = new JLabel("Decimal");
//
//lblDecimal.setHorizontalAlignment(JLabel.CENTER);
lblMessage = new JLabel("Result will be displayed here");
lblMessage.setForeground(Color.red);
lblMessage.setHorizontalAlignment(JLabel.CENTER);
txtOctal = new JTextField("0", 5);
txtOctal.setHorizontalAlignment(JLabel.CENTER);
//txtDecimal = new JTextField("0", 5);
//
//txtDecimal.setHorizontalAlignment(JLabel.CENTER);
calculate_btn = new JButton("Calculate Area");
//AHandlerClass aListener = new AHandlerClass() ;
//btnOtoD.addActionListener(aListener);
//btnDtoO.addActionListener(aListener);
panCentre.add(lblOctal);
//panCentre.add(lblDecimal);
panCentre.add(txtOctal);
//panCentre.add(txtDecimal);
panCentre.add(calculate_btn);
//panCentre.add(btnDtoO);
panel.add(lblTitle, BorderLayout.NORTH);
panel.add(lblMessage,BorderLayout.SOUTH);
panel.add(panCentre, BorderLayout.CENTER);
}
public static void main(String args[]) {
summinup_copy myGui = new summinup_copy();
myGui.setTitle("Bharath");
myGui.setSize(400, 200);
myGui.setVisible(true);
}
}
As you have already figured out, you have to use LayoutManagers when coding a Swing GUI by hand. Here are some links that can help you figure out which LayoutManager is appropriate for a given look:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
In order to place a JLabel next to a JTextField or other component, I usually use GridLayout or GridBagLayout. I find that it takes a lot of trial and error trying to get components to look the way I want. Often you have to have layers of embedded JPanels to get it just right.
Related
I am trying to implement a JAVA GUI app, but I am facing a problem that I could not find the solution anywhere about how to move the JTextArea to a certain place on the panel. I took a picture of the software.
I have tried many ways to make the white JTextArea object placed below the big JTextArea object on the right panel. Does anyone have any idea about this? Like how to move the JTextArea object around the others, and how to make the JButton/JTextArea objects stay in the fixed place?
public class menu extends JFrame {
private JButton generate, sort;
private final JTextArea TEXT_AREA_EAST = new JTextArea(30,40);
private final JTextArea TEXT_AREA_WEST = new JTextArea(30,40);
private final JTextArea TEXT_AREA_EAST_BELOW = new JTextArea(5,30);
private void display() {
setTitle ("Sorting Algorithm Runtime Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,300);
setLocationRelativeTo(null);
setLayout(new GridLayout(5,2,5,5));
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.white);
contentPane.setBorder(
BorderFactory.createEmptyBorder(horizontal, horizontal, horizontal, horizontal));
contentPane.setLayout(new BorderLayout(horizontal, vertical));
ButtonGroup bg = new ButtonGroup();
rightPanel = new JPanel();
rightPanel.setOpaque(true);
rightPanel.setBackground(Color.yellow);
border = BorderFactory.createTitledBorder("Sorted List");
border.setTitleJustification(TitledBorder.CENTER);
rightPanel.setBorder(border);
sort = new JButton("Sort");
rightPanel.add(sort, JPanel.TOP_ALIGNMENT);
rightPanel.add(TEXT_AREA_EAST, BorderLayout.EAST);
rightPanel.add(TEXT_AREA_EAST_BELOW, BorderLayout.SOUTH);
TEXT_AREA_EAST.setBackground(Color.CYAN);
TEXT_AREA_EAST.setEditable(false);
This is how the app look like
I need to write an applet that converts char values to ascii values. Right now I'm just trying to get the layout of the applet right, but for some reason my JTextFields are showing up very strangely and I don't know how to go about fixing it. One is very large and the other is extremely small.
I had some trouble getting GridLayout to work the way I wanted, and I have some feeling that the problems have something to do with that but I don't know for sure.
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
public class Ex1_2 extends JApplet implements ActionListener
{
private JTextField charInput;
private JLabel display1;
private JLabel dummy;
private JLabel display2;
private JLabel welcome;
private JTextField ascii;
private JLabel error;
Container pane = getContentPane();
public void init()
{
pane.setLayout(new BorderLayout());
pane.setBackground(Color.orange);
display1 = new JLabel("Character", SwingConstants.CENTER);
display2 = new JLabel("ASCII code", SwingConstants.CENTER);
dummy = new JLabel("", SwingConstants.CENTER);
dummy.setBackground(Color.orange);
welcome = new JLabel("Char <-> ASCII converter", SwingConstants.CENTER);
welcome.setForeground(Color.blue);
pane.add(welcome, BorderLayout.NORTH);
pane.add(dummy, BorderLayout.SOUTH);
//charInput.addActionListener(this);
add(addMiddle());
}
JPanel addMiddle()
{
JPanel p = new JPanel();
p.setLayout(new GridLayout(0, 2, 10, -5));
p.setBackground(Color.green);
p.add(display1, BorderLayout.SOUTH);
p.add(display2, BorderLayout.SOUTH);
p.add(dummy);
p.add(addInnerLeft());
p.add(addInnerRight());
p.add(dummy);
return p;
}
JPanel addInnerLeft()
{
JPanel p2 = new JPanel(new GridLayout(0, 2));
p2.setBackground(Color.yellow);
pane.add(p2);
charInput = new JTextField("");
charInput.setForeground(Color.black);
//p2.add(charInput);
return p2;
}
JPanel addInnerRight()
{
JPanel p3 = new JPanel();
p3.setBackground(Color.yellow);
ascii = new JTextField("");
ascii.setForeground(Color.black);
//p3.add(ascii);
return p3;
}
public void actionPerformed(ActionEvent e)
{
}
}
A quick fix:
Consider setting your JTextFields's column property. For instance, if you use:
ascii = new JTextField("", 5);
your ascii JTextField now gets some preferred size width.
A better long-term fix:
Study, learn and use the layout managers to better advantage.
Note that a problem with JApplets is that the size is specified by the HTML code and not by the layout managers (as far as I understand things), and so you must take care to make sure that the GUI's are sized big enough.
e.g., with layouts, I got this:
The second text field is sized that way because you initialized it:
ascii = new JTextField("");
This represents that the text field has a string value for its name where the length of the string is zero. The text field is being sized automatically according to the text it contains. Since it contains a string with zero length, the size of the text field is so small.
You could use the setColumns(int columns) method on the text field to give it a fixed width, so that it can get a preferred size.
I'm trying to set the components of this application to a set location using setLocation so far i haven't been able to move the components. There is more code but its get calling and setting this code for the most part. any ideas?
import javax.swing.*;
public class HangmanPanel extends JPanel {
private static final long serialVersionUID = -5793357804828609325L;
public HangmanPanel(){
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//Button.addActionListener();
JLabel tfLable = new JLabel("Please Enter a Letter");
JTextField text = new JTextField(10);
String input = text.getText();
heading.setLocation(50, 20);
tfLable.setLocation(20, 100);
text.setLocation(320, 50);
Button.setLocation(230, 100);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
}
}
You should not use setLocation() to layout Swing components, it is much better to use a Layout. Please have a look at these Layout Tutorials.
I'm trying to make a simple menu for my game. I have 4 buttons in the center and I want to make them a little bit bigger and center them.
The last part worked but I can't seem to call any of my JButtons and do a .setSize / .setPreferedSize(new Dimension()) on it.
public class mainMenu extends JFrame {
private JButton start, highscore, help, stoppen;
public mainMenu() {
super("Master Mind");
maakComponenten();
maakLayout();
toonFrame();
}
private void maakComponenten() {
start = new JButton("Start");
start.setBackground(Color.gray);
highscore = new JButton("Higscores");
help = new JButton("Help");
stoppen = new JButton("Stoppen");
}
private void maakLayout() {
JPanel hoofdmenu = new JPanel();
hoofdmenu.setLayout(new BoxLayout(hoofdmenu, BoxLayout.Y_AXIS ));
hoofdmenu.add(start);
start.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(highscore);
highscore.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(help);
help.setAlignmentX(CENTER_ALIGNMENT);
hoofdmenu.add(stoppen);
stoppen.setAlignmentX(CENTER_ALIGNMENT);
super.add(hoofdmenu);
}
private void toonFrame() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(500,500);
}
public static void main(String[] args) {
new mainMenu();
}
}
As an example, to change the size of the "Start" button,
change :
start1 = new JButton("Start");
to
start1 = new JButton("Start") {
{
setSize(150, 75);
setMaximumSize(getSize());
}
};
The problem is that JFrames use BorderLayout by default, which means that your JPanel will naturally fill the space.
Before adding your JPanel, call the following code to change the JFrame's layout to null and use the JPanel's settings instead.
this.setLayout(null);
JPanel hoofdmenu = new JPanel();
hoofdmenu.setBounds(0,0, 400, 100);
Alternatively, you could set the maximum size of the JButtons
Dimension maxSize = new Dimension(100, 100);
start.setMaximumSize(maxSize);
highscore.setMaximumSize(maxSize);
help.setMaximumSize(maxSize);
stoppen.setMaximumSize(maxSize);
Here's another example following behind the previous two - I'm making a soundboard program, and this is actually a sample from it - The JPanel actually is needed, agreeing to the second post.
JFrame frame = new JFrame();
JPanel menuPanel = new JPanel();
JButton Button1 = new JButton("<BUTTON NAME 1>");
Button1.setSize(80, 30);
Button1.setLocation(4, 4);
JButton Button2 = new JButton("<BUTTON NAME 2>");
Button2.setSize(80, 30);
Button2.setLocation(90, 4);
Ah, and another thing - You created the buttons in a different block from the second piece of code. Doing that causes the other blocks to not see it. You need to declare them outside the block so all the blocks can see them.
I have created a JFrame, and now I want to add a JLabel and textfields in it. Please tell me how to do that. I have used the following code but its not working.
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
Problem is this code is showing frame window but it is not showing label in it. Please help.
That's your first question, later you'll ask:
How do I get the value from my text field
So, I suggest you to take a look at this tutorial
http://java.sun.com/docs/books/tutorial/uiswing/start/index.html
And ask us if you have questions from that tutorial. Using an IDE will simplify your life.
Here's a start anyway:
Code:
import javax.swing.*;
import java.awt.Color;
public class MyApp {
public static void main( String [] args ) {
JFrame frame = new JFrame();
frame.setBackground( new Color(0,0,0,64 ));
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel top = new JPanel();
top.add( new JLabel("What is your name"){{
setForeground(Color.white);
}});
top.add( new JTextField(10) );
frame.add( top );
frame.pack();
frame.setVisible( true );
}
}
EDIT
Dismiss this answer. It was posted when the question was rather ambiguous. I'm leaving it as CW for it may be helpful.
plus OSX frames with alpha background are too cool!
The main issue is the layout being used by the content pane (most likely JRootPane.RootLayout, A custom layout manager that is responsible for the layout of layeredPane, glassPane, and menuBar ) is not the best. This code should work;
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
i_frame.getContentPane().setLayout(new FlowLayout());
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
setting a different layout does the trick
The problem is that you are adding a second component (Box.createRigidArea) in the same layout position (BorderLayout.CENTER) as the Label.
JFrame.add() results in the same as JFrame.getContentPane().add()...
So the label is being replaced by the RigidArea.
Try this:
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
// i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
to add more components, change the LayoutManager:
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
Container pane = i_frame.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); // any LayoutManager you need
pane.add(i_from);
pane.add(Box.createRigidArea(new Dimension(2,0))); // space after JLabel ?
i_frame.setSize(200,200); // better done before setLocationRelativeTo
i_frame.setLocationRelativeTo(null);
i_frame.setVisible(true);
Note: if you "just" want to add an empty border to your label, use a setBorder() instead of the RigidArea:
i_from.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
[]]
For adding JLabel to JFrame see the line of code see here
public class JLabelExample extends JFrame {
JLabel jLabel;
public JLabelExample() {
jLabel = new JLabel();
jLabel.setText("tutorialData.com");
jLabel.setForeground(Color.BLUE);
this.add(jLabel);
}
public static void main(String a[]) {
JLabelExample labelExample = new JLabelExample();
labelExample.setSize(250, 200);
labelExample.setTitle("tutorialData.com");
labelExample.setVisible(true);
}
}
Please refer more on JFrame