JFrame wait for user's input - java

I have a program which i need to get input from the user through a Jframe window.
Its like a while loop, where i invoke the Jframe window and get input from the user. But the JFrame window doesnt wait for input and run the loop until the last time it should run and only there waits for input.
I would like to make the Jframe window wait for input at each iteration of the while loop. Is there any way to do this ?
...
/**
* Create the frame.
*/
public Janela3(KieSession kSession) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 462, 447);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
kSession.setGlobal("J3", this);
contentPane.setLayout(null);
JPanel panelMain = new JPanel();
panelMain.setBackground(new Color(248, 148, 6));
panelMain.setBounds(0, 0, 448, 44);
contentPane.add(panelMain);
tituloJanela = new JLabel();
tituloJanela.setFont(new Font("Tahoma", Font.BOLD, 24));
tituloJanela.setForeground(new Color(255, 255, 255));
panelMain.add(tituloJanela);
kSession.setGlobal("TJ3", tituloJanela);
JPanel childPugh = new JPanel();
childPugh.setBounds(0, 44, 448, 364);
...
}

If I'm correct, you have a while loop in which you get user input but the loop may not continue if there is no input yet? Currently the information you provide is too limited to give a concrete answer but I'll give it a shot.
You could solve this by using another while loop that waits for input. Check 'the pseudo-semi-real code' below.
input = getInput();
while (input == null)
{
input = getInput();
}

Related

How to remove blank space between image and text inside the JPanel?

I'm trying to develop a little application for my Java class. I'm using jsoup to get information from an URL.
I finally got everything, but I don't know how to remove this huge blank between the images and the text. Any advice?
JFrame jf4 = new JFrame("¡¡NEWS WITH PICTURE!!");
JPanel p3 = new JPanel(new BorderLayout());
p3.setBorder(new EmptyBorder(5, 5, 0, 0));
p3.setLayout(new GridLayout(90, 2, 5, 5));
for (Element link: pictures) {
Element picture = link.select("source[media=(max-width: 48em)]").first();
Element text = link.select("img").first();
//System.out.println(picture);
//System.out.println(picture.attr("data-original-set"));
try {
JLabel label3 = new JLabel();
label3.setIcon(new ImageIcon(new ImageIcon(new URL(picture.attr("data-original-set"))).getImage().getScaledInstance(300, 300, Image.SCALE_DEFAULT)));
p3.add(label3);
JLabel label4 = new JLabel(text.attr("alt"));
p3.add(label4);
} catch (Exception exp) {
exp.printStackTrace();
System.out.println(exp);
}
} // IN CASE OF ERROR OF THE URL IT PRINTS java.net.MalformedURLException: no protocol: LINK TRIED
JScrollPane panelPane2 = new JScrollPane(p3);
jf4.getContentPane().add(panelPane2);
jf4.pack();
jf4.setVisible(true);
jf4.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Finally thanks to #prasad_ I get the solution.
I follow his advice. Instead of creating a new JLabel I use the propiertie setText on the same label.
Instead of this:
JLabel label3 = new JLabel();
label3.setIcon(new ImageIcon(new ImageIcon(new URL(picture.attr("data-original-set"))).getImage().getScaledInstance(300, 300, Image.SCALE_DEFAULT)));
p3.add(label3);
JLabel label4 = new JLabel(text.attr("alt"));
p3.add(label4);
I do this:
JLabel label3 = new JLabel();
label3.setIcon(new ImageIcon(new ImageIcon(new URL(picture.attr("data-original-set"))).getImage().getScaledInstance(300, 300, Image.SCALE_DEFAULT)));
label3.setText(text.attr("alt"));
p3.add(label3);
So finally, the blank disappear.

Positioning two panels on JFrame [duplicate]

This question already has an answer here:
JAVA positioning labels on JFRAME
(1 answer)
Closed 5 years ago.
I'm trying to get an output like this (designed with Netbeans designer), where I need to actually design it by code:
Where the layout of the JFrame should be like this:
JFrame frame = new JFrame("Horizontal Histogram");
frame.setVisible(true);
frame.setSize(400, 300);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 1));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.add(panel);
JPanel panel_2 = new JPanel();
panel_2.setLayout(new GridLayout(5, 1));
panel_2.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.add(panel_2);
JLabel label_1 = new JLabel("0-29");
JLabel label_2 = new JLabel("30-39");
JLabel label_3 = new JLabel("40-69");
JLabel label_4 = new JLabel("70-100");
JLabel stats_1 = new JLabel(); //number of stars
JLabel stats_2 = new JLabel();
JLabel stats_3 = new JLabel();
JLabel stats_4 = new JLabel();
stats_1.setText(stars); //starts is a string like ("***")
stats_2.setText(stars);
stats_3.setText(stars);
stats_4.setText(stars);
panel.add(label_1);
panel.add(label_2);
panel.add(label_3);
panel.add(label_4);
My code below only shows the stars, in one entire column. If I remove the second panel and add the 'stats labels' to the first panel it shows a 2 x 4 grid layout like this:
Any ideas on how to get an output like the first image I've posted?
JFrame uses by default BorderLayout.
This: frame.add(panel); adds panel to BorderLayout.CENTER
This: frame.add(panel_2); adds panel_2 to BorderLayout.CENTER
The problem is that BorderLayout.CENTER can hold one component only.
Use:
frame.add(panel, BorderLayout.WEST); and frame.add(panel_2, BorderLayout.EAST);
To get better insight of layouts read A Visual Guide to Layout Managers.

JScrollPane Not Scrolling In JTextArea

There's something that I don't understand. My code does not like JScrollBar apparently. I add it and I cannot scroll horizontally nor vertically.
Here's what it looks like:
Keep in mind that I'm new and I'm still working on it, so I'm sorry if it was something really obvious and easily avoidable.
public ChangeLog() {
//Init.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextArea textarea = new JTextArea();
JScrollPane scrollpane = new JScrollPane(textarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Text Stuff
textarea.setFont(textarea.getFont().deriveFont(16f));
textarea.setText("Change Log: \n V1.0(A): Original encoder \n V1.0(B): Original decoder \n V1.1: Combination of both encoder and decoder \n V1.2: Added a heavier encoding & decoding system \n V1.3: Added an icon \n V1.4: Created an 'Info' page \n V1.5: Added a 'Change Log' page to the 'Info' page \n "
+ "V1.6: Removed the 'Change Log' \n V1.7: Added a 'Change Log' but was not implemented \n V1.8: Added a the 'Change Log' button \n V1.9: Added horizontal and vertical scroll bars to the 'Change Log'");
textarea.setForeground(Color.BLACK);
Dimension d = new Dimension(250, 275);
textarea.setPreferredSize(d);
//Other Stuff
scrollpane.setViewportView(textarea);
scrollpane.getPreferredSize();
//Layout
panel.setLayout(null);
scrollpane.setBounds(new Rectangle(new Point(20, 20), scrollpane.getPreferredSize()));
textarea.setBounds(new Rectangle(new Point(20, 23), textarea.getPreferredSize()));
//Frame Stuff
frame.setAlwaysOnTop(true);
frame.setSize(300, 350);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
//Panel Stuff
frame.add(panel);
panel.setSize(frame.getSize());
panel.setBackground(Color.BLUE);
panel.add(textarea);
panel.add(scrollpane);
} }
I have created a working solution. Made some changes also.
public TestClass() {
//Init.
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JTextArea textarea = new JTextArea();
JScrollPane scrollpane = new JScrollPane(textarea);
panel.add(scrollpane, BorderLayout.CENTER);
//Text Stuff
textarea.setFont(textarea.getFont().deriveFont(16f));
textarea.setText("Change Log: \n V1.0(A): Original encoder \n V1.0(B): Original decoder \n V1.1: Combination of both encoder and decoder \n V1.2: Added a heavier encoding & decoding system \n V1.3: Added an icon \n V1.4: Created an 'Info' page \n V1.5: Added a 'Change Log' page to the 'Info' page \n "
+ "V1.6: Removed the 'Change Log' \n V1.7: Added a 'Change Log' but was not implemented \n V1.8: Added a the 'Change Log' button \n V1.9: Added horizontal and vertical scroll bars to the 'Change Log'");
textarea.setForeground(Color.BLACK);
//Dimension d = new Dimension(250, 275);
//textarea.setPreferredSize(d);
//Other Stuff
scrollpane.setViewportView(textarea);
scrollpane.getPreferredSize();
//Layout
//scrollpane.setBounds(new Rectangle(new Point(20, 20), scrollpane.getPreferredSize()));
//textarea.setBounds(new Rectangle(new Point(20, 23), textarea.getPreferredSize()));
//Listeners
//Frame Stuff
frame.setAlwaysOnTop(true);
frame.setSize(300, 350);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
//Panel Stuff
frame.add(panel);
panel.setSize(frame.getSize());
panel.setBackground(Color.BLUE);
panel.add(scrollpane);
}
Also when swing better works with the layout managers and null layout will leads to inconsistent look on different screen types.
Let me know if anything more required. And yes everybody starts from scratch. I am still learning. You will too get many things. Just keep the hunger of learning. :-)
Dimension d = new Dimension(250, 275);
textarea.setPreferredSize(d);
Don't hardcode a size for the text area. The size of the text area will change dynamically as text is added/removed and scrollbars will appear/disappear as required.
JTextArea textarea = new JTextArea();
Don't create the text area with no parameters. Instead, when you create the text area use something like:
JTextArea textarea = new JTextArea(5, 20);
to suggest a default size of the text area. Then when you have more than 5 lines of text the scrollbar will appear.
So I'm a relatively new Java developer
Start by reading the Swing Tutorial for Swing basics. There is a section on How to Use Text Areas to get you started.
panel.setLayout(null);
scrollpane.setBounds(...)
Don't a null layout. Don't use setBounds(). Swing was designed to be used with layout managers. See the above tutorial for working examples.

Layered JLabels not working

When I attempt to layer JLabels, the end result has them appearing next to each other, with the gif overlapping the logo image even though I told it to be on the bottom layer.
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.io.*;
class GameFrame extends JFrame
{
ImageIcon logo, bg;
JTextPane l1;
JTextArea l2;
JLabel i1, i2;
JButton b1;
GridBagLayout g;
int count;
JLayeredPane jlp;
GameFrame() throws IOException, UnsupportedLookAndFeelException, ClassNotFoundException, InstantiationException, IllegalAccessException
{
super("Simple2.0");
setSize(400, 250);
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
count = 0;
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
jlp = new JLayeredPane();
jlp.setSize(400, 250);
jlp.setVisible(false);
bg = new ImageIcon("fire.gif");
i2 = new JLabel(bg);
i2.setBackground(new Color(0, 0, 0, 0));
i2.setVisible(false);
logo = new ImageIcon("logo.png");
i1 = new JLabel(logo);
i1.setBackground(new Color(0, 0, 0, 0));
i1.setVisible(false);
g = new GridBagLayout();
GridBagConstraints gb = new GridBagConstraints();
gb.gridy = 1;
gb.insets = new Insets(10, 0, 0, 0);
gb.anchor = GridBagConstraints.SOUTH;
setLayout(g);
l1 = new JTextPane();
l1.setBackground(getBackground());
l1.setEnabled(false);
l1.setDisabledTextColor(Color.BLACK);
l1.setSize(350, 200);
l1.setText("Hello and welcome to SIMPLE!");
l2 = new JTextArea();
l2.setSize(350, 200);
l2.setBackground(getBackground());
l2.setEnabled(false);
l2.setDisabledTextColor(Color.BLACK);
l2.setLineWrap(true);
l2.setWrapStyleWord(true);
l2.setVisible(false);
b1 = new JButton("continue");
b1.addActionListener((ActionEvent e) ->
{
if(count == 0)
{
l1.setVisible(false);
l2.setText(" This game was a rework of a text based game made by me and a friend of mine during our first semester in Java.");
l2.setVisible(true);
count++;
}
else if(count == 1)
{
l2.setText(" It was a simple attempt to make a combat and inventory system that would function within a Java operated terminal, and was"
+ " full of bugs, errors, and long workarounds to problems that can now easily be solved with our new ability.");
count++;
}
else if(count == 2)
{
l2.setVisible(false);
l1.setText("And as such I present our new work, SIMPLE.");
l1.setVisible(true);
count++;
}
else
{
l1.setVisible(false);
b1.setVisible(false);
i1.setVisible(true);
i2.setVisible(true);
jlp.setVisible(true);
}
});
jlp.add(i1, 0);
jlp.add(i2, 1);
add(l1);
add(l2);
add(i1);
add(i2);
add(b1, gb);
add(jlp);
setVisible(true);
}
}
Thanks in advance for any help!
edit: I added the specific layers but have not seen a change in the outcome, as blaring a problem as that would immediately seem.
Read the section from the Swing tutorial on How to Use Layered Panes for a working example that displays multiple layers on top of one another.
When you "add" the label to the layered pane, you need to specify the "layer" you want the label added to. The tutorial explains how the layering works.
Also, while looking at the tutorial look at the better way to structure your program so that:
the GUI is created on the Event Dispatch Thread
you don't extend JFrame.
It is better to start with the working example and then customize it slowly to your requirement.

Can I add more than on button to a java JFrame?

I am facing a problem, I want to add more than a button to a JFrame, but it only takes the last one and puts it into the frame, a sample of my code is below:
String isName = "";
JFrame frame = new JFrame(isName);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
String childAmb = "PDA276";
for (int j=0; j<3; j++){
if (childAmb.matches("Phone\\w\\w\\w"))
fancyButtonCreator(childAmb, new ImageIcon ("src/phone.gif"), frame);
else if (childAmb.matches("PDA\\w\\w\\w"))
fancyButtonCreator(childAmb, new ImageIcon ("src/pda.gif"), frame);
else if (childAmb.matches("PC\\w\\w\\w"))
fancyButtonCreator(childAmb, new ImageIcon ("src/pc.gif"), frame);
}
frame.setVisible(true);
frame.setBounds(100, 200, 200, 200);
Thank you.
If you don't have a layout-manager, only one, the last component added will show up.
frame.setLayout (new FlowLayout ());
frame.add (new JButton ("foo"));
frame.add (new JButton ("bar"));
Read the section from the Swing tutorial on Using Layout Managers for examples.
You can start with the FlowLayout.

Categories