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

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.

Related

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.

how to create 2 content panels in north widget

can we create 2 content panels in north widget.
BorderLayoutContainer con = new BorderLayoutContainer();
ContentPanel cp = new ContentPanel();
VerticalLayoutContainer logoLayout = new VerticalLayoutContainer();
BorderLayoutData d = new BorderLayoutData(.20);
d.setMargins(new Margins());
Image logo = new Image("/IMAGES/Logo.png");
logoLayout.add(logo);
cp.add(logoLayout);
cp.setHeaderVisible(false);
con.setNorthWidget(cp, d);
please suggest me how to create two content panels.
Basically what I need to do is - please look into the image and let me know what I can do for that
You create your two panels within a single panel, and then assign that single panel to NORTH. Remember that your overall layout can be created from nested layouts.
ContentPanel cp = new ContentPanel();
JPanel panelA = new JPanel();
JPanel panelB = new JPanel();
JPanel panelBig = new JPanel();
panelBig.add(panelA);
panelBig.add(panelB);
cp.add(panelBig, BorderLayout.NORTH);
I think you can probably work out the rest of the details on your own.

Simple question about JTextArea

I want to create a blank text area in which the user can enter a few sentences, and then, when the user closes the window (or before), I want to save this text in a string (and print it just to test that it works). So far, the code I have written does not work:
JTextArea area = new JTextArea(5,20);
JScrollPane scrollPane = new JScrollPane(q);
JFrame frame = new JFrame("TextDemo");
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
String paragraph_text = area.getText();
System.out.println(paragraph_text);
You need to add your JTextArea to the scrollpane
JScrollPane scrollPane = new JScrollPane(area);

Categories