Layered JLabels not working - java

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.

Related

display gifs in java jars using eclipse

Hi I am unsure on how to format my animated gif images to let them show on Jars created on eclipse.
try {
//ImageIcon titleIcon = new ImageIcon(ImageIO.read(getClass().getResource("title.gif")));
title = new ImagePicture (new ImageIcon(ImageIO.read(getClass().getResource("title.gif"))), 0, 0);
//title = new ImagePicture (new ImageIcon("title.gif"), 0, 0);
}//end try
catch (IOException e) {
}//end catch
//set title bounds
title.setBounds(260, 0, 400, 100);
That is my code right now for an animated GIF, Thank you for your input.
Hard to give a good example without more context, but you can try adding the ImageIcon to a JLabel like this.
URL url = this.getClass().getResource("title.gif");
Icon title = new ImageIcon(url);
JLabel titleLbl = new JLabel(title);
//You have to add titleLbl to a container after this, of course

How to render all pages of a large size file in left side panel using Java PDF BOx 2.0.2

I am trying to use java pdfbox and customize it to render my large size pdf (100 MB ) with 1969 pages using that project.
I have changed the UI as per my requirement .Also the original PDF box doesnt render all the pages in form of images on the left side panel. So I added a separate piece of code to render the same . But doing so , is causing a huge memory leak .I can see usage of 1 gb of memory .
I suppose this is happening because I am trying to load all the pages in the memory in a JButton and then trying to render it .
Below is my piece of code :
private JPanel sidePanel = new JPanel();
sidePanel.setBorder(new EmptyBorder(0, 0, 0, 0));
for (int i = 1; i < numberOfPages + 1; i++) {
int pageListValue = i - 1;
JButton pageButton = new JButton();
JLabel pageNum = new JLabel();
try {
BufferedImage bim = pdfRenderer.renderImageWithDPI((i - 1), 100, ImageType.RGB);
ImageIcon imageIcon = new ImageIcon(resize(bim, 140, 190));
pageButton.setIcon(imageIcon);
} catch (IOException exception) {
exception.printStackTrace();
}
pageNum.setText(Integer.toString(i));
pageNum.setForeground(Color.WHITE);
pageButton.setBackground(new Color(39, 48, 55));
pageButton.setBorder(new EmptyBorder(0, 10, 0, 10));
pageNum.setBorder(new EmptyBorder(0, 0, 10, 0));
pageNum.setFont(new Font("Arial Narrow", Font.BOLD, 14));
pageNum.setAlignmentX(Component.CENTER_ALIGNMENT);
pageButton.setAlignmentX(Component.CENTER_ALIGNMENT);
pageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showPage(pageListValue);
}
});
sidePanel.add(pageButton);
sidePanel.add(pageNum);
pageButton=null;
pageNum=null;
}
Here , numberOfPages has a value of 1969 , hence the loop runs for 1969 times and loads all the buttons and labels in the memory and then add them to the side panel.
Is there any way I can do this without loading all the buttons in the memory and hence render them on my viewer at the same time while I am scrolling down the scroll bar.
Why do I need to use multithreading for this?
I need to load 2 pages in the memory at a time and when I scroll down , I need to remove the previous two pages and load the next two.
Any suggestion would be highly appreciated.

Can I resize only the height of my frame using pack()?

I am writing a program that brings up a JDialog box that lists multiple options from a config file. The number of options can vary each time it is opened, so I need to be able to dynamically adjust the height of the window, but not the width. The window looks best using FlowLayout and defining the width of the window so that the JPanels that the data is in wrap propertly. But I am unable to dynamically adjust the height. I tried to use the pack method, but it lines all the panels up in one line like FlowLayout is meant to be. I tried GridLayout but it re-sizes all of the panels to the same size and is an unacceptable look. I also tried BoxLayout but was unable to get that one to work.
Is there a better layout manager to use or a way to make the width static?
Here is my code. Every panel and box is defined above the constructor, I just did not copy that code:
public ReSizeMe()
{
curConfig = new Config();
config = curConfig.getConfig();
setBox = new JDialog();
setBox.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // Set as 480, 600
setBox.setLayout(new FlowLayout());
this.buildSetFrame();
//setBox.pack();
setBox.setVisible(true);
}
public void buildSetFrame()
{
intPanel = new JPanel();
butPanel = new JPanel();
optPanel = new JPanel();
editPanel = new JPanel[maxOptions];
optWrapper = new JPanel[maxOptions];
intPanel.setLayout(new FlowLayout());
optPanel.setLayout(new GridLayout(10, 1)); // trying different things here too.
optText = new JTextField[maxOptions];
editButton = new JButton[maxOptions];
delButton = new JButton[maxOptions];
intPanel.setBorder(BorderFactory.createTitledBorder("Modify Interface"));
apply = new JButton("Apply");
newOpt = new JButton("New Option");
help = new JButton("Help");
close = new JButton("Close");
intPanel.add(ethIntLabel);
intPanel.add(ethIntName);
butPanel.add(apply);
butPanel.add(newOpt);
butPanel.add(close);
ethIntName.setText(config.getProperty("EthIntName"));
setBox.add(welcomeMsg);
setBox.add(intPanel);
setBox.add(optPanel);
buildOptions();
setBox.add(butPanel);
}
void buildOptions()
{
for (int i = 0; i < maxOptions; i++)
{
editable = Boolean.parseBoolean(config.getProperty("option." + i + ".edit"));
if (config.getProperty("option." + i + ".name") == null)
{
break;
}
else if (editable != false &&
config.getProperty("option." + i + ".name") != null &&
!config.getProperty("option." + i + ".name").isEmpty())
{
editPanel[i] = new JPanel();
optWrapper[i] = new JPanel();
optText[i] = new JTextField(20);
editButton[i] = new JButton("Edit");
delButton[i] = new JButton("Delete");
editButton[i].setActionCommand(Integer.toString(i));
delButton[i].setActionCommand(Integer.toString(i));
optText[i].setText(config.getProperty("option." + i + ".name"));
optText[i].setEditable(false);
editPanel[i].add(editButton[i]);
editPanel[i].add(delButton[i]);
optWrapper[i].add(optText[i]);
optWrapper[i].add(editPanel[i]);
optPanel.add(optWrapper[i]);
}
}
}
Yes, Box should work wonderful:
Box box = Box.createVerticalBox();
box.add(...)
box.add(Box.createVerticalStrut(5)); // spacing
<etc.>
add(box);

Java: AWT Label not showing up

Pretty straightforward issue. My Java AWT (not Swing) label is simply not showing up. Most of the following code isn't even being used (for debugging this issue).
Just a note: this is within a Frame's constructor (and yes I have added several other panels and such that work just fine). Secondly, the frame's layout has been set to null.
I'm stumped.
File inf = new File("instructions.txt");
Label ilb;
if(inf.exists())
{
Log.v("Loading instructions");
try
{
FileInputStream fis = new FileInputStream(inf);
byte[] insb = new byte[65535];
fis.read(insb);
fis.close();
String inst = new String(insb);
ilb = new Label("test", Label.LEFT);
File fntfile = new File("font/pf_tempesta_seven.ttf");
Font infnt = null;
try {
FileInputStream ffis = new FileInputStream(fntfile);
infnt = Font.createFont(Font.TRUETYPE_FONT, ffis);
ffis.close();
} catch (FontFormatException e) {
Log.e("Could not format LCD font!", e);
} catch (IOException e) {
Log.e("Could not read LCD font file!", e);
}
if(infnt == null)
infnt = new Font("Trebuchet MS", Font.PLAIN, 8);
else
infnt = infnt.deriveFont(8.0f);
//ilb.setFont(infnt);
//ilb.setForeground(new Color(123, 123, 123));
//ilb.setPreferredSize(new Dimension(350, 400));
//ilb.setSize(350, 400);
//ilb.setLocation(580, 190);
Log.d("adding label");
add(ilb);
} catch(IOException e) {
Log.e("Could not read instructions!", e);
}
}else
Log.w("Instructions file not found!");
1) for todays GUI use Swing JComponents (starts with J) rather than prehistoric AWT Label
2) for your issue could be better use JTextArea with method append()
3) you have got issues with Concurency (in Swing) AWT / Swing is single threaded and all output to the GUI must be wrapped into invokeLater
4) for better help sooner you have edit your question with SSCCE
As #JBNizet suggested, null layouts don't work with all AWT components.
I was thrown off since my Panels were positioned just fine with a null layout on my Frame, whereas Labels require a basic layout in order to display. I was tempted to go as far as saying all other components had the same 'feature', but another part of my code proved that point wrong:
// Load Image
Log.v("Loading header image");
_iBG = new ImageIcon("img/hpcount_top_bg.png").getImage();
// Set size
setSize(1024, 152);
setPreferredSize(new Dimension(1024, 152));
// Set position
setLocation(0, 0);
// Set visible
setVisible(true);
// Set layout
setLayout(null);
// Add children
add(new Exit()); // Exit extends java.awt.Button
The above code (which is located within the constructor of a class extending java.awt.Panel) works perfectly.
My workaround is to put the label inside another Panel with a layout (messy, but it works) and position that panel within the Frame absolutely to achieve the same effect.

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