Java selectable JLabel - java

I have made a GUI with a gallery panel which shows images held in JLabels. I need to make JLabel highlightable and then remove it if the user clicks remove. Is there a way or should I change my approach?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class GalleryPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private int currentImage;
private JLabel[] images;
private final int MAX_IMAGES = 12;
private JScrollPane scrollPane;
private JList<JLabel> imageGallery;
private DefaultListModel<JLabel> listModel;
private JPanel imageHolder;
public void init()
{
setLayout(new BorderLayout());
imageHolder = new JPanel();
imageHolder.setLayout(new BoxLayout(imageHolder, BoxLayout.PAGE_AXIS));
imageHolder.setSize(getWidth(), getHeight());
images = new JLabel[MAX_IMAGES];
listModel = new DefaultListModel<JLabel>();
listModel.addElement(new JLabel(new ImageIcon("Untitled.png")));
imageGallery = new JList<JLabel>(listModel);
imageGallery.setBackground(Color.GRAY);
imageGallery.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
imageGallery.setLayoutOrientation(JList.VERTICAL);
imageGallery.setFixedCellHeight(50);
imageGallery.setFixedCellWidth(100);
scrollPane = new JScrollPane(imageHolder);
scrollPane.setBackground(Color.RED);
add(scrollPane, BorderLayout.CENTER);
}
public void addImageToGallery(File file)
{
if ( currentImage <= images.length - 1)
{
BufferedImage bufImage = null;
try
{
bufImage = ImageIO.read(file); //tries to load the image
}
catch (Exception e)
{
System.out.println("Unable to load file " + file.toString());
}
Image resizedImage = bufImage.getScaledInstance(bufImage.getWidth()/5, bufImage.getHeight()/5, Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(resizedImage);
images[currentImage] = new JLabel(icon, JLabel.CENTER);
//images[currentImage].setSize(resized);
//images[currentImage
images[currentImage].setBorder(new TitledBorder(new LineBorder(Color.GRAY,5), file.toString()));
imageHolder.add(images[currentImage]);
revalidate();
repaint();
currentImage++;
}
else
{
throw new ArrayIndexOutOfBoundsException("The gallery is full");
}
}
public final int getMaxImages()
{
return MAX_IMAGES;
}
public Dimension getPreferredSize()
{
return new Dimension(300, 700);
}
}

So you first of call should be the tutorals
How to use Lists
Selecting items in a list
Adding items to and removing items from a list
Which will give you the basic information you need to proceeded.
Based on your available code, you should not be adding a JLabel to the ListModel, you should never add components to data models, as more often than not, Swing components have there own concept of how they will render them.
In your case, you're actually lucky, as the default ListCellRenderer is based on a JLabel and will render Icon's automatically, for example
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
DefaultListModel model = new DefaultListModel();
model.addElement(new ImageIcon("mt01.jpg"));
model.addElement(new ImageIcon("mt02.jpg"));
model.addElement(new ImageIcon("mt03.jpg"));
JList list = new JList(model);
list.setVisibleRowCount(3);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(list.getSelectedIndex());
}
}
});
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Related

Add a JScrollPane to a JList

I have the following code:
Main:
package PackageMain;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Main {
public static JFrame frame = new JFrame("Window");
public static PanelOne p1;
public static PanelTwo p2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 800, 600);
p1 = new PanelOne();
p2 = new PanelTwo();
frame.setVisible(true);
} catch(Exception e){
}
}
});
}
And class 2:
package PackageMain;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class PanelOne{
public PanelOne(){
loadScreen();
}
public void loadScreen(){
JPanel p1 = new JPanel();
DefaultListModel model = new DefaultListModel<String>();
JList list = new JList<String>(model);
//
JScrollPane scroll = new JScrollPane(list);
list.setPreferredSize(null);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
scroll.setViewportView(list);
//
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
System.out.println("You selected " + list.getSelectedValue());
}
});
p1.add(list);
Main.frame.add(p1);
Main.frame.revalidate();
Main.frame.repaint();
for (int i = 0; i < 100; i++){
model.addElement("test");
}
}
I've tried a bunch of stuff to get the JScrollPane to appear on the JList, but it doesn't want to. My best guess is that the model is screwing things up, but this is a simplified version, and the model needs to be there.
JScrollPane scroll = new JScrollPane(list);
You add the JList to the JScrollPane which is correct.
p1.add(list);
But then you add the JList to the JPanel, which is incorrect. A component can only have a single parent, so theJListis removed from theJScrollPane`.
You need to add the JScrollPane to the JPanel:
p1.add( scroll );
You're adding the list to too many components: to the JScrollPane's viewport -- OK, but also to the p1 JPanel -- not OK. Add it only to the viewport, and then add the JScrollPane to the GUI (p1 if need be).
Also:
There's no need to add the JList to the JScrollPane twice, in the constructor and in the viewport view as you're doing, once is enough.
list.setPreferredSize(null);????
Just add Scroll Pane to the frame rather than the List.
change your line with the below code:
Main.frame.add(scroll);

Problems with Graphics drawImage

I've been hunting through past StackOverflow posts and trying to figure out why my image won't display.
I know that the ImageIO is fine since I can run getWidth() on my BufferedImage and it returns the correct width.
Here is my Graphic class, followed by my main class.
(I'm sorry for trashy code, I'm new to this.)
Code in Graphic class:
package blackjack;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Graphic extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public JFrame frame = new JFrame("Game Window");
public JPanel layout = new JPanel(new BorderLayout());
public JPanel menu = new JPanel();
public JPanel playing = new JPanel(new BorderLayout());
public JPanel game = new JPanel();
public BufferedImage cardArray[] = new BufferedImage[52];
public void begin() {
//starting menu
}
public void playersTurn() {
menu.add(playing);
Font font = new Font("",Font.PLAIN, 24);
JPanel btnHolder = new JPanel();
JLabel play = new JLabel("Playing:");
JLabel or = new JLabel(" or ");
JLabel question = new JLabel(" ? ");
question.setFont(font);
or.setFont(font);
play.setFont(font);
JButton hit = new JButton("Hit");
JButton stand = new JButton("Stand");
hit.addActionListener(this);
stand.addActionListener(this);
playing.add(play, BorderLayout.WEST);
playing.add(btnHolder, BorderLayout.CENTER);
btnHolder.add(hit);
btnHolder.add(or);
btnHolder.add(stand);
btnHolder.add(question);
}
public void gui() {
//main gui
Dimension imageD = new Dimension(71,96);
Dimension menuD = new Dimension(900,120);
menu.setBorder(BorderFactory.createLineBorder(Color.black));
menu.setPreferredSize(menuD);
JPanel titlePanel = new JPanel();
JLabel title = new JLabel("BlackJack");
title.setFont(new Font("", Font.PLAIN, 14));
titlePanel.add(title);
Graphic gr = new Graphic();
gr.setPreferredSize(imageD);
//adding
frame.add(layout);
layout.add(menu, BorderLayout.SOUTH);
layout.add(titlePanel, BorderLayout.NORTH);
layout.add(gr, BorderLayout.CENTER);
//frame settings
frame.setSize(900, 650);
frame.setResizable(false);
frame.setVisible(true);
}
public void buildPathArray() {
for(int i = 1; i<=52; i++){
BufferedImage im = null;
try {
im = ImageIO.read(new File(Blackjack.getInstallDir() + Blackjack.s + "src" + Blackjack.s + "cardpngs"+ Blackjack.s + (100+i)+".png"));
} catch (IOException e) {
e.printStackTrace();
}
cardArray[i-1]= im;
//System.out.println(Blackjack.getInstallDir() + "\\src\\cardpngs\\" + (100+i)+".png");
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Hit")) {
} else if(e.getActionCommand().equals("Stand")) {
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//g.setColor(Color.GREEN);
//g.fillOval(20, 20, 20, 20);
g.drawImage(cardArray[0], 0, 0, this);
}
}
Code in my main class:
package blackjack;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Blackjack {
public static String installDir = "";
public static String s = "";
public static void main(String[] args) {
Path currentRelativePath = Paths.get("");
installDir = currentRelativePath.toAbsolutePath().toString();
s = System.getProperty("file.separator");
Graphic gr = new Graphic();
gr.buildPathArray();
gr.gui();
//System.out.println(installDir);
//g.playersTurn();
}
public static String getInstallDir() {
return installDir;
}
}
The output is this:
You're creating one instance of Graphic in your Blackjack class...
public class Blackjack {
public static String installDir = "";
public static String s = "";
public static void main(String[] args) {
//...
Graphic gr = new Graphic();
gr.buildPathArray();
gr.gui();
}
And another in your Graphic class
public void gui() {
//...
Graphic gr = new Graphic();
gr.setPreferredSize(imageD);
//adding
//...
layout.add(gr, BorderLayout.CENTER);
//...
}
But you only initialise the images, using buildPathArray of the instance in you BlackBelt class, which is not what is actually displayed on the screen...
As a general rule of thumb, you shouldn't be creating an instance of JFrame from within another component with the express purpose of display that component. Your Graphic component is also trying to do too much. Instead, I would have a Game class, maybe, which pulled the title, menu and Graphic components together and then put that onto an instance of JFrame
The main reason for this is, is your Graphic class is trying to do too much. It should be solely responsible for display the cards and managing them. The Game class should manage the other UI elements and be responsible for ensuring that the UI meets the current state of the game "model", taking in user input (and listening to events from the other UI elements) and updating the model and responding to events that the model creates, a little more like...
BlackJack...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BlackJack {
public static void main(String[] args) {
new BlackJack();
}
public BlackJack() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Game extends JPanel {
private JPanel menu;
private Graphic graphic;
public Game() {
menu = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(900, 120);
}
};
menu.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel titlePanel = new JPanel();
JLabel title = new JLabel("BlackJack");
title.setFont(new Font("", Font.PLAIN, 14));
titlePanel.add(title);
Graphic gr = new Graphic();
gr.buildPathArray();
setLayout(new BorderLayout());
add(menu, BorderLayout.SOUTH);
add(titlePanel, BorderLayout.NORTH);
add(gr, BorderLayout.CENTER);
}
}
}
Graphic...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Graphic extends JPanel {
private static final long serialVersionUID = 1L;
public BufferedImage cardArray[] = new BufferedImage[52];
public void begin() {
//starting menu
}
public void playersTurn() {
// All of this belongs in Game
}
#Override
public Dimension getPreferredSize() {
return new Dimension(71,96);
}
public void buildPathArray() {
for (int i = 1; i <= 52; i++) {
BufferedImage im = null;
try {
im = ImageIO.read(new File(Blackjack.getInstallDir() + Blackjack.s + "src" + Blackjack.s + "cardpngs" + Blackjack.s + (100 + i) + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
cardArray[i - 1] = im;
//System.out.println(Blackjack.getInstallDir() + "\\src\\cardpngs\\" + (100+i)+".png");
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//g.setColor(Color.GREEN);
//g.fillOval(20, 20, 20, 20);
g.drawImage(cardArray[0], 0, 0, this);
}
}
You might also want to have a look at Model-View-Controller.

Wrapping JLabels inside a JPanel thats inside a JScrollPane

My Java is a bit rusty so please bear with me. I have a method in my GUI class that calls another class file which returns a JList. The problem im having is getting the text from the JList, you can see an example of the output below
package com.example.tests;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import com.example.tests.IJ_runTestAFJ;
public class GUI_v2 extends JFrame
{
private static final long serialVersionUID = 1L;
IJ_CommonSetup setup = new IJ_CommonSetup();
Container c;
JPanel panel;
JScrollPane userScrollPane, errorScrollPane, sysScrollPane;
JTextArea tfUserError, tfSysError;
private JButton resetButton;
public JList<String> errorList;
GUI_v2()
{
resetButton = new JButton();
resetButton.setText("Click to populate TextArea");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//test.runTest_Login(stUserName,stPwd);
updatePanel();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
panel = new JPanel();
tfSysError = new JTextArea(10,33);
tfSysError.setLineWrap(true);
tfSysError.setEditable(false);
tfSysError.setWrapStyleWord(false);
sysScrollPane = new JScrollPane(tfSysError);
sysScrollPane.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(sysScrollPane);
panel.add(resetButton);
c = getContentPane();
c.add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setSize(400,250); //width, height
setLocation(600,0);
setResizable(false);
validate();
}//close GUI
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Create and display the form */
EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI_v2().setVisible(true);
}
});
}
public void updatePanel()
{
errorList = new JList<String>();
errorList = setup.getErrorJList();
tfSysError.append(errorList.getComponent(1).toString());
validate();
}
}// end on class
IJ_CommonSetup.java
package com.example.tests;
import javax.swing.JLabel;
import javax.swing.JList;
public class IJ_CommonSetup{
/**
*
*/
public static String stError = new String();
public static JList<String> stJListError = new JList<String>();
public JList<String> getErrorJList(){
String error1 = new String("TestTestTestTestTestTestTestTestTestTestTestTestTestTest ");
String error2 = new String("ApplesApplesApplesApplesApplesApplesApplesApplesApplesApples ");
JLabel newError1 = new JLabel();
newError1.setText(error1);
JLabel newError2 = new JLabel(error2);
stJListError.add(newError1);
stJListError.add(newError2);
return stJListError;
}
}
im having some trouble getting labels to wrap inside a panel that's
inside a Scrollpane. At the moment if the string thats added to the
label is long it is aligned to the left which is fine but the label
stretches outside the panel cutting off the end of the string.
use JTextArea(int, int) in JScrollPane
setEditable(false) for JTextArea
instead of JLabels added to JPanel (in JScrollPane)
Normal text in a JLabel doesn't wrap. You can try using HTML:
String text = "<html>long text here</html";

Look and feel is not updating in Swing JTabbedPane

I have created an application in Java Swing. I offer the option to change the look and feel of the application from a menu, but after adding a new tab in JTabbedPane, it is not getting updated with the new look and feel.
I have already used this code:
Window windows[] = Frame.getWindows();
for(Window window : windows) {
SwingUtilities.updateComponentTreeUI(window);
}
Leveraging #Andrew's example and this old thing, it seems to work for me.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
/**
* #see https://stackoverflow.com/a/11949899/230513
* #see https://stackoverflow.com/a/5773956/230513
*/
public class JTabbedText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.addTab("Model", createPanel());
jtp.addTab("View", createPanel());
jtp.addTab("Control", createPanel());
f.add(createToolBar(f), BorderLayout.NORTH);
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
private static JToolBar createToolBar(final Component parent) {
final UIManager.LookAndFeelInfo[] available =
UIManager.getInstalledLookAndFeels();
List<String> names = new ArrayList<String>();
for (LookAndFeelInfo info : available) {
names.add(info.getName());
}
final JComboBox combo = new JComboBox(names.toArray());
String current = UIManager.getLookAndFeel().getName();
combo.setSelectedItem(current);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int index = combo.getSelectedIndex();
try {
UIManager.setLookAndFeel(
available[index].getClassName());
SwingUtilities.updateComponentTreeUI(parent);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
});
JToolBar bar = new JToolBar("L&F");
bar.add(combo);
return bar;
}
private static Box createPanel() {
Box panel = new Box(BoxLayout.X_AXIS);
JLabel label = new JLabel("Code: ", JLabel.LEFT);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
JTextArea text = new JTextArea(4, 16);
text.setAlignmentY(JTextField.TOP_ALIGNMENT);
text.append("#" + panel.hashCode());
text.append("\n#" + label.hashCode());
text.append("\n#" + label.hashCode());
panel.add(label);
panel.add(text);
return panel;
}
}

JLayeredPane formatting issue

I have a problem with my JLayeredPane, I am probably doing something incredibly simple but I cannot wrap my head around it. The problem i have is that all the components are merged together and have not order. Could you please rectify this as I have no idea. The order I am trying to do is have a layout like this
output
label1 (behind)
input (in Front)
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class window extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 7092006413113558324L;
private static int NewSize;
public static String MainInput;
public static JLabel label1 = new JLabel();
public static JTextField input = new JTextField(10);
public static JTextArea output = new JTextArea(main.Winx, NewSize);
public window() {
super("Satine. /InDev-01/");
JLabel label1;
NewSize = main.Winy - 20;
setLayout(new BorderLayout());
output.setToolTipText("");
add(input, BorderLayout.PAGE_END);
add(output, BorderLayout.CENTER);
input.addKeyListener(this);
input.requestFocus();
ImageIcon icon = new ImageIcon("C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Roaming\\.Satine\\img\\textbox.png", "This is the desc");
label1 = new JLabel(icon);
add(label1, BorderLayout.PAGE_END);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
try {
MainMenu.start();
} catch (IOException e1) {
System.out.print(e1.getCause());
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
And the main class.
import java.awt.Container;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class main {
public static int Winx, Winy;
private static JLayeredPane lpane = new JLayeredPane();
public static void main(String[] args) throws IOException{
Winx = window.WIDTH;
Winy = window.HEIGHT;
window Mth= new window();
Mth.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Mth.setSize(1280,720);
Mth.setVisible(true);
lpane.add(window.label1);
lpane.add(window.input);
lpane.add(window.output);
lpane.setLayer(window.label1, 2, -1);
lpane.setLayer(window.input, 1, 0);
lpane.setLayer(window.output, 3, 0);
Mth.pack();
}
}
Thank you for your time and I don't expect the code to be written for me, all I want is tips on where I am going wrong.
I recommend that you not use JLayeredPane as the overall layout of your GUI. Use BoxLayout or BorderLayout, and then use the JLayeredPane only where you need layering. Also, when adding components to the JLayeredPane, use the add method that takes a Component and an Integer. Don't call add(...) and then setLayer(...).
Edit: it's ok to use setLayer(...) as you're doing. I've never used this before, but per the API, it's one way to set the layer.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class LayeredPaneFun extends JPanel {
public static final String IMAGE_PATH = "http://duke.kenai.com/" +
"misc/Bullfight.jpg";
public LayeredPaneFun() {
try {
BufferedImage img = ImageIO.read(new URL(IMAGE_PATH));
ImageIcon icon = new ImageIcon(img);
JLabel backgrndLabel = new JLabel(icon);
backgrndLabel.setSize(backgrndLabel.getPreferredSize());
JPanel forgroundPanel = new JPanel(new GridBagLayout());
forgroundPanel.setOpaque(false);
JLabel fooLabel = new JLabel("Foo");
fooLabel.setFont(fooLabel.getFont().deriveFont(Font.BOLD, 32));
fooLabel.setForeground(Color.cyan);
forgroundPanel.add(fooLabel);
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JButton("bar"));
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JTextField(10));
forgroundPanel.setSize(backgrndLabel.getPreferredSize());
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(backgrndLabel.getPreferredSize());
layeredPane.add(backgrndLabel, JLayeredPane.DEFAULT_LAYER);
layeredPane.add(forgroundPanel, JLayeredPane.PALETTE_LAYER);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(new JScrollPane(new JTextArea("Output", 10, 40)));
add(layeredPane);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("LayeredPaneFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LayeredPaneFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories