Creating a JApplet MadLibs game - java

I am creating a JApplet MadLibs game, but the image I add fills up the entire page so that my Labels and JTextFields are being blocked. I only want the logo to be centered at the top of the applet.
My code:
import java.awt.*;
import javax.swing.*;
import javax.swing.JApplet;
import java.awt.event.*;
import java.net.URL;
public class MadLibs extends JApplet implements ActionListener {
JLabel label1 = new JLabel("A Proper First Name: ");
JLabel label2 = new JLabel("A Pet: ");
JLabel label3 = new JLabel("A Personal Attribute: ");
JLabel label4 = new JLabel("An Adjective: ");
JLabel label5 = new JLabel("A Verb: ");
JTextField jtf1 = new JTextField();
JTextField jtf2 = new JTextField();
JTextField jtf3 = new JTextField();
JTextField jtf4 = new JTextField();
JTextField jtf5 = new JTextField();
JButton jb = new JButton("Create!");
JLabel madlib = new JLabel("");
Container con = getContentPane();
private Image image;
public void init() {
image = getImage(getDocumentBase(), "MadLibsLogo.gif");
jb.addActionListener(this);
con.add(label1);
con.add(jtf1);
con.add(label2);
con.add(jtf2);
con.add(label3);
con.add(jtf3);
con.add(label4);
con.add(jtf4);
con.add(label5);
con.add(jtf5);
con.add(jb);
con.add(madlib);
}
public void actionPerformed(ActionEvent e) {
madlib.setText(jtf1.getText() + " had a little " + jtf2.getText() + "/nIts " + jtf3.getText() + " was " + jtf4.getText() +
" as snow/nAnd everywhere that " + jtf1.getText() + jtf5.getText() + "/nThe " + jtf2.getText() + " was sure to go.");
repaint();
}
public void paint(Graphics g)
{
g.drawImage(image, 0, 0, 229, 73, this);
}
}

Don't override a JApplet's paint method, and in fact it is usually a bad idea to override the paint method of any top-level window unless you're sure that you need to do this, don't care about or need the double buffering offered with Swing graphics, and understand that this may effect the GUI's borders and child components.
Why not simply put the Image in an ImageIcon and that in a JLabel, and then place the JLabel where you desire to display the image?
Edit: you appear to be adding many components to the contentPane without regard for layout. Have you changed it's layout from the default BorderLayout somewhere in code not posted?
Edit 2 You state:
No I haven't...I still haven't gotten to the layout. How would I change the BorderLayout so that everything is aligned?
If you haven't changed the layout, then in all likelihood the only thing you are seeing is the last component added to the contentPane, the madLib JLabel. What you will want to is to layer JPanels on top of each other, each with its own layout manager. For instance, continue leaving the contentPane with a BorderLayout, adding the logo JLabel with the image in the BorderLayout.NORTH or PAGE_START position. Then add most of the body of the GUI into a JPanel that's placed BorderLayout.CENTER. Read up on the various layout managers and play with them as that's the best way to learn how to use them.

Related

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

positioning different component in java GUI

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

Java Swing UI Layout

I am creating a basic user interface in Swing and was hoping for some help. Below is a screenshot of what I am trying to achieve:
My code currently is as follows:
package testui;
import java.awt.Container;
import javax.swing.*;
public class TestUI{
private JTextField outputArea = new JTextField();
private JTextField errorReportArea = new JTextField();
private JPanel inputPanel = new JPanel();
private JLabel nameLabel = new JLabel("Item Name");
private JLabel numberLabel = new JLabel("Number of units (or Volume in L)");
private JLabel priceLabel = new JLabel("Price per unit (Or L) in pence");
private JTextField nameField = new JTextField(10);
private JTextField numberField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JButton addVolumeButton = new JButton("Add by Volume");
private JButton addNumberButton = new JButton("Add by number of units");
public TestUI() {
JFrame frame = new JFrame("Fuel Station");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outputArea.setEditable(false);
errorReportArea.setEditable(false);
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));
inputPanel.add(nameLabel);
inputPanel.add(nameField);
inputPanel.add(numberLabel);
inputPanel.add(numberField);
inputPanel.add(priceLabel);
inputPanel.add(priceField);
inputPanel.add(addVolumeButton);
inputPanel.add(addNumberButton);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(outputArea);
contentPane.add(errorReportArea);
contentPane.add(inputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
TestUI test1 = new TestUI();
}
}
Which looks like this:
So what I would like to do is set a specific size for the top two JTextFields, as the top one will contain multiple lines of text, and the one below will contain just one line of text. I am unsure how to do this without using setSize, as I have been told it is bad coding practice to use this.
I would also like to add some padding between the JLabels, JTextFields and JButtons in the bottom JPanel.
If anyone could give me some suggestions on resizing these components I would be most grateful
Since you want your textfields to be multilined, use JTextAreas. JTextFields are single lined only.
Your components are right next to each other which isn't the same look as your intended outcome. There may be some method that gives your components some breathing room before you would call frame.pack()
Look for any method that can make a component fill the total amount of room it's given; especially when you want something to fill a large chunk of space.
You can set the number of columns instead of using setSize() for your JTextFields/JTextAreas. Just saying.
Reviewing all of Java's Layout Managers would help you get a grasp of the capabilities and use cases for each layout manager
There are a few layout managers that are flexible enough to perform this, such as Mig, Gridbag, and SpringLayout.
In your case, you'd have the following constraints:
outputarea - south border constrained to be ###px from the north border of the contentPane
errorReportArea - north border constrained to be 0px from outputarea's south, and south border constrained to be 0px from inputPanel's north.
inputPanel - north border constrained to be ##px from the south border of the contentPane.
GUI builders such as WindowBuilder will allow you to do this pretty quickly. You just drop in the layout onto the contentPane and then set the constraints.
If you have to use a box layout look at the glue and rigidArea methods in Box. If you can use other layouts, go with those suggested by the other answers.
I have created a solution with the MigLayout manager.
Here are some recommendations:
Put application code outside the constructor; in the solution, the code
is placed in the initUI() method.
The application should be started on EDT by calling the
EventQueue.invokeLater(). (See the main() method of the provided solution.)
Use a modern, flexible layout manager: MigLayout, GroupLayout, or FormLayout.
Take some time to study them to fully understand the layout management process. It
is important have a good understanding of this topic.
Shorten the labels; use more descriptive tooltips
instead.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutSolution extends JFrame {
private JTextArea outputArea;
private JTextField errorReportField;
private JLabel nameLabel;
private JLabel numberLabel;
private JLabel priceLabel;
private JTextField nameField;
private JTextField numberField;
private JTextField priceField;
private JButton addVolumeButton;
private JButton addNumberButton;
public MigLayoutSolution() {
initUI();
}
private void initUI() {
setLayout(new MigLayout());
outputArea = new JTextArea(10, 20);
errorReportField = new JTextField(15);
nameLabel = new JLabel("Item name");
numberLabel = new JLabel("# of units");
numberLabel.setToolTipText("Number of units (or Volume in L)");
priceLabel = new JLabel("Price per unit");
priceLabel.setToolTipText("Price per unit (Or L) in pence");
nameField = new JTextField(10);
numberField = new JTextField(10);
priceField = new JTextField(10);
addVolumeButton = new JButton("AddVol");
addVolumeButton.setToolTipText("Add by Volume");
addNumberButton = new JButton("AddNum");
addNumberButton.setToolTipText("Add by number of units");
add(new JScrollPane(outputArea), "grow, push, wrap");
add(errorReportField, "growx, wrap");
add(nameLabel, "split");
add(nameField);
add(numberLabel);
add(numberField);
add(priceLabel);
add(priceField);
add(addVolumeButton);
add(addNumberButton);
pack();
setTitle("Fuel station");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutSolution ex = new MigLayoutSolution();
ex.setVisible(true);
}
});
}
}

JTextField permanent Position/Location?

So I am a having a problem regarding my JTextField.
What I'm trying to do is to put the JTextField box below the picture(map of a certain town).
Yeah, I used .setBounds and it was already below the image, but what I want to happen is that if I do .pack();, it must be still visible. Unfortunately, it wasn't.
I tried using the .setBorder(BorderFactory.createEmptyBorder(5,50,0,50)); and I saw that the box is below the picture but it is no longer available for putting a text.
And to conclude, I want the JTextField below the picture and still must be visible whenever I pack it.
Please Help. Thank you.
I am still on the stage of discovering new things about GUI.
Sorry for the noob question.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
class ProgDraftMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
ProgDraft gui = new ProgDraft();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setResizable(false);
gui.pack();
//gui.setSize(1000 , 1000);
gui.setVisible(true);
}
});
}
}
class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
ProgDraft() {
/***Panel**/
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEADING));
/***Title***/
JLabel title = new JLabel("Perimeter Check", JLabel.CENTER);
Font font = new Font("Gigi", Font.BOLD, 50);
title.setFont(font);
/***Image***/
ImageIcon pics = new ImageIcon(getClass().getResource("antipolo.png"));
JLabel logo = new JLabel(pics);
logo.setBorder(BorderFactory.createEmptyBorder(10, 70, 0, 50));
logo.setToolTipText("Ito raw kunware yung barangay.");
panel.add(logo);
/***Info ANtipolo***/
String text = "Ito kunware ang ANtipolo" + "<br>" +
"Marami ditong landslide areas" + "<br>" + "<br>" +
"Take care and stay safe!" + "<br>" +
"I love my dogs" + "<br>" + "<br>" +"<br>" +
"Please help!";
JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
dog.setBorder(BorderFactory.createEmptyBorder(5,50,0,50));
panel.add(dog);
/***JTextFieldski**/
JTextField textField = new JTextField(6);
textField.setBorder(BorderFactory.createEmptyBorder(5,50,0,50));
textField.setBounds(210,470,100,25);
panel.add(textField);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(textField, BorderLayout.SOUTH);
getContentPane().add(dog, BorderLayout.CENTER);
getContentPane().add(panel, BorderLayout.SOUTH);
getContentPane().add(title, BorderLayout.NORTH);
}
}
I think you took my advice yesterday about using EmptyBorder a little too far. You are trying to use it for pixel perfect position. That's not what they're meant for. Don't worry about pixel perfect positioning. Like I said yesterday, learn the layout managers and make use of them. Also you can wrap components in panels with different layout managers and nest the panels. You don't have to try and get everything perfect on one panel. Different layout managers have different features and qualities.
For instance What you are trying to do is add two different components to the BorderLayout.SOUTH. The thing about BorderLayout is each position can only have one components. The last one added wins. So what can we do? How about wrapping the two in a panel, then adding that panel to the SOUTH :-) Easy right?
Also in regards to the EmptyBorders, Make use the the JLabel api. You can setHorizontalAlignment to JLabel.CENTER. The default is JLabel.LEADING, so all the text is to the left. If you set it to the center, then it will be centered.
Also just FYI, setBounds will not work unless you are using null layouts, which I advise against. You don't use it.
Here is the refactor (using NO Empty Borders, letting the layout managers do the job we pay them to do)
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
class ProgDraftMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ProgDraft gui = new ProgDraft();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setResizable(false);
gui.pack();
//gui.setSize(1000 , 1000);
gui.setVisible(true);
}
});
}
}
class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
ProgDraft() {
/**
* Main Panel
*/
JPanel mainPanel = new JPanel(new BorderLayout());
/**
* *Title**
*/
JLabel title = new JLabel("Perimeter Check", JLabel.CENTER);
Font font = new Font("Gigi", Font.BOLD, 50);
title.setFont(font);
mainPanel.add(title, BorderLayout.PAGE_START); // add title to top
/**
* *Info ANtipolo**
*/
String text = "Ito kunware ang ANtipolo" + "<br>"
+ "Marami ditong landslide areas" + "<br>" + "<br>"
+ "Take care and stay safe!" + "<br>"
+ "I love my dogs" + "<br>" + "<br>" + "<br>"
+ "Please help!";
JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
dog.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(dog); // add dog to center
/**
* *Image** ==========>>>>>> Make sure to change the image name back.
*/
ImageIcon pics = new ImageIcon(getClass().getResource("stackoverflow.png"));
JLabel logo = new JLabel(pics);
logo.setHorizontalAlignment(JLabel.CENTER);
//logo.setBorder(BorderFactory.createEmptyBorder(10, 70, 0, 50));
logo.setToolTipText("Ito raw kunware yung barangay.");
/**
* Wrapper for text field and icon
*/
JPanel iconFieldPanel = new JPanel(new BorderLayout());
JTextField textField = new JTextField(10);
iconFieldPanel.add(logo);
iconFieldPanel.add(textField, BorderLayout.PAGE_END);
JPanel iconFieldWrapper = new JPanel();
iconFieldWrapper.add(iconFieldPanel);
mainPanel.add(iconFieldWrapper, BorderLayout.PAGE_END); // add icon and field to bottom
getContentPane().add(mainPanel);
}
}
And pleeease do take some time to go over the link I provided for using layout managers. Study one at a time and get the hang of each. It's an art, so it'll take time, just like anything else.

Placing a JLabel at a specific x,y coordinate on a JPanel

I'm trying to place a series of JLabels at specific X and Y coordinates on a JPanel (and set its height and width, too). No matter what I do, each label winds up immediately to the right of the previous label and has the exact same size as all of the others.
Right now, my Jpanel is in a Grid Layout. I've tried Absolute Layout (illegal argument exception results), Free Design (no labels appear), Flow Layout (everything just gets squeezed to the center), and a few others.
Not sure what I need to do to make this work. Can anyone help? Thanks!
JLabel lbl1 = new JLabel("label 1");
JLabel lbl2 = new JLabel("label 2");
JLabel lbl3 = new JLabel("label 3");
JLabel lbl4 = new JLabel("label 4");
JLabel lbl5 = new JLabel("label 5");
myPanel.add(lbl1);
myPanel.add(lbl2);
myPanel.add(lbl3);
myPanel.add(lbl4);
myPanel.add(lbl5);
lbl1.setLocation(27, 20);
lbl2.setLocation(123, 20);
lbl3.setLocation(273, 20);
lbl4.setLocation(363, 20);
lbl5.setLocation(453, 20);
lbl1.setSize(86, 14);
lbl2.setSize(140, 14);
lbl3.setSize(80, 14);
lbl4.setSize(80, 14);
lbl5.setSize(130, 14);
You have to set your container's Layout to null:
myPanel.setLayout(null);
However is a good advise also to take a look at the Matisse Layout Manager, I guess it is called GroupLayout now. The main problem with absolute positioning is what happens when the window changes its size.
Set the container's layout manager to null by calling setLayout(null).
Call the Component class's setbounds method for each of the container's children.
Call the Component class's repaint method.
Note:
Creating containers with absolutely positioned containers can cause problems if the window containing the container is resized.
Refer this link:
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
Layout managers are used to automatically determine the layout of components in a container. If you want to put components at specific coordinate locations, then you should not use a layout manager at all.
myPanel = new JPanel(null);
or
myPanel.setLayout(null);
My advise is to use an IDE like NetBeans with its GUI editor. To inspect the code and because there are many ways:
Setting the layout manager, or for absolute positioning doing a myPanel.setLayout(null), has several influences.
In general, assuming you do your calls in the constructor of a JFrame, you can call pack() to start the layouting.
Then, every layout manager uses its own implementation of add(Component) or add(Component, Constraint). BorderLayout's usage is with add(label, BorderLayout.CENTER) and so on.
// Best solution!!
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = (JPanel) frame.getContentPane();
panel.setLayout(null);
JLabel label = new JLabel("aaa");
panel.add(label);
Dimension size = label.getPreferredSize();
label.setBounds(100, 100, size.width, size.height);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
You can use your own method that calling by setSize, setLocation values for directly....! `
As well i show you how to use JProgress Bar
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class installComp{
void install(Component comp, int w, int h, int x, int y){
comp.setSize(w,h);
comp.setLocation(x,y);
}
}
class MyFrame extends JFrame{
int cur_val = 0;
JButton btn = new JButton("Mouse Over");
JProgressBar progress = new JProgressBar(0,100);
MyFrame (){
installComp comp=new installComp();
comp.install(btn,150,30,175,20);
comp.install(progress,400,20,50,70);
btn.addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent evt){
cur_val+=2;
progress.setValue(cur_val);
progress.setStringPainted(true);
progress.setString(null);
}
});
add(btn);
add(progress);
setLayout(null);
setSize(500,150);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setVisible(true);
}
}
class Demo{
public static void main(String args[]){
MyFrame f1=new MyFrame();
}
}

Categories

Resources