I have a JFrame with the JDesktopPane and inside the JDesktopPane, I launch with the constructor a JInternalFrame.
(Its a app like the authentification users, with the textbox user and textbox pass)
I lauch the internal like this:
MyInternalFrame internalF = new MyInternalFrame();
desktopPane.add(internalF);
I try with:
internalF.setVisible(true);
internalF.setSelected(true);
desktopPane.getDesktopManager().activateFrame(internal);
desktopPane.setSelectedFrame(internal);
How I can lauch the JInternalFrame and Its selected by default?
When I run the aplication, internalframe is like in background, Its not selected, Its not focused.
Have a look at the How To Use Internal Frames java tutorial. It gives a nice example and uses the following;
protected void createFrame() {
MyInternalFrame frame = new MyInternalFrame();
frame.setVisible(true);
desktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {}
}
You can make the internal frame visible AFTER the desktop is created and the main frame is visible. In that case the frame will be selected by default.
So, one example of what you can do:
Create main frame
Create desktop
Create internal frame but don't make it visible
Start thread that sets visible to true on the internal frame, but the thread can wait until the desktop is shown
Make the main frame visible
In the thread call internalFrame.setVisible(true) and exit from the thread.
In such case the internal frame will appear on the desktop and it will be selected as you want it.
You might think of other solution without using threads, but writing handlers to the main frame's events. In any case, to make the internal frame visible after it shows, you have to show it AFTER desktop with main frame is displayed.
Here is the example, that you can use:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.HeadlessException;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private Internal internalFrame;
public Main() throws HeadlessException {
super("Internal Frame Test");
setBounds(10, 10, 600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
add(createDesktop(), BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
internalFrame.setVisible(true);
}
});
setVisible(true);
}
private Component createDesktop() {
JDesktopPane d = new JDesktopPane();
internalFrame = new Internal("first");
d.add(internalFrame);
return d;
}
public static class Internal extends JInternalFrame {
private static final long serialVersionUID = 1L;
public Internal(String title) {
super(title);
setBounds(10, 10, 300, 100);
}
}
public static void main(String[] a) {
new Main();
}
}
Related
So I'm making a simple program that jumps from panel to panel and am using an actionlistener Button to make the jump. What kind of method or operation do I use to jump from panel to panel?
I tried to use setVisible(true); under the action listener, but I get just a blanks screen. Tried using setContentPane(differentPanel); but that doesn't work.
ackage Com.conebind.Characters;
import Com.conebind.Tech.TechA16;
import Com.conebind.Overviews.OverviewA16;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Char_A16 extends JFrame {
private JButton combosButton16;
private JButton techButton16;
private JButton overviewButton16;
private JLabel Image16;
private JPanel panel16;
private JPanel panelOverviewA16;
public Char_A16() {
overviewButton16.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
OverviewA16 overview16 = new OverviewA16();
overview16.setVisible(true);
overview16.pack();
overview16.setContentPane(new Char_A16().panelOverviewA16);
}
});
techButton16.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Todo
}
});
}
private void createUIComponents(){
Image16 = new JLabel(new ImageIcon("Android 16.png"));
}
public static void main (String[] args){
JFrame frame = new JFrame("Android 16");
frame.setContentPane(new Char_A16().panel16);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);}
}
The setContentPane(OverviewA16) doesn't work because there's not an object that defines the panel.
Please check this demo project showing how to use CardLayout with IntelliJ IDEA GUI Designer.
The main form has a method that switches between 2 forms displayed inside it:
public void showPanel(String id) {
final CardLayout cl = (CardLayout) cardPanel.getLayout();
cl.show(cardPanel, id);
}
Both forms are added to the card layout during the main form initialization:
FormOne one = new FormOne();
one.setParentForm(this);
cardPanel.add(one.getPanel(), FORM_ONE);
FormTwo two = new FormTwo();
two.setParentForm(this);
cardPanel.add(two.getPanel(), FORM_TWO);
final CardLayout cl = (CardLayout) cardPanel.getLayout();
cl.show(cardPanel, FORM_ONE);
A reference to the main parent form is passed to these 2 forms using setParentForm() method so that FormOne and FormTwo classes can access the showPanel() method of the MainForm.
In a more basic case you may have a button or some other control that switches the forms
located directly on the MainForm, then you may not need passing the main form reference to the subforms, but it can be still useful depending on your app logic.
I have 2 jframes, 1 is kinda like the main menu, i want an attribute to change in the level jframe when a button is pressed so i tried:
SpeelVeld frame = new SpeelVeld();
frame.level = 1;
System.out.println(frame.level);
I used the sout to see what really happens because it wasnt working, but i see that the level goes from 0 to 1 back to 0 and goes on and on, does someone know why and how to fix?
SpeelVeld frame = new SpeelVeld();
frame.setBounds(0,0,519,591);
frame.setLocationRelativeTo(null);
frame.getContentPane().setBackground(Color.WHITE);
frame.setTitle("RWINA");
frame.setVisible(true);
frame.setLevel(1);
this is in the main method of my original GameProject file.
How can i make a jdialog
I have 2 jframes, 1 is kinda like the main menu,
You shouldn't use 2 JFrames for this. The dependent sub-window, likely your main menu window, should in fact be a JDialog, probably a non-modal dialog from the looks of it.
I want an attribute to change in the level jframe when a button is pressed so i tried:
SpeelVeld frame = new SpeelVeld();
frame.level = 1;
System.out.println(frame.level);
and here's a big problem. Understand that in this code, you're creating a new SpeelVeld object, the stress being on the word new. Changing the state of this object will have no effect on the other SeelVeld object that is currently being displayed. Do do that, your second window will need a valid reference to the displayed SeelVeld object. How to do this will depend all on code not yet shown, but often it can be done simply by passing in the displayed SpeelVeld object into the main menu object by use of a constructor parameter or setter method.
For example:
import java.awt.Dialog.ModalityType;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
// JPanel for our main GUI
public class SpeelVeldFoo {
private static void createAndShowGui() {
// JPanel used by the main JFrame
SpeelVeldPanel speelVeldPanel = new SpeelVeldPanel();
// JPanel used by the main menu JDialog. Pass the above into it
MainMenuPanel mainMenuPanel = new MainMenuPanel(speelVeldPanel);
// create your JFrame
JFrame frame = new JFrame("Speel Veld");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(speelVeldPanel); // add the JPanel
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
// create your non-modal JDialog
JDialog menuDialog = new JDialog(frame, "Main Menu", ModalityType.MODELESS);
menuDialog.add(mainMenuPanel); // add the JPanel that holds its "guts"
menuDialog.pack();
menuDialog.setLocationByPlatform(true);
menuDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
#SuppressWarnings("serial")
class SpeelVeldPanel extends JPanel {
private int level = 1; // simple example just has a level int
private JLabel levelLabel = new JLabel("1"); // and displays it in a JLabel
public SpeelVeldPanel() {
add(new JLabel("Level:"));
add(levelLabel);
int ebGap = 50;
setBorder(BorderFactory.createEmptyBorder(ebGap, 2 * ebGap, ebGap, 2 * ebGap));
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
// whenever level is changed, update the display
this.level = level;
levelLabel.setText(String.valueOf(level));
}
}
// class for the JPanel held by the JDialog
#SuppressWarnings("serial")
class MainMenuPanel extends JPanel {
private JSpinner levelSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 5, 1));
private SpeelVeldPanel speelVeldPanel = null; // reference to the main GUI
// note the parameter.... you pass in the displayed main GUI so you can
// change it
public MainMenuPanel(final SpeelVeldPanel speelVeldPanel) {
this.speelVeldPanel = speelVeldPanel; // set the field
// respond when the spinner's data changes
levelSpinner.addChangeListener(new LevelListener());
add(new JLabel("Set the Speel Veld's level:"));
add(levelSpinner);
int ebGap = 10;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
}
private class LevelListener implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
// when the spinner's data changes
int level = (int) levelSpinner.getValue(); // get the data
speelVeldPanel.setLevel(level); // and send it to the main GUI
}
}
}
You'll note that I don't like extending JFrame or JDialog if I can avoid it. My feeling is that one can paint oneself into a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
You probably want the JFrame to be the top-level container, then have a JPanel that holds your menu. The menu could be whatever you want, I'm using a JTextArea. Then, you need a JButton for the JPanel or JFrame that when pressed, changes the text in the JTextArea. Here is an implementation that you could work from. I'm using the ActionEvent as the trigger for when to mess with the JTextArea:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class SimpleSwing {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
JPanel mainMenuPanel = new JPanel();
JTextArea textAttribute = new JTextArea("Original Text");
JButton changeAttributeButton = new JButton("Change Attribute");
changeAttributeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textAttribute.setText("Whatever new text you want");
}
});
mainMenuPanel.add(textAttribute);
mainMenuPanel.add(changeAttributeButton);
mainFrame.add(mainMenuPanel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(500, 500);
mainFrame.setVisible(true);
}
}
I have a frame, on this frame I have a Menu with About MenuItem. When we select it the program opens a new JPanel with texts and with OK button and the enabled status of parent panel is set to false.
And now comes a problem. When we click on OK, then I want to close this About panel, and I want to turn to parent panel, and I want to enable it!
Please tell me, how?
Consider using a WindowListener that reacts to the closing event of the about-dialog. You can add this in your frame or in the constructor of your dialog, just set the variables accordingly.
myDialog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
parentFrame.setEnabled(true);
}
});
If you really only have a switching JPanel, use a ButtonListener.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
frame.setEnabled(true);
}
});
As mentioned in the comments, using a modal JDialog would be a more elegant way of solving the problem of disabling a parent frame while a dialog is active. Here is a tutorial.
Why don't you use simply a JOptionPane (particularly the showMessageDialog method)? You can specify there an Object (for example a JPanel) which will be presented in a modal dialog. Take a look at this sample code I've written for you (I've used a JButton, but it will be the same for JMenuItem):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class AboutDialogDemo extends JFrame {
private final JButton btnAbout = new JButton("About...");
public AboutDialogDemo() {
final JFrame thisFrame = this;
btnAbout.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(thisFrame, new AboutPanel());
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(btnAbout, BorderLayout.PAGE_END);
pack();
}
public static void main(String[] args) {
AboutDialogDemo frame = new AboutDialogDemo();
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class AboutPanel extends JPanel {
private final JLabel lblAbout = new JLabel("Sample about text");
public AboutPanel() {
setLayout(new BorderLayout());
add(lblAbout, BorderLayout.PAGE_START);
}
}
I hope you'll find it useful
I want to remove only minimize button from JFrame
but want maximize and close button in JFrame title bar.
Here I am talking about removing not disabling.
I don't think removing the minimize button is a good thing. But may be you can use the setUndecorated() method to remove the title bar and window edges. And you'll have to add your own close and maximize buttons to perfom those action.
Here is an example :
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
public class Example {
public Example() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);//<---- this will disable the frame decorations
JPanel panel = new JPanel();
panel.add(new JLabel("titlebar"));
//Add button maximize
JButton button_max=new JButton("Maximize");
button_max.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(frame.getExtendedState() == JFrame.NORMAL) {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
} else {
frame.setExtendedState(JFrame.NORMAL);
}
}
});
panel.add(button_max);
//Add button close
JButton button_close = new JButton(new AbstractAction("Close") {
private static final long serialVersionUID = -4901571960357967734L;
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
panel.add(button_close);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new Example();
}
}
Edit :
As #peeskillet states in the comment, even with this method the window still can be resized and draged by the user. The ComponentResizer class allows to do that.
Here is a an SO post which gives a good example to use this class with Jframe.
It's a very big hack, which works only with Synthetica L&F because it provides a painted title bar. Note: this L&F is not free to use. So if you use it you must by a license.
When you use this L&F you can iterate over all component starting from root pane to find an instance of SyntheticaTitlePane. On success you can try to access the field iconifyAction using Reflection Framework and use the method Action.setEnabled(false) on it.
I have no idea how to access the standard title bar because it's native. Probably it's impossible.
In an action (i.e. a method) executed by pressing a button deployed into a JFrame, I want to hide the java app and then to get a screenshot. Finally, once the screenshot is taken, I need to make the JFrame visible.
The method is the following:
public void myButtonPressedAction(){
//Hiding the JFrame
this.setVisible(false);
//Now I use Robot to get a screenshot using another method
//not reported for simplicity
myMethodToGetScreenshot();
//Making the JFrame visible
this.setVisible(true);
}
What happens is that, once visibility is set to false, the app starts to become invisible and immediately I get the screenshot: unfortunately, the screenshot also capture the JFrame while fading out (i.e., it is going to become invisible, the isVisible method returns true, but the JFrame is not completely invisible).
One possible solution is to insert a timer to put a delay between the call to setVisible(false) and the one to myMethodToGetScreenshot(). However, suppose that the system is busy, the delay could be undervalued; on the contrary, a larger delay will make my application slow!
How can I get the exact time instant such that the JFrame has been completely fade out, i.e. it is really invisible?
EDIT
This are initialized in the constructor:
String myPath= ...;//here I have a String that represent a path to a folder.
JPEGImageWriteParam JPEG_PARAMS_BEST_QUALITY = new JPEGImageWriteParam(null);
JPEG_PARAMS_BEST_QUALITY.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
JPEG_PARAMS_BEST_QUALITY.setCompressionQuality(1f);
This is the code for myMethodToGetScreenshot():
public void myMethodToGetScreenshot(){
BufferedImage capture = new Robot().createScreenCapture(screenArea);
ImageWriter writer = writerService.getWriter();
writer.setOutput(new FileImageOutputStream(new File(myPath+"screenshot.jpg")));
writer.write(null, new IIOImage(capture, null, null), JPEG_PARAMS_BEST_QUALITY);
}
This is the screenshot I get. You can see the JFrame fading out...
Then put some delay time. You can use Swing timer.
Here is a small demo:
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ScreenshotDemo {
JFrame frame = new JFrame();
JButton button = new JButton("Catch the screenshot");
Timer timer;
Robot robot;
JLabel label = new JLabel();
public ScreenshotDemo() {
try {
robot = new Robot();
} catch (AWTException e1) {
e1.printStackTrace();
}
// Keeps frame disposed for 3 seconds
timer = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Rectangle size = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());
Image image = robot.createScreenCapture(size);
label.setIcon(new ImageIcon(image));
frame.setVisible(true);
}
});
timer.setRepeats(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
timer.start();
}
});
frame.add(button, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// frame.pack();
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ScreenshotDemo();
}
});
}
}
Basically, you will hide your frame for some time (3 seconds in this demo). While frame is hidden you will take a snapshot.
Instead of setvisible you can use setExtendedState
//Minimize the JFrame
this.setExtendedState(JFrame.ICONIFIED);
//Now I use Robot to get a screenshot using another method
//not reported for simplicity
myMethodToGetScreenshot();
//Restore the JFrame
this.setExtendedState(JFrame.NORMAL);
You have to add a reasonable delay after hiding the frame and before taking the screenshot. Easiest way is to insert a call to robot.delay() before robot.createScreenCapture().
I'd give the ComponentListener a try (assuming this code goes to a member of a JFrame-extending class):
final Container contentPane = getContentPane();
ComponentAdapter componentAdapter = new ComponentAdapter() {
#Override
public void componentHidden(ComponentEvent arg0) {
myMethodToGetScreenshot();
contentPane.removeComponentListener(this);
}
};
contentPane.addComponentListener(componentAdapter);