How can i obtain a flash message ( a black screen that splashes for few seconds) on screen for the time limit that i suggest ?
The whole screen of the computer should go black and there should be a message at the center.
For example in the following picture the length and width will be the length and width of the screen of the monitor:
Message covering the whole screen
I want this to be fired if a button is click or on it's own when some event is fired.
I'm not sure what you mean. Try this link. Here is also an example provided by Oracle for splash screens.
Next time, be sure to provide more information.
Here are my suggestions,
Since you want this every time you click a button, the splash screen is not a viable solution.I think you have to make a window with your message,but keep in mind that going full screen isn't as simple as making a large panel, you need to look into the underlying OS graphics. Here is a solution to create a full-screen (non-windowed) application in Java which might be helpful to you.
Also I suggest you to have a look at the Java's Full-Screen mode API .
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class displayFullScreen extends JFrame {
private JLabel alarmMessage = new JLabel("Alarm !");
private JPanel panel = new JPanel();
public displayFullScreen() {
setUndecorated(true);
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
alarmMessage.setText("Alarm !");
alarmMessage.setFont(new Font("Cambria",Font.BOLD,100));
alarmMessage.setForeground(Color.CYAN);
panel.add(alarmMessage);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width,screenSize.height);
panel.setBackground(Color.black);
add(panel);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
escapeHandler(ke);
}
});
}
public void escapeHandler(KeyEvent ke) {
if(ke.getKeyCode() == ke.VK_ESCAPE) {
displayFullScreen.this.dispose();
}
}
}
Related
I want do design a simple login format and in order to do so I want two JTextFields for Username/Password and a Login Button. The Login button is display as expected but when I add the JTextField, nothing shows in my JFrame. Would be nice if someone could help a beginner out...
Here's my code (I know it's ugly but this is just a "code sketch"):
package bucketlistpackage;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GameFrame extends JFrame {
public GameFrame(String title) {
super(title); //sets title of frame
startFrame(); //sets details of main frame
final Container logincont = getContentPane(); //creates content pane
JFrame loginframe = new JFrame();
usernameField(loginframe);
loginButton(loginframe);
logincont.add(loginframe);
}
private void usernameField(JFrame loginframe) {
JTextField usernameF = new JTextField("Username", 1);
usernameF.setBounds(50, 50, 50, 20);
loginframe.add(usernameF);
usernameF.setVisible(true);
}
private void startFrame() {
this.setSize(1000, 1000);
this.setVisible(true);
}
private void loginButton(Container cont) {
JButton loginB = new loginButton();
loginB.setSize(300, 150);
loginB.setText("Login");
cont.add(loginB);
}
}
The problem lies on how you are adding component to one another in your case.
You are adding a JFrame to a Container, when in all case it should be the other way around.
The other problem is that you are not using Layouts to manage the components positions on the JFrame.
Another problem as well is that you are not refreshing the windows after adding all the stuff on it.
A bit of a resume on how Java works with native UIs:
Java creates a new thread for the UI. So if you open the debugger you will see AWT threads as well as the main threads and others. This means that you have to manage this in a correct way, because after the application starts SWING and the functions you determine for reactions will lay the ground on how it will behave. Your main thread will die, but the visual threads will keep active.
If you are just starting to program I would encourage you to practice a bit more native java language before moving to SWING or AWT. This libraries can be really painful and tricky to use.
The other thing is SWING library follows a hierarchy for the components:
JFrame > JPanels > Components
In your code you have already worked with all of them but in a disorganized way. JFrame is the main application window, where the graphics will be displayed (can also be a Canvas or whatever class you want to use for that matter). JPanels are organizers, you can use different layouts to organize whatever is inside it. And finally the Components are well... everything! A component can be a JTextField, but it can also be a JPanel, or JButton.
The idea with SWING is to create multiple Panels and organize the end components inside them, using the help of the different layouts to see whats the best approach to make them attractive in many different window sizes.
Finally, if you are using Eclipse, there is a plugin called WindowBuilder which might help you. I don't recommend you using it if you are very new to Java since it will make you depend a lot on it instead of learning how to actually code with SWING.
Hope this helps!!!
Btw, to fix the code above I would do something like this:
public GameFrame(String title) {
super(title); //sets title of frame
startFrame(); //sets details of main frame
final Container logincont = getContentPane(); //creates content pane
logincont.setLayout(new BorderLayout());
usernameField(logincont, BorderLayout.NORTH);
loginButton(logincont, BorderLayout.CENTER);
this.revalidate();
this.repaint();
}
private void usernameField(Container loginframe, String direction) {
JTextField usernameF = new JTextField("Username");
// usernameF.setBounds(50, 50, 50, 20);
loginframe.add(usernameF, direction);
usernameF.setVisible(true);
}
private void startFrame() {
this.setSize(1000, 1000);
this.setVisible(true);
}
private void loginButton(Container cont, String direction) {
JButton loginB = new JButton();
loginB.setSize(300, 150);
loginB.setText("Login");
cont.add(loginB, direction);
}
I'm working on a project, there are JInternalFrames in the mainframe. Now, we need to let them to be JFrame. I'm considering using a JFrame to hold on JInternalFrame. The problem is that the titlebar of Internalframe is there, and user can drag it around.
Is there any way to make the Internal frame work like a pane in the JFrame?
After searching on the Internet, I found somebody removes the titlepane.
Do you have any good idea on this?
Thanks you!
update:
Maybe I was on the wrong track. The real problem is the JInternal frame can not get out of the main Frame, or any way to make it look like it's out side of the frame?
Is there any way to make the Internal frame work like a pane in the
JFrame
Im not sure by what you mean by pane, but I guess like a JPanel? Of course you can but why, would be my question, unless you want some sort of quick floating panel, but than you say you dont want it draggable? So Im bit unsure of your motives and makes me weary to answer....
The problem is that the titlebar of Internalframe is there
Well Here is code to remove the titlepane (found it here):
//remove title pane http://www.coderanch.com/t/505683/GUI/java/JInternalframe-decoration
BasicInternalFrameTitlePane titlePane =(BasicInternalFrameTitlePane)((BasicInternalFrameUI)jInternalFrame.getUI()).getNorthPane();
jInternalFrame.remove(titlePane);
and user can drag it around.
And I found this to make JInternalFrame unmovable by removing the MouseListeners which make it movable, but it is important to note its not necessary to remove the MouseListeners as the method used to make it undraggable will remove the NorthPane which the MouseListener is added too thus its unnecessary for us to remove it ourselves.:
//remove the listeners from UI which make the frame move
BasicInternalFrameUI basicInternalFrameUI = ((javax.swing.plaf.basic.BasicInternalFrameUI) jInternalFrame.getUI());
for (MouseListener listener : basicInternalFrameUI.getNorthPane().getMouseListeners()) {
basicInternalFrameUI.getNorthPane().removeMouseListener(listener);
}
And as per your title:
how to make JInternalFrame fill the Container
Simply call setSize(int width,int height) on JInternalFrame with parameters of the JDesktopPanes width and height (JDesktopPane will be sized via overriding getPreferredSize()).
Which will give us this:
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.event.MouseListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
/**
*
* #author David
*/
public class Test {
public Test() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void createAndShowGUI() throws HeadlessException {
JFrame frame = new JFrame();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JDesktopPane jdp = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
};
frame.setContentPane(jdp);
frame.pack();
createAndAddInternalFrame(jdp);
frame.setVisible(true);
}
private void createAndAddInternalFrame(final JDesktopPane jdp) {
JInternalFrame jInternalFrame = new JInternalFrame("Test", false, false, false, false);
jInternalFrame.setLocation(0, 0);
jInternalFrame.setSize(jdp.getWidth(), jdp.getHeight());
//remove title pane http://www.coderanch.com/t/505683/GUI/java/JInternalframe-decoration
BasicInternalFrameTitlePane titlePane = (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) jInternalFrame.getUI()).getNorthPane();
jInternalFrame.remove(titlePane);
/*
//remove the listeners from UI which make the frame move
BasicInternalFrameUI basicInternalFrameUI = ((javax.swing.plaf.basic.BasicInternalFrameUI) jInternalFrame.getUI());
for (MouseListener listener : basicInternalFrameUI.getNorthPane().getMouseListeners()) {
basicInternalFrameUI.getNorthPane().removeMouseListener(listener);
}
*/
jInternalFrame.setVisible(true);
jdp.add(jInternalFrame);
}
}
Given your requirements, I suggest you just use a simple JPanel inside your JFrame content pane.
I have been using this code to implement a Popup JDialog of sorts, like what you see when your anti-virus is scanning your system or updates itself:
import java.awt.*;
import javax.swing.JDialog;
import javax.swing.JLabel;
public class PopupDialog extends JDialog {
public PopupDialog() throws HeadlessException {
createUI();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
PopupDialog popupDialog = new PopupDialog();
popupDialog.setVisible(true);
}
});
}
private void createUI() {
setTitle("Popup Dialog");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
addComponentsToFrame();
//This call will give screens viable area, which takes into account the taskbar, which could be at the bottom, top,left or right of the screen.
Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
//get screen size
int sWidth = maxBounds.width, sHeight = maxBounds.height;
setSize(275, 225);//set frame size
Dimension appDim = getSize();
//get app size
int aWidth = appDim.width, aHeight = appDim.height;
//set location like a tooltip would be except its a custom dialog like an AV
setLocation(sWidth - aWidth, (sHeight - aHeight));
}
private void addComponentsToFrame() {
JLabel label = new JLabel("Popup Dialog");
getContentPane().add(label, BorderLayout.CENTER);
}
}
But my question is: is there any class or package in java that will do this for me? and if not how would I go about allowing the JDialog to slide up from the taskbar (or offscreen)? or somehow become visible in a slow manner like a ToolTip Popup would from the system tray. Thanks.
EDIT The reason i want to use a JDialog or Frame is because i want to be able to fully skin the Popup window, using setUndecorated(true); and adding custom exit icons, backgrounds etc
You mean like the examples here: http://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html ?
First, you can make your frame be always on top, this will ensure it is always visible. Next, you could position the frame off the bottom of the screen and slide it up programmatically. This should be fairly smooth even on an older XP machine. There is no standard Java API to do this but you can do it yourself pretty easily. Another option instead of sliding is to make the window fully transparent and fade it in. This API was added in recent (last 2 years) Java 6 updates, so it should be available everywhere.
I'm doing a project where i need some custom swing components. So far I have made a new button with a series of images (the Java Metal look doesn't fit with my UI at all). Ive implemented MouseListener on this new component and this is where my problem arises. My widget changes image on hover, click etc except my MouseListener picks up mouse entry into a the entire GridLayout container instead of into the image. So I have an image of about 200*100 and the surrounding container is about 400*200 and the mouseEntered method is fired when it enters that GridLayout section (even blank space parts of it) instead of over the image. How can I make it so that it is only fired when I hover over the image? Ive tried setting size and bounds and other attributes to no avail.
EDIT: Here's a demonstration of my issue. As you can see (sort of, colors are very similar) the bottom right button is highlighted just by entering its section of the GridlLayout. I only want it highlighted when I'm over the image actual, not the GridLayout section.
I Won't add the MouseListener methods because they just involve switching the displayed image.
public customWidget()
{
this.setLayout(new FlowLayout());
try {
imageDef=ImageIO.read(new File("/home/x101/Desktop/buttonDef.png"));
imageClick=ImageIO.read(new File("/home/x101/Desktop/buttonClick.png"));
imageHover=ImageIO.read(new File("/home/x101/Desktop/buttonHover.png"));
current=imageDef;
} catch (IOException e)
{
e.printStackTrace();
}
this.addMouseListener(this);
}
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(current, 0, 0, current.getWidth(), current.getHeight(), null);
}
EDIT: added code section
As an alternative, consider the The Button API, which includes the method setRolloverIcon() "to make the button display the specified icon when the cursor passes over it."
Addendum: For example,
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonIconTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
private static void createAndShowGui() {
String base = "http://download.oracle.com/"
+ "javase/tutorial/uiswing/examples/components/"
+ "RadioButtonDemoProject/src/components/images/";
ImageIcon dog = null;
ImageIcon pig = null;
try {
dog = new ImageIcon(new URL(base + "Dog.gif"));
pig = new ImageIcon(new URL(base + "Pig.gif"));
} catch (MalformedURLException ex) {
ex.printStackTrace(System.err);
return;
}
JFrame frame = new JFrame("Rollover Test");
JPanel panel = new JPanel();
panel.add(new JLabel(dog));
panel.add(new JLabel(pig));
JButton button = new JButton(dog);
button.setRolloverIcon(pig);
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I assume your image contains ONLY 4 'customWidget' objects (in a 2x2 grid).
Your code is working as I would expect. Your MouseListener methods are responding to MouseEvents for 'customWidget' (not the image drawn in 'customWidget'), which is sized to take up 1/4 of the image, so they will respond when it enters the enlarged area. The error is actually in your Test program, because you are allowing the custom button widget to be larger than the image.
If you want a Test program that provides an image similar to yours, you should create a larger grid (say 4x4), and then only place your buttons in every other grid node. Place an empty component into the gaps.
Although I won't answer to your particular question, I hope this helps:
If the components just look wrong maybe you should reuse Swing components and just write a custom Look&Feel or theme.
It would certainly help ensuring the look of the application is consistent and at least you are using the right tool for the task you want to accomplish.
As a sidenote, be aware that Java comes with multiple Look&feels, including Look&Feels made to mimic the native OS theme.
See: http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
How would you make a JComponent (panel, frame, window, etc.) fullscreen, so that it also overlaps everything on the screen including the windows start bar?
I don't want to change the resolution or anything with the graphics device like bitdepth etc, I just want to overlap everything else.
Check out this tutorial describing Java's Full-Screen mode API.
Example code (taken from the tutorial). Note that the code operates on a Window so you would need to embed your JPanel with a Window (e.g. JFrame) in order to do this.
GraphicsDevice myDevice;
Window myWindow;
try {
myDevice.setFullScreenWindow(myWindow);
...
} finally {
myDevice.setFullScreenWindow(null);
}
You can try some of the codes in this page, allowing a container to fill the screen (so it is not a solution for an individual component, but for a set of components within a container like a JFrame)
public class MainWindow extends JFrame
{
public MainWindow()
{
super("Fullscreen");
getContentPane().setPreferredSize( Toolkit.getDefaultToolkit().getScreenSize());
pack();
setResizable(false);
show();
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, getContentPane());
Point l = getLocation();
l.x -= p.x;
l.y -= p.y;
setLocation(l);
}
});
}
...
}
You need to use the following API: http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html
Going full screen isn't as simple as making a large panel, you need to look into the underlying OS graphics. But your JPanel code should translate just fine.
I needed to search a lot, to do the same. Here is completely a working version of it by steps, so that i can find it later also, and use it.
Step 1: create a file called fullscreen.java
Step 2: copy this code and paste it as it is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class fullscreen extends Window
{
private Button button;
public fullscreen()
{
super(new Frame());
button = new Button("Close");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
setLayout(new FlowLayout());
add(button);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0,0,screenSize.width, screenSize.height);
}
public static void main(String[] args)
{
// This will take over your whole screen tested and works in my:
// Fedora 12/13/14
// CentOS 5.0
// if this works for you, in other platforms, please leave a comments which OS it worked.
// happy coding!
new fullscreen().setVisible(true);
}
}
Step 3: compile the code and run
Done.
If I were you I would try to make Java not draw the border of the Jframe, then make it take all the screen.
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class FenNoBorder extends JFrame {
public FenNoBorder () {
setUndecorated(true);
setVisible(true);
GraphicsEnvironment graphicsEnvironment=GraphicsEnvironment.getLocalGraphicsEnvironment();
Rectangle maximumWindowBounds=graphicsEnvironment.getMaximumWindowBounds();
setBounds(maximumWindowBounds);
}
}