JLayeredPane with a JDialog - java

I am unable to make any components apear on a JLayeredPane when adding it to a JDialog.
I have also been unable to find a web resource that shows this may be done in a reasonably sized block of code. Every sight iv looked at "claims" this can be done, and then shows a disgustingly long solution.
What i want is to take a JLayered pane add a Button and place a JLabel with an icon in it onto this pane aswell. In english i want a button with an icon stuck in the front of its text.
That is the awt Button as I have been unable to find a way of making a system looking swing JButton.
Edit: could you help me out with something a little more specific. I think I was a littile to vague in my post.
Button button = new Button("ok");
JDialog dialog = new JDialog(null,"Windows",Dialog.ModalityType.APPLICATION_MODAL);
dialog.getLayeredPane().add(button);
dialog.pack();
dialog.setVisible(true);

I don't seem to have any issues...
public class TestLayeredDialog {
public static void main(String[] args) {
new TestLayeredDialog();
}
public TestLayeredDialog() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JDialog dialog = new JDialog();
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setLayout(new BorderLayout());
dialog.add(new MyContent());
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
System.exit(0);
}
});
}
public class MyContent extends JLayeredPane {
public MyContent() {
JLabel label = new JLabel("Hello new world");
label.setSize(label.getPreferredSize());
label.setLocation(0, 0);
add(label);
Dimension size = getPreferredSize();
JButton button = new JButton("Click me");
button.setSize(button.getPreferredSize());
button.setLocation(size.width - button.getWidth(), size.height - button.getHeight());
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(MyContent.this).dispose();
}
});
add(button);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Remember, JLayeredPane DOES NOT have a layout manager. You become responsible for managing the size and position of the child components, that's the point.
Updated with new example
public class TestLayeredDialog {
public static void main(String[] args) {
new TestLayeredDialog();
}
public TestLayeredDialog() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JDialog dialog = new JDialog();
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setLayout(new BorderLayout());
JLabel label = new JLabel("Hello new world");
label.setSize(label.getPreferredSize());
label.setLocation(0, 0);
dialog.getLayeredPane().add(label, new Integer(1));
dialog.setSize(100, 100);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
System.exit(0);
}
});
}
}
The layered pane of the JRootPane is responsible for (amongst other things) laying out the content pane and menu bar. It is also used (in some cases) to display things like popups.
Have a read through How to Use Root Panes
You can choose to put components in the root pane's layered pane. If
you do, then you should be aware that certain depths are defined to be
used for specific functions, and you should use the depths as
intended. Otherwise, your components might not play well with the
others. Here's a diagram that shows the functional layers and their
relationship:
Using this, means you are competing with components already on the screen.
Unless you have VERY good reason to be messing with this component, I would suggest you avoid it as 1- It's possible to be changed in the future (the layer position of the components) and 2- It may interfere with other components used by the Swing API

This example seems to work with the following lines added to the constructor:
this.addMouseListener(new MouseHandler(this));
this.add(new JLabel("Label"));
this.add(new JButton(UIManager.getIcon("html.pendingImage")));

Related

java scrolling while dragging

So I have several problems:
1) Is this code OK ? Or can it be written better ? (I will have an array with pictures in the final version)
2) When I click Next button the rectangle that I drew on first picture stays on the second one, how to clear it ? So after pressing Next button there is no rectangle on the new picture ?
3) I want to be able to auto-scroll while I drag the mouse button (while drawing the rectangle), but it's not really working...
Please help
public class SelectionExample {
static public TestPane panelek;
static public BufferedImage tempimage;
public static void main(String[] args) {
new SelectionExample();
}
public SelectionExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
panelek = new TestPane();
panelek.setPreferredSize(new Dimension(100, 100));
panelek.setAutoscrolls(true);
JScrollPane scrollPane = new JScrollPane(panelek);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
frame.add(scrollPane, BorderLayout.CENTER);
JButton next = new JButton("NEXT");
frame.add(next, BorderLayout.PAGE_START);
try {
tempimage = ImageIO.read(new File("D:/test/temp1.jpg"));
} catch (IOException ex) {
Logger.getLogger(SelectionExample.class.getName()).log(Level.SEVERE, null, ex);
}
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try {
tempimage = ImageIO.read(new File("D:/test/temp2.jpg"));
} catch (IOException ex) {
Logger.getLogger(SelectionExample.class.getName()).log(Level.SEVERE, null, ex);
}
panelek.repaint();
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Is this code OK ? Or can it be written better ?
Don't use static variables. If you want to change the image on your panel then you need to create a setImage(...) method in your class. The method will then save the image and invoke repaint(). That is classes should be responsible for managing their properties and provide getter/setter methods.
The formatting of your code is terrible and therefore difficult to read. Use either tabs or spaces for code indentation and be consistent.
I want to be able to auto-scroll while I drag the mouse button
Read the API for the setAutoScrolls(...) method of the JComponent class. It provides code for the mouseDragged(...) method of your MouseMotionLister.

JTextArea is not getting added to frame

I am unable to understand why JTextArea is not getting displayed with my code.
This is the first time i am using FocusAdapter class in a swing program.
Here is the code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Focus extends FocusAdapter
{
JFrame f;
JTextArea jt;
Focus()
{
f=new JFrame("focus");
jt=new JTextArea(50,50);
jt.addFocusListener(this);
jt.setFont(new Font("varinda",Font.PLAIN,15));
f.setSize(550,550);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void focusGained(FocusEvent fe)
{
jt.setText("focusgained");
}
public static void main(String s[])
{
new Focus();
}
}
am unable to understand why JTextArea is not getting displayed with my code. This is the first time i am using FocusAdapter class in a swing program.
It was because you set the layout of the JFrame to null and I don't see you adding the JTextField to your JFrame.
You may do this:
f.add(jt);
jt.setBounds(x, y, width, height); //Give int values for x, y, width, height
Last but not least, try to use a layout for your JFrame and you can consider adding a JPanel to the JFrame instead of adding components directly into the JFrame.
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
The basic answer to you question is, you need to actually add the JTextArea to displable container, in this, your JFrame, for example...
public class Focus extends FocusAdapter
{
JFrame f;
JTextArea jt;
Focus()
{
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
jt=new JTextArea(50,50);
jt.addFocusListener(this);
jt.setFont(new Font("varinda",Font.PLAIN,15));
f = new JFrame("Testing");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(jt));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
public void focusGained(FocusEvent fe)
{
jt.setText("focusgained");
}
public static void main(String s[])
{
new Focus();
}
}
Have a look at
Laying Out Components Within a Container
How to Use Text Areas
How to Use Scroll Panes
for more details
You have not added the JTextArea to your JFrame. This is why it' not added. ;)
You can do so by:
f.add(jt);
f.setSize(500,500);
or:
f.add(new JScrollPane(jt) );

Content of JFrame not showing

When the user hits "close" in one JFrame frame, I want the JFrame credits to be displayed showing my name and stuff for 2.5 seconds before the program exits. Now, credits is showing, but empty without the textArea and the Button - couldnt find whats wrong.
Heres my code:
For the closing operation of frame
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
int result = JOptionPane.showConfirmDialog(null, "Sind Sie sicher?", "Schließen", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION){
credits.setVisible(true);
try {
Thread.sleep(2500);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.exit(0);
} else {
//do nothing
}
}
});
For credits (just the class initializing the frame):
public class CreditsFrame extends JFrame {
Positioner pos = new Positioner();
private JPanel contentPane;
ImageIcon frameIcon = new ImageIcon("files/images/frameicon.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CreditsFrame frame = new CreditsFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CreditsFrame() {
setIconImage(frameIcon.getImage());
setAlwaysOnTop(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(pos.posX(pos.screenX, 441), pos.posY(pos.screenY, 210), 441, 210);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JTextArea txtarea = new JTextArea();
txtarea.setBounds(10, 11, 415, 125);
txtarea.setEditable(false);
txtarea.setBackground(Color.WHITE);
txtarea.setWrapStyleWord(true);
txtarea.setLineWrap(true);
txtarea.append("created by & more here");
contentPane.setLayout(null);
contentPane.add(txtarea);
JButton btnOk = new JButton("Ok");
btnOk.setBounds(154, 147, 89, 23);
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
contentPane.add(btnOk);
}
}
Any suggestions for a quick fix? Thanks.
Any suggestions for a quick fix?
Yes, don't call Thread.sleep(...) on the Swing event thread unless you want to put your entire GUI to sleep. Instead use a Swing Timer to handle the delay. Basically, the timer's ActionListener will be called after the milliseconds delay has passed.
e.g.,
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
int result = JOptionPane.showConfirmDialog(null, "Sind Sie sicher?", "Schließen", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION){
credits.setVisible(true);
new Timer(2500, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit();
}
}).start();
} else {
//do nothing
}
}
});
Also, look at The Use of Multiple JFrames, Good/Bad Practice?
Other issues that will bite you in the future:
You look to be using null layouts and setBounds. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms different from the original one.
Never set a JTextAreas bounds as this will make it completely fail if it is placed within a JScrollPane and more text than can be displayed is added -- the scroll bars will seem not to work since you've artificially constrained the size of the text component.

Translucent loading overlay for JFrame

I have a JFrame containing various components and I would like to add a translucent grey overlay over the top while the application is initializing various things. Ideally it would prevent interaction with the underlying components and would be able to display some "Loading..." text or a spinning wheel or something similar.
Is there a simple way to do this using Java and Swing?
Take a look at JRootPane and JLayeredPane http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html#layeredpane
What you're asking about specifically sounds like a Glass Pane.
http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html#glasspane
The Glass Pane prevents interaction with underlying components and can be used to display something on top of your JFrame.
As #David said, you can use the glass pane for displaying some loading text or image above the rest of the application.
As for the grey overlay: why don't you use the built in ability to disable components as long as your application is loading? Disabled components will get grayed out automatically and cannot be interacted with by the user.
Something like this:
public class LoadingFrame extends JFrame{
JButton button;
public LoadingFrame() {
button = new JButton("ENTER");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Application entered");
}
});
setLayout(new BorderLayout());
add(button, BorderLayout.CENTER);
}
public void startLoading(){
final Component glassPane = getGlassPane();
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
final JLabel label = new JLabel();
panel.add(label, BorderLayout.SOUTH);
setGlassPane(panel);
panel.setVisible(true);
panel.setOpaque(false);
button.setEnabled(false);
Thread thread = new Thread(){
#Override
public void run() {
for (int i = 5; i > 0; i--) {
label.setText("Loading ... " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// loading finished
setGlassPane(glassPane);
button.setEnabled(true);
}
};
thread.start();
}
public static void main(String[] args) {
LoadingFrame frame = new LoadingFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.startLoading();
frame.setVisible(true);
}
}

Top Menu(close, minimize, maximize) Java

How to change Look and Feel for the ToolBar, the top menu (where the buttons to close, minimize, maximize)
Is it possible to like something change? (Add, delete button, assign a background)
What is import is required to create it?
you can set the background image of a JButton you could have a look at this: Swing Tutorial: JButton which shows the use of the new JButton(String text,ImageIcon imgIco) to create a JButton with an ImageIcon and String.
To set the colour of the background and text you could use setBackground(Color c) and setForeground(Color c)
or
Alternatively just customize Look and Feel color scheme by setting an appropriate supported Look and Feel and then change the color scheme/size etc of its components thier are hundreds of things you can change for every component see this for them all.
To customize the Exit, Minimize and Maximize Toolbar buttons this can also be using the Look and Feel ( Custom design for Close/Minimize buttons on JFrame ):
import java.awt.BorderLayout;
import javax.swing.*;
public class FrameCloseButtonsByLookAndFeel {
FrameCloseButtonsByLookAndFeel() {
String[] names = {
UIManager.getSystemLookAndFeelClassName(),
UIManager.getCrossPlatformLookAndFeelClassName()
};
for (String name : names) {
try {
UIManager.setLookAndFeel(name);
} catch (Exception e) {
e.printStackTrace();
}
// very important to get the window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame f = new JFrame(UIManager.getLookAndFeel().getName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel gui = new JPanel(new BorderLayout());
f.setContentPane(gui);
JTree tree = new JTree();
tree.setVisibleRowCount(4);
gui.add(tree, BorderLayout.LINE_START);
gui.add(new JScrollPane(new JTextArea(3,15)));
JToolBar toolbar = new JToolBar();
gui.add(toolbar, BorderLayout.PAGE_START);
for (int ii=1; ii<5; ii++) {
toolbar.add(new JButton("Button " + ii));
if (ii%2==0) {
toolbar.addSeparator();
}
}
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FrameCloseButtonsByLookAndFeel();
}
});
}
}
Well the easiest way to change frame titlebar look is to set LookAndFeel before you create your frame.
Probably this is what you are looking for - http://www.jtattoo.net/ScreenShots.html

Categories

Resources