Java making a GUI - java

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

Related

JPanel inside JFrame doesn't show content sometimes. Why?

I managed to fix it but I don't understand why the same code results in different results. Some classmates have had the same problem.
The issue is that it I use miVentana.setVisible(true); before chicha(); the elements inside the JPanel will show when executing but if I run it again sometimes they won't ve visible until I resize the window, a few times not even the JPanel background color was visible. Just clicking the "Run" bottom on the IDE without changing anything else.
I just tried it 10 consecutive times and the elements were only visible on the 4th attempt.
Could this come from some memory garbage remaining from previous executions of the code?
I'm using Eclipse Version: Photon Release (4.8.0).
This is the code with the weird behaviour:
public class Ej10 extends JFrame {
public Ej10() {
setLayout(null);
}
static Ej10 miVentana = new Ej10();
public static void main(String[] args) {
miVentana.setTitle("Ejercicio10");
miVentana.setBounds(20, 20, 500, 600);
miVentana.setLocationRelativeTo(null);
miVentana.setVisible(true);
chicha();
//miVentana.setVisible(true);
}
static void chicha() {
JPanel miPanel = new JPanel();
miPanel.setLayout(new BoxLayout(miPanel, BoxLayout.PAGE_AXIS));
miPanel.setBounds(20, 20, 350, 450);
miPanel.setBackground(Color.CYAN);
JLabel lUsuario = new JLabel("Usuario:");
lUsuario.setVisible(true);
JTextField campoUsuario = new JTextField();
JLabel lPwd = new JLabel("Contraseña:");
JPasswordField campoPwd = new JPasswordField();
JButton bAcceso = new JButton("Acceder");
miPanel.add(lUsuario);
miPanel.add(campoUsuario);
miPanel.add(lPwd);
miPanel.add(campoPwd);
miPanel.add(bAcceso);
miPanel.setVisible(true);
miVentana.add(miPanel);
}
}
Components need to be added to the frame BEFORE the frame is made visible.
One of the functions of the setVisible() method is to invoke the layout manager. Otherwise components have a size() of (0, 0) so there is nothing to paint.
Also, all GUI components should be created on the Event Dispatch Thread (EDT), otherwise you can have random results. Read the section from the Swing tutorial on Concurrency for more information.
Take a look at the FrameDemo from How to Make Frames for the most basic example of how your code should be structured to avoid problems. It shows how to create components on the EDT and how to make the frame visible.
they won't ve visible until I resize the window,
Resizing the frame will also cause the layout manager to be invoked.
miPanel.setBounds(20, 20, 350, 450);
That statement will do nothing because the layout manager of the frame will determine the size and location of the panel based on the rules of the layout manager. The default layout manager for a frame is a BorderLayout, so basically the panel will get all the space available to the frame.
The tutorial also has a section on Layout Managers that you should read.

populating JTabbed Pane with JScroll panes according to user selection

We have a project for university which is a program to hold handouts and feedback for courseworks done.
What we've thought of is breaking the whole thing down into smaller pieces, for example:
You have a coursework which requires to write a program and a report on results etc.
So the user will create a new coursework by selecting the "code" and "report" options, since that's what is required. And then we need to create the respective tabs in the program so the user can input what is needed.
I have created all necessary forms and windows, It's just I'm not sure how to move on forward.
a) where should I put my code? should I have it on the "create" event?
b) how do I do this whole custom population thing?
Obviously, I'm not asking for the entire thing in code. I'm not even sure what to read and what to search for.
Following are some screenshots of the ui to help explain what I mean.
New project window
How the main window should be after creating a new projet. Notice the various tabs.
A form for report feedback
On your "Create" button click check for the checkbox.isSelected() and use the method below as:
if(reportCheckbox.isSelected()){
addonScreen(new reportFrame(),"Report Submission");
addonScreen(new reportFeedbackFrame(),"Report Feedback");
}
Use a desktop pane as a container...add your tabbed pane to it
public static JTabbedPane tabbedPane = new JTabbedPane();
jDesktopPane1.add(tabbedPane);
Use this method to add tabs to the layout at runtime
public static void addOnScreen(JInternalFrame inFrame, String title) {
//border for the internal frame
javax.swing.plaf.InternalFrameUI ifu = inFrame.getUI();
((javax.swing.plaf.basic.BasicInternalFrameUI) ifu).setNorthPane(null);
Border b1 = new LineBorder(new Color(114, 139, 173), 3, true) {
};
tabbedPane.setBounds(0, 0, jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setLocation(0, 0);
inFrame.setSize(jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setBorder(b1);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout());
jp.setOpaque(true);
jp.add(inFrame);
tabbedPane.addTab(title, jp);
tabbedPane.setSelectedComponent(jp);
inFrame.requestFocusInWindow();
inFrame.setVisible(true);
tabbedPane.setVisible(true);
}

Java: What Layout Manager would be best for a game menu?

===================
Game Name
Play
Exit
===================
the above is what my previous game menu looked like. I used the Box Layout to create it but it was very tedious. Is there there a better layout manager that I could use?
here is the code for those that asked of the main pane.
private JButton JB;
private JButton EB;
private JOptionPane JO;
public StartUpWindow(){
super("Pong");
JPanel outside = new JPanel();
JPanel inside = new JPanel();
setLayout(new BorderLayout());
outside.setLayout(new BoxLayout(outside, BoxLayout.LINE_AXIS));
inside.setLayout(new BoxLayout(inside, BoxLayout.PAGE_AXIS));
outside.add(Box.createHorizontalStrut(280));
outside.add(inside);
outside.add(Box.createHorizontalStrut(20));
inside.add(Box.createVerticalStrut(20));
JLabel title = new JLabel(" "+"Pong");
title.setFont( new Font("Serif", Font.BOLD, 40));
inside.add(title);
inside.add(Box.createVerticalStrut(20));
JButton btt1 = new JButton("Start");
Dimension d = new Dimension(200,40);
btt1.setSize(d);
btt1.setMinimumSize(d);
btt1.setMaximumSize(d);
btt1.setPreferredSize(d);
JButton btt2 = new JButton("Credits");
btt2.setSize(d);
btt2.setMinimumSize(d);
btt2.setMaximumSize(d);
btt2.setPreferredSize(d);
JButton btt3 = new JButton("Exit");
btt3.setSize(d);
btt3.setMinimumSize(d);
btt3.setMaximumSize(d);
btt3.setPreferredSize(d);
inside.add(btt1);
btt1.addActionListener(this);
btt1.setActionCommand("start");
inside.add(Box.createVerticalStrut(5));
inside.add(btt2);
btt2.addActionListener(this);
btt2.setActionCommand("credits");
inside.add(Box.createVerticalStrut(5));
inside.add(btt3);
btt3.addActionListener(this);
btt3.setActionCommand("exit");
inside.add(Box.createVerticalStrut(20));
add(outside);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setVisible(true);
this.setResizable(false);
this.setLocation(450,200);
inside.setBackground(Color.GRAY);
outside.setBackground(Color.GRAY);
}
I agree that BoxLayout is tedious but I admire its relative simplicity.
Another quick and easy option is to use the "javax.swing.Box" class instead of using a layout manager directly.
Box box = Box.createVerticalBox();
box.add(new JLabel("Game"));
box.add(Box.createVerticalStrut(20));
box.add(new JLabel("Button 1"));
box.add(new JLabel("Button 2"));
JFrame frame = new JFrame();
frame.add(box);
frame.pack();
frame.setVisible(true);
Box offers a number of useful methods. You can use it to create vertical and horizontal boxes, create "struts" to reserve horizontal and vertical space, and create "glue" to fill in available space when the layout grows.
Of course you could also use GridBagLayout, but I tend to reserve it for more complex layouts. Box and his cousin BoxLayout are often good enough for simple layouts and are easy for new programmers who are maintaining the application to understand and debug.
Why not simply use no layout and instead draw everything using a Graphics object?
You could easily achieve this by creating a BufferStrategy bound to the Window object (invoke createBufferStrategy on the latter) then call a few simple methods to easily redraw the screen.
This also means it's simpler to then code the game's display when you're playing it.
BufferStrategy also allows the use of page flipping and other forms of buffering when the application is in fullscreen exclusive mode, allowing it to refresh the screen very rapidly in many applications.

My JTextField doesn't appear

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

Java Swing panel layered on top with centered text

I'm making a simple Jeopardy-esque game:
using Java Swing. It's obviously a JFrame with a JPanel in it and buttons in rows.
Now what I need is to add a layered panel with a centered and wrapped text in it:
Which I can remove later. I already tried using JTextPane and JTextArea and JPanel, none of those want to even display. The best effect I have achieved with AWT Panel, it does display but I can't center or wrap text in it.
Here's some code for which I appologise, I would usually try to make it short and readable but since it's not working I don't know what to do with it to make ti look better:
JLabel questionLabel = new JLabel(questionList.get(randomNumber).getQuestion(), SwingConstants.CENTER);
Font font = new Font("Arial", Font.PLAIN, 20);
//------------------JTextPane--------------------
JTextPane questionPane = new JTextPane();
questionPane.setForeground(Color.WHITE);
questionPane.setSize(gameWidth, gameHeight);
questionPane.setText(questionList.get(randomNumber).getQuestion());
questionPane.setFont(font);
questionPane.setEditable(false);
//------------------AWT panel--------------------
Panel awtPanel = new Panel();
awtPanel.setBackground(Color.blue);
awtPanel.setSize(game.getWidth(),game.getHeight());
Label labelQuestion = new Label("<html>" + questionList.get(randomNumber).getQuestion() + "</html>", Label.CENTER);
labelQuestion.setFont(font);
awtPanel.setForeground(Color.white);
awtPanel.add(labelQuestion);
//------------------JPanel-----------------------
JPanel layeredPanel = new JPanel();
layeredPanel.setBackground(Color.blue);
layeredPanel.setSize(game.getWidth(),game.getHeight());
JLabel jLabelQuestion = new JLabel("<html>" + questionList.get(randomNumber).getQuestion() + "</html>", SwingConstants.CENTER);
jLabelQuestion.setFont(font);
layeredPanel.setForeground(Color.WHITE);
layeredPanel.add(jLabelQuestion, BorderLayout.CENTER);
game.getLayeredPane().add(layeredPanel, JLayeredPane.DEFAULT_LAYER);
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
button.setEnabled(false);
font = new Font("Arial", Font.PLAIN, 16);
button.add(jLabelQuestion, BorderLayout.CENTER);
button.setDisabledIcon(new ImageIcon(source.getScaledInstance(gameWidth/4, gameHeight/5, java.awt.Image.SCALE_SMOOTH)));
questionList.remove(randomNumber);
logger.info(questionList.size());
game.getLayeredPane().remove(layeredPanel);
UPDATE: I chnaged to SWT rather than Swing, and I use the StackLayout with a few Composites in it, and just change between them as I see fit.
You can generally solve issues like this with a JLabel.
I would recommend encapsulating the above grid in the BorderLayout.CENTER of another pane, perhaps a new content pane. Then, add the caption to BorderLayout.NORTH.
As a more tangible example,
private void createContent() {
this.getContentPane().setLayout(new BorderLayout());
//establish the panel currently set as center, here labeled "everythingElse"
this.getContentPane().add(everythingElse, BorderLayout.CENTER);
//Create a JLabel with your caption
JLabel jlbl = new JLabel("Question");
//format that caption, most details being rather obvious, but most importantly:
jlbl.setHorizontalAlignment(SwingConstants.CENTER); //keeps text centered
this.getContentPane().add(jlbl, BorderLayout.NORTH); //add it to the top of the panel
//...other cleanup operations...
}
The issue with grid panes is that they have a limited tolerance for the number of components visible in them. If you overload one, it won't show. For BorderLayout panes, you can easily swap new items into and out of them.
For efficiency's sake, I might recommend compiling this JLabel as a final somewhere else in your code, and holding onto it for when you need it. This way, you will also dodge overhead from repeatedly creating the label object.
Lastly, avoid AWT whenever you can. It's been deprecated for an excess of ten years, and if you do use it you will run into numerous critical problems involving heavyweight and lightweight component incompatibilities. If you intend to use another windowing kit, consider implementing the new standard, JavaFX, with a JFXPane-- it's much more tolerant of HTML syntax, as well.

Categories

Resources