My JTextField doesn't appear - java

Here is my java code:
JLabel persAdi,persSoyadi,persKodu,ust,alt;
JTextField ad,soyad,tckimlikno;
JButton bul,iptal;
public persBul(){
setSize (400,600);
setResizable(false);
setLocation (20, 20);
setVisible(true);
Container icerik = getContentPane();
icerik.setLayout(null);
icerik.getX();
ust=new JLabel("Bulmak İstediğiniz Personelin;");
ust.setBounds(10, 10, 200, 30);
icerik.add(ust);
persAdi=new JLabel("Adı:");
persAdi.setBounds(10,40,80,15);
icerik.add(persAdi);
ad=new JTextField();
ad.setBounds(50, 40, 80, 20);
icerik.add(ad);
persSoyadi=new JLabel("Soyadı:");
persSoyadi.setBounds(10, 180, 80, 30);
icerik.add(persSoyadi);
soyad=new JTextField();
soyad.setBounds(200, 40, 100, 30);
Icon bulPng=new ImageIcon(getClass().getResource("search.png"));
Icon iptalPng=new ImageIcon(getClass().getResource("cancel.png"));
bul=new JButton("",bulPng);
bul.setBounds(20, 120, 40, 40);
icerik.add(bul);
iptal=new JButton("",iptalPng);
iptal.setBounds(90, 120, 40, 40);
icerik.add(iptal);
}
public static void main(String[] args){
persBul app=new persBul();
}
When I debug this code, my JTextField doesn't appear. Only first JLabel can appear and I don't see any other JLabel or JTextField or JButton. My button appears when my cursor is on it. I have to do this project but I haven't created the user interface yet. Can anybody help me?

You should avoid using null layouts.
You can achieve the same (or a ver aproximate) UI by using layout managers. As I pointed in this comment.
Here's a MCVE which I recommend you to do in further questions. Also look at How to ask guide in order to make better questions.
I made a new class because trying to modify yours was more work than this. Copy-paste it and understand how it works, then adapt it to your own class.
Edit
You can add separators to add spaces. Also as #Andrew Thompson said in his comment, you can look at How to use multiple layout managers (I did something like that in the example). Here are other options on How to add spaces in swing. Maybe GridBag Layout is the one which seems more like a null layout.
Here's a guide on layouts (link also provided by Andrew).
After reading your question:
Can I use setBounds(x,y,width,height); function with this code? Or What can I do for using this function (setBounds(x,y,width,height);)? Because I want to determine my own self x,y points of the JLabel,JTextField,JButton
You should avoid using setBounds(x,y,width,height); at all costs, because, as also Andrew gave the explanation of why:
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components.
Using a null layout could bring some unexpected errors while executing program. It is fine to use null layout (I mean, setBounds(x,y,width,height);, if and only if you're a newbie on swing, but as soon as posible try to start using the Layout Managers instead of the null layout.
What I want to say is: It's not wrong to use null layout only for educational purposes, but even as it is larger and sometimes more complex and requires a bit more thinking, it's better to use them in order to avoid unexpected errors. While you're a student use it, but avoid it if it's for a professional program.
Here's the output of this answer So you can see the use of spaces in swing.
import javax.swing.*;
import java.awt.*;
class example {
JFrame frame;
JPanel panel, hPanel1, hPanel2;
JLabel label1, label2;
JTextField field1, field2;
example() {
frame = new JFrame("example");
panel = new JPanel();
hPanel1 = new JPanel();
hPanel2 = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
hPanel1.setLayout(new FlowLayout());
hPanel2.setLayout(new FlowLayout());
label1 = new JLabel("Label 1");
label2 = new JLabel("Label 2");
field1 = new JTextField();
field2 = new JTextField();
field1.setColumns(6);
field2.setColumns(6);
hPanel1.add(label1);
hPanel1.add(field1);
hPanel2.add(label2);
hPanel2.add(field2);
panel.add(hPanel1);
panel.add(hPanel2);
frame.add(panel);
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new example();
}
});
}
}

Related

Generating java swing fields based on user input

Java beginner here.
I am trying to generate Labels based on user input(take input for the number of labels to generate between 0 to 50) in a JPanel inside a JScrollPane.
The labels are generating correctly but the problem is the panel cant be scrolled down to view all the Labels.
Is it because I am using absolute layout for the panel? If yes then what might be the solution? Please guide.
Note: I made the labels using an array of 50 JLabels in a for loop. Terrible programming practice maybe but works.
Here's the code snippet
frame = new JFrame();
frame.setSize(800, 800);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(103, 37, 439, 350);
frame.getContentPane().add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(null);
JButton btnGenerateLabels = new JButton("Generate Labels");
btnGenerateLabels.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel[] lab = new JLabel[50];
int y = 50;
for(int i=0; i<50; i++)
{
lab[i] = new JLabel();
lab[i].setText("Label "+(i+1));
panel.add(lab[i]);
lab[i].setBounds(180, y, 97, 25);
y += 30;
}
}
});
btnGenerateLabels.setBounds(129, 23, 152, 25);
panel.add(btnGenerateLabels);
Is it because I am using absolute layout for the panel?
Yes. Don't use a null layout. Swing was designed to be used with layout managers.
The solution is to use a layout manager, probably the GridLayout as was suggested.
After all the components have been added to the panel you then need to invoke revalidate() and repaint() on the panel. This will invoke the layout manager and each component will be given a size/location.
Scrollbars will then appear as required.

Java making a GUI

Probably gonna get pooped on for this, I am not asking anybody to do my homework, but I am reaching out for help. I've already done the first question but the professor is asking for me to make a GUI in the second question. I've actually never made a GUI in Java before so this is all really new to me.
Make a simple, but visually appealing, GUI that has at least the following features:
a. A text box to enter an email address;
b. A text box to enter a message title;
c. A text area to enter a message;
d. Appropriate labels for text entry areas;
e. Buttons to “Send,” “Save for later,” and “Discard” the message;
f. A checkbox to “Flag as Important.”
As you marked Netbeans i assume you use this IDE.
To get in touch with gui building i would recommend you the netbeans gui builder:
Netbeans Gui Builder Tutorial
For your simple task this should be more than enough if using such tools for your task is allowed
If you are to just create the controls (text 'box', text area, etc) and not make them do anything, this is really simple to do in Netbeans. just start a new application and drag and drop from the Swing Controls shown on the right of the Netbeans IDE.
For more on building java GUIs, try my guide at
http://philofjava.webstarts.com/
Definitely research on Java applets, that is most likely what the problem is references.
With applets, you can insert all those components onto a pop-up window at the coordinates of your choosing.
Edit: here's a sample from a project I had to do for a project in my java class. It creates the JFrame then puts the components on it. I'd really recommend looking up how to use Swing, a lot of websites offer in depth tutorials for every component you can use.
import javax.swing.*;
public class aSimpleApplet
{
public static void main(String args[])
{
JFrame frame = new JFrame("This is the frame that holds all the components");
frame.setSize(800, 800);
frame.setLayout(null);
frame.setVisible(true);
JButton button = new JButton("A button");
button.setBounds(25, 25, 150, 50);
JTextField textField = new JTextField("A text field");
textField.setBounds(200, 25, 575, 100);
JTextArea textArea = new JTextArea("A text area");
JScrollPane scrollBar = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollBar.setBounds(50, 175, 350, 300);
JCheckBox checkBox = new JCheckBox("A checkbox");
checkBox.setBounds(400, 200, 250, 50);
JLabel label = new JLabel("A label");
label.setBounds(100, 600, 150, 50);
frame.add(button);
frame.add(textField);
frame.add(scrollBar);
frame.add(checkBox);
frame.add(label);
}
}

Is there a way of moving JPanel in BorderLayout?

I am using a BorderLayout for the frame (the first one that "caught" my attention in the tuts) and a FlowLayout for the labels (the one I found appropriate for what I do), and the result shows up like this:
My objective is to push the "2*1" a little bit down, to sort of "center" it.
I looked around and found a lot of people saying to use a null layout, but then saying it's not the best alternative (even though my window is not resizable), and the other solution I found was using a combo of layouts (unless I misunderstood).
The question is the one on top of this, plus if not, what really is the best alternative? (The following is the code that makes this window (minus the vars and other methods, to simplify visualization).
public Frame() {
super("Jogo de Multiplicar!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(300, 200);
setResizable(false);
getContentPane().setBackground(pink);
mensagem = new TransparentPanel();
operacao = new TransparentPanel();
//added stuff in mensagem and operacao
add(operacao);
add(mensagem, BorderLayout.SOUTH);
}
My objective is to push the "2*1" a little bit down, to sort of "center" it.
If you just want more space at the top then you can use a Border:
operacao.setBorder( new EmptyBorder(...) );
Read the section from the Swing tutorial on How to Use Borders for more information.
If you want to actually center it you can use a BoxLayout:
Box box = Box.createVerticalBox();
box.add( Box.createVerticalGlue() );
box.add( topPanel );
box.add( Box.createVerticalGlue() );
box.add( bottomPanel );
The tutorial also has a section on How to Use BoxLayout. Search the table of contents.
You could use MigLayout as your only LayoutManager. It's pretty mighty and usually offers everything that the other managers do too.
With this it's pretty simple to center the components:
public class MultiplyExample extends JFrame{
private static final long serialVersionUID = 1L;
JLabel testLabel = new JLabel("2*2 = 4");
public MultiplyExample(){
super("Example");
setBounds(300, 50, 200, 200);
// Set the MigLayout, so that columns and then rows get centered
setLayout(new MigLayout("center, center"));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(testLabel);
}
public static void main(String[] args) {
JFrame testFrame = new MultiplyExample();
testFrame.setVisible(true);
}
}
Result:
Here is a demo what the MigLayout has to offer:
http://www.miglayout.com/swingdemoapp.jnlp
Here is a quickstart-guide:
http://www.miglayout.com/QuickStart.pdf
If you have to use BorderLayout, you could put your components onto another panel and put this one into the center by using BorderLayout.CENTER:
pane.add(button, BorderLayout.CENTER);

How to re-size JButton

I've bee teaching myself java and following along with the problems in the book. I'm trying to make a display for my calculator. In the example(I did not attach this) the buttons were a smaller size than what mine are and I can't figure out how to reformat them. I tried using the dimension class but it had no affect. Also, I can't get my text at the top of the calculator to align left.
Here is my code:
public class Calculator extends JFrame {
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(300, 300);
setLayout(new BorderLayout());
JPanel numberPanel = new JPanel();
add(numberPanel, BorderLayout.CENTER);
numberPanel.setLayout(new GridLayout(4, 3, 3, 3));
for(int i = 1; i < 10; i++) {
JButton button = new JButton(String.valueOf(i));
numberPanel.add(button);
}
JButton zero = new JButton("" + 0);
JButton dot = new JButton(".");
JButton clear = new JButton("C");
numberPanel.add(zero);
numberPanel.add(dot);
numberPanel.add(clear);
JPanel keyPanel = new JPanel();
add(keyPanel, BorderLayout.EAST);
keyPanel.setLayout(new GridLayout(4, 1, 3, 3));
JButton plus = new JButton("+");
JButton minus = new JButton("-");
JButton times = new JButton("*");
JButton divide = new JButton("/");
keyPanel.add(plus);
keyPanel.add(minus);
keyPanel.add(times);
keyPanel.add(divide);
JPanel equalsPanel = new JPanel();
add(equalsPanel, BorderLayout.SOUTH);
equalsPanel.setLayout(new GridLayout(1, 1));
JButton equals = new JButton("=");
equalsPanel.add(equals);
JPanel textPanel = new JPanel();
add(textPanel, BorderLayout.NORTH);
JTextField inputBox = new JTextField("0.0");
inputBox.setHorizontalAlignment(JTextField.LEFT);
inputBox.setEditable(false);
Font font = new Font("MonoSpaced", Font.BOLD, 20);
inputBox.setFont(font);
textPanel.add(inputBox);
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
}
Imports were left off for brevity
GridLayout will laugh at you when you try and set a dimension. It does respect preferred sizes. You should select a layout manager that will respect preferred sizes. Or you can simply pack() (after you add all your components) your frame instead of setSize() and all the components preferred sizes will kick in. (Disclaimer - because of GridLayout though, if you try and resize the frame after that, you components will resize again)
See more at How to use Layout Managers. For a quick view of which layout managers respect preferred sizes and which ones don't, have a look at this post.
A common approach is to nest panels with different layout managers also, as seen here
UPDATE
As mentioned preciously, you should just call pack on the frame instead of set size. With your current code, this would cause the frame to be very small because of the preferred sizes of the components. If you want the buttons to have a bigger preferred size, you can set the font to a bigger font and/or use button.setMargins(new Insets(w,x,y,x)); to make the margins bigger. But it is preferred to pack the frame.
I would recommend using the Window Builder add-on if you’re using Eclipse. This tool will help you with many aspects of Swing. Learn by doing.
WindowBuilder Dowload Link

java swing calculator layouts

I need to do an assignment and create a calculator. It's a beginner Java course, so keep in mind that I'm no expert. It shouldn't look spectacular, so the easiest way to achieve the below would be great.
The inner workings of it is fine, but drawing it has been a real headache.
We've only gotten exposure to flowlayout so far...and in this instance it's not what I want at all. Let me start of by telling you what layout I'm looking for:
At the top a heading spreading across the calculator, with perhaps a
background fill.
Then below that, 2 buttons next to each other.
Below that, two labels next to each other.
Then two text field next to each other.
Below that, two labels next to each other.
Then two text field next to each other.
I tried drawing it here, but it doesn't format correctly. If I can put it in HTML it would basically be a simple table, with 6 rows and 2 columns. But the top row must span across both columns.
Flowlayout just put everything next to each other from left to right.
After that I tried using GridLayout, but the top heading was the problem here, as it didn't span across both columns.
Here is my code so far:
public class TripCalculator extends JFrame implements ActionListener {
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
public static final int NUMBER_OF_CHAR = 4;
public JTextField stopTime, distance, tripTime, speed;
public TripCalculator() {
setSize(WIDTH, HEIGHT);
WindowDestroyer listener = new WindowDestroyer();
addWindowListener(listener);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JLabel heading = new JLabel("HEADING");
contentPane.add(heading);
contentPane.setLayout(new FlowLayout());
JButton addStop = new JButton("BUTTON1");
addStop.addActionListener(this);
JButton addLeg = new JButton("BUTTON2");
addLeg.addActionListener(this);
contentPane.add(addStop);
contentPane.add(addLeg);
JLabel subHead1 = new JLabel("LABEL1");
contentPane.add(subHead1);
JLabel subHead2 = new JLabel("LABEL2");
contentPane.add(subHead2);
stopTime = new JTextField(NUMBER_OF_CHAR);
contentPane.add(stopTime);
distance = new JTextField(NUMBER_OF_CHAR);
contentPane.add(distance);
JLabel subHead3 = new JLabel("LABEL3");
contentPane.add(subHead3);
JLabel subHead4 = new JLabel("LABEL4");
contentPane.add(subHead4);
tripTime = new JTextField(NUMBER_OF_CHAR);
contentPane.add(tripTime);
speed = new JTextField(NUMBER_OF_CHAR);
contentPane.add(speed);
}
}
I would greatly appreciate if anyone can show me in the right direction.
Flowlayout or Gridlayout by themselves won't help you. Either you can use Gridbaglayout, or a combination of layouts such as FlowLaout+Gridlayout.
If you are drawing a calculator, I am assuming you are drawing something like this :
Where you have title information at the top, a calculator keypad in the middle, and some other buttons at the bottom :
This could be achieved with a vertical box layout, with flowlayouts at the top and bottom, and in the middle a grid layout with all the number keys.
But... without you showing a diagram of what you want its very difficult to say.
Here's an example of using multiple Layout Managers as you can see you can use more than one, but you should use more than one JPanel to achieve what you want.
Also a recommendation is: Don't extend from JFrame, instead create a JFrame object as I did in this example and here's why you shouldn't do that.
import java.awt.*;
import javax.swing.*;
public class LayoutManagersExample {
public static void main(String args[]) {
new LayoutManagersExample();
}
public LayoutManagersExample() {
JFrame frame = new JFrame("Layout Managers Example");
JPanel topPane = new JPanel();
JPanel midPane = new JPanel();
JPanel panesHolder = new JPanel();
JLabel label = new JLabel("Top label");
JTextField field = new JTextField();
field.setColumns(5);
topPane.setLayout(new FlowLayout());
midPane.setLayout(new GridLayout(3, 2));
topPane.add(label);
topPane.add(field);
midPane.add(new JButton("Button 1"));
midPane.add(new JButton("Button 2"));
midPane.add(new JButton("Hello I'm a button"));
midPane.add(new JButton("HEY! Click me :)"));
midPane.add(new JButton("I love you"));
midPane.add(new JButton("This is another button"));
panesHolder.setLayout(new BoxLayout(panesHolder, BoxLayout.Y_AXIS));
panesHolder.add(topPane);
panesHolder.add(midPane);
frame.add(panesHolder);
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
}
And this is how it looks like:

Categories

Resources