How to correctly use repaint() and revalidate()? - java

I am new to JPanel and don't quite understand how to reset it. Once a picture is chosen and the user wants to select a new one, I want it to erase the old selected picture and paste the new one. But I'm not sure how. I've seen repaint() and revalidate() used, but I clearly don't know how to use it. So how do I accomplish this?
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.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JRadioButtonMenuItem;
public class Menu extends JFrame {
JMenuBar menuBar;
ButtonGroup pictureGroup, problemsGroup;
BufferedImage picture1img, picture2img, picture3img;
JMenu choiceOfThreePictures, numberOfProblems;
JRadioButtonMenuItem picture1, picture2, picture3, fourProblems, nineProblems, sixteenProblems;
// /Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture1.jpg
// /Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture2.png
// /Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture3.jpg
public Menu() {
// Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
// Create Picture choices on Menu Bar
choiceOfThreePictures = new JMenu("Picture Choices");
// Add Picture choices on Menu Bar
menuBar.add(choiceOfThreePictures);
// Create MenuItems onto Picture choices
pictureGroup = new ButtonGroup();
picture1 = new JRadioButtonMenuItem("Picture 1");
picture2 = new JRadioButtonMenuItem("Picture 2");
picture3 = new JRadioButtonMenuItem("Picture 3");
// Add Picture Choices to Picutre choices menu
choiceOfThreePictures.add(picture1);
pictureGroup.add(picture1);
choiceOfThreePictures.add(picture2);
pictureGroup.add(picture2);
choiceOfThreePictures.add(picture3);
pictureGroup.add(picture3);
// Create Number Of Problems on Menu Bar
numberOfProblems = new JMenu("Number Of Problems");
// Add Number Of problems on Menu Bar
menuBar.add(numberOfProblems);
// Create Menu Items onto Number Of problems
problemsGroup = new ButtonGroup();
fourProblems = new JRadioButtonMenuItem("4");
nineProblems = new JRadioButtonMenuItem("9");
sixteenProblems = new JRadioButtonMenuItem("16");
// Add Number Of problems onto menu
numberOfProblems.add(fourProblems);
problemsGroup.add(fourProblems);
numberOfProblems.add(nineProblems);
problemsGroup.add(nineProblems);
numberOfProblems.add(sixteenProblems);
problemsGroup.add(sixteenProblems);
// Start creating ActionListeners
picture1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Working");
try {
picture1img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture1.jpg"));
getContentPane().add(new JLabel(new ImageIcon(picture1img)));
revalidate();
repaint();
setVisible(true);
} catch (IOException e) {
System.out.println("Couldn't find image.");
}
}
});
picture2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Working");
try {
picture2img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture2.jpg"));
getContentPane().add(new JLabel(new ImageIcon(picture2img)));
revalidate();
repaint();
setVisible(true);
} catch (IOException e) {
System.out.println("Couldn't find image.");
}
}
});
picture3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Working");
try {
picture3img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture3.jpg"));
getContentPane().add(new JLabel(new ImageIcon(picture3img)));
revalidate();
repaint();
setVisible(true);
} catch (IOException e) {
System.out.println("Couldn't find image.");
}
}
});
}
public static void main(String[] args) {
Menu mb = new Menu();
mb.setSize(900, 700);
mb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb.setVisible(true);
}
}

You are using it just fine, you can even remote repaint() call as revalidate is more then enought. The problem is, that you are adding new images but you are not removing previously added images from the contentPane that is why it is not switching.
So if you do
picture3img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture3.jpg"));
getContentPane().removeAll(); // HERE IS IMPORTANT PART
getContentPane().add(new JLabel(new ImageIcon(picture3img)));
revalidate();
It will work
The better approach would be to hold single label as a "image display" and use setIcon(icon) on JLabel insteed of changing whole labels.

Related

Black outline while resizing JFrame

I'm trying to create a smooth animation from one JPanel to the next where the second JPanel is both taller and wider than the first requiring me to rescale the JFrame. To do this I created the following code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
public class Example1 extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
public Example1()
{
initComponents();
}
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // get look and feel based on OS
}
catch (ClassNotFoundException ex) // catch all errors that may occur
{
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
catch (UnsupportedLookAndFeelException ex)
{
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable()
{
public void run() // run the class's constructor, therefore starting
// the UI being built
{
new Example1().setVisible(true);;
}
});
}
private WindowListener exitListener = new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
closingEvent(); // if window closing, go to exit menu
}
};
private void initComponents() // method to build initial view for user for installation
{
// instantiating elements of the GUI
pnlStart = new JPanel();
lblMain = new JLabel();
lblDivider = new JLabel();
lblTextPrompt = new JLabel();
txtAccNum = new JTextField();
btnNext = new JButton();
btnExit = new JButton();
pnlStart.setVisible(true);
add(pnlStart); // adding the panel to the frame
removeWindowListener(exitListener);
addWindowListener(exitListener); // removing before adding the windowlistener, ensures there is only one listener there
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // setting "x" button to do nothing except what exitListener does
setPreferredSize(new Dimension(600, 400)); // setting measurements of jframe
setTitle("Example 1.0"); // setting title on JFrame
setResizable(false); // disabling resizing
setLayout(null); // ensuring I can specify element positions
setBackground(Color.WHITE); // setting background color
lblMain.setText("<html>Please input a number below how many accounts you would like to<br>create: </html>"); // main label that explains what happens, html used for formatting
lblMain.setFont(lblMain.getFont().deriveFont(18.0f)); // changing font size to 16
lblMain.setBounds(27, 60, 540, 100); // setting position and measurements
add(lblMain); // adding label to JFrame
lblTextPrompt.setText("Amount of accounts (1-10):");
lblTextPrompt.setFont(lblMain.getFont().deriveFont(16.0f));
lblTextPrompt.setBounds(166, 190, 198, 18);
lblTextPrompt.setLabelFor(txtAccNum);
add(lblTextPrompt);
txtAccNum.setFont(lblMain.getFont());
txtAccNum.setBounds(374, 187, 50, 26);
txtAccNum.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent e)
{
if (txtAccNum.getText().length() >= 4) // limit textfield to 3 characters
e.consume();
}
});
txtAccNum.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AccDetails(Integer.parseInt(txtAccNum.getText()));
}
});
add(txtAccNum);
lblDivider.setText(""); // ensuring no text in label
lblDivider.setBounds(10, 285, 573, 10); // setting bounds and position of dividing line
lblDivider.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY)); // setting border to label for the dividing
add(lblDivider); // adding it to JFrame
btnNext.setText("Next"); // adding text to button for starting
btnNext.setFont(lblMain.getFont().deriveFont(14.0f)); // setting font size
btnNext.setBounds(495, 315, 80, 35); // positioning start button
btnNext.addActionListener(new ActionListener() // add listener for action to run method
{
public void actionPerformed(ActionEvent evt)
{
AccDetails(Integer.parseInt(txtAccNum.getText()));
}
});
add(btnNext); // adding button to JFrame
btnExit.setText("Exit"); // adding text to button for exiting
btnExit.setFont(btnNext.getFont()); // getting font from start button
btnExit.setBounds(20, 315, 80, 35); // positioning on form
btnExit.addActionListener(new ActionListener() // add listener for action to run method
{
public void actionPerformed(ActionEvent evt)
{
closingEvent(); // running cancel method (same method as hitting the "x" button on the form)
}
});
add(btnExit); // adding button to JFrame
repaint(); // repainting what is displayed if going coming from a different form
revalidate(); // revalidate the elements that will be displayed
pack(); // packaging everything up to use
setLocationRelativeTo(null); // setting form position central
txtAccNum.requestFocusInWindow(); // setting focus on start button when everything is loaded
}
private void AccDetails(int accNum)
{
getContentPane().removeAll();
// instantiating elements of the GUI
pnlAccDetails = new JPanel();
pnlAccDetails.setVisible(true);
add(pnlAccDetails); // adding the panel to the frame
removeWindowListener(exitListener);
addWindowListener(exitListener); // removing before adding the windowlistener, ensures there is only one listener there
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // setting "x" button to do nothing except what exitListener does
while (sizeW != 750 && sizeH != 500)
{
setBackground(Color.BLACK);
Point loc = getLocationOnScreen();
setPreferredSize(new Dimension(sizeW, sizeH));
pnlAccDetails.setPreferredSize(new Dimension(sizeW, sizeH));
repaint();
revalidate();
pack();
sizeW += 1.5;
sizeH += 1;
if (toggle)
{
setLocation((int)(loc.getX() - 0.75), (int)(loc.getY() - 0.5));
toggle = false;
}
else
{
toggle = true;
}
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
setTitle("Example 1.0"); // setting title on JFrame
setResizable(false); // disabling resizing
setLayout(null); // ensuring I can specify element positions
setBackground(Color.WHITE); // setting background color
repaint(); // repainting what is displayed if going coming from a different form
revalidate(); // revalidate the elements that will be displayed
pack(); // packaging everything up to use
setLocationRelativeTo(null); // setting form position central
}
private void closingEvent()
{
if (JOptionPane.showConfirmDialog(null, "<html><center>Are you sure you want to quit?</center></html>", "Quit?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION)
System.exit(0); // output warning that it would cancel installation, if accepted...
else // if not accepted...
{
}
}
// objects used in UI
private JPanel pnlStart;
private JPanel pnlAccDetails;
private JLabel lblMain;
private JLabel lblDivider;
private JLabel lblTextPrompt;
private JTextField txtAccNum;
private JButton btnNext;
private JButton btnExit;
private int sizeW = 600;
private int sizeH = 400;
private boolean toggle = false;
}
While this code does work, during the resizing, the form doesn't retain it's background colour and instead has a black outline with the new measurements. I understand, from the research I've done, this is due to the rendering engine used. Is there anyway to force the render engine to run at each iteration or is there another way of doing this? I've seen the suggestion of using Universal Tween Engine however I couldn't find any resizing examples, especially for the JFrame.
Thanks in advance
As stated in the above comments (by #Sergiy Medvynskyy) blocking the Swing Thread caused it to not render correctly. With using a Swing Timer the animation works smoothly. The code I have used for the solution is:
timer = new Timer (10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
Point loc = getLocationOnScreen();
setPreferredSize(new Dimension(sizeW, sizeH));
pnlAccDetails.setPreferredSize(new Dimension(sizeW, sizeH));
repaint();
revalidate();
pack();
sizeW += 3;
sizeH += 2;
if (toggle)
{
setLocation((int)(loc.getX() - 0.75), (int)(loc.getY() - 0.5));
toggle = false;
}
else
{
toggle = true;
}
if (sizeW == 750 && sizeH == 500)
{
timer.stop();
}
}
});
timer.start();
The above code is used in place of the while loop in my original question. Thanks to Sergiy Medvynskyy for the answer.

RadioButtonMenuItem for java.awt.Menu

In my java AWT (not Swing) application I use java.awt.MenuBar.
And I need use different checkboxes and radiobuttons inside the menu items.
I found java.awt.CheckboxMenuItem and successfully use it.
MenuBar menuBar = new MenuBar();
Menu menuSettings = new Menu("Settings");
Menu menuSettingsMenuGrid = new Menu("Grid");
CheckboxMenuItem menuCheckboxShowGrid = new CheckboxMenuItem("Show");
CheckboxMenuItem menuCheckboxHotspots = new CheckboxMenuItem("Hotspots");
menuSettingsMenuGrid.add(menuCheckboxShowGrid)
menuSettingsMenuGrid.add(menuCheckboxHotspots)
menuSettings.add(menuSettingsMenuGrid);
menuBar.add(menuSettings);
mApplicationFrame.setMenuBar(menuBar);
But I can't find RadioButton. But I really need to use it in awt Menu. What can help me?
But I can't find RadioButton. But I really need to use it in awt Menu. What can help me?
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AWTMenuSample {
public static void main(String args[]) {
Frame frame = new Frame("AWT Menu");
MenuBar bar = new MenuBar();
Menu menu = new Menu("Settings");
ActionListener actionPrinter = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
System.out.println("Action [" + e.getActionCommand() + "] performed!\n");
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
MenuItem menuItemShow = new MenuItem("Show");
menuItemShow.addActionListener(actionPrinter);
menu.add(menuItemShow);
MenuItem menuItemHotspots = new MenuItem("Hotspots");
menuItemHotspots.addActionListener(actionPrinter);
menu.add(menuItemHotspots);
bar.add(menu);
frame.setMenuBar(bar);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
You can write your own algorithm to group actions in ActionListener event.

Insert a GIF image into JFrame and make it visible and invisible on demand

In my application I am extracting data from a project DB. When I do that I want to signal to user that data extraction is in progress. I want to achieve this by making my current frame view.getFrame2() invisible and making view.getFrame3() visible. Frame 3 will have GIF image with frame titled as "Extraction is in progress". I am able to achieve my target but I am not able to view the image in the frame. It's blank.
Below is the code snippet I am using; one class is used for view, another one for controller and yet another one for the model. I also have a main class to initialize all the M-V-C classes. I don't want to complicate the code by creating more classes.
View
My View class:-
/** View**/
package mvc.views;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.*;
public class View {
JFrame frame2, frame3;
JPanel panel3;
Toolkit tk;
Image icon;
Color background;
public View() {
/** processing image view **/
frame3 =new JFrame();
frame3.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame3.setTitle( "Extraction in process...." );
try {
icon = new ImageIcon("C:\\Users\\pc033k\\Desktop\\gears_animated.gif").getImage();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
panel3 = new JPanel();
background = Color.white;
panel3.setOpaque(true);
frame3.setContentPane(panel3);;
frame3.setBounds(100, 100, 400, 400);
frame3.setLocationRelativeTo(null);
frame3.setVisible(false);
/** End of processing image view **/
}
public void paint (Graphics g)
{
panel3.paint(g);
panel3.setBackground(background);
g.drawImage(icon,100,100,500,500,null);
}
}
/** End of View**/
Controller
/** Start Controller**/
package mvc.controllers;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import mvc.models.*;
import mvc.views.*;
public class Controller {
public Model model;
public View view;
public ActionListener myButtonListener;
//public MyDateListener listener;
boolean status, process1;
public String user, password, FN, LN, type;
JTextField text1, text2;
JCalendarCombo cal1, cal2;
public Date date1, date2;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
}
public class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == view.getGetcrmdataButton()){
FN = view.getUserText1().getText();
LN = view.getUserText2().getText();
date1 = view.getCalendar2().getDate();
date2 = view.getCalendar3().getDate();
type = (String) view.getComb1().getSelectedItem();
view.getFrame2().dispose();
view.getFrame3().setVisible(true);
view.getFrame3().repaint();
try {
process1 = model.CRMDataExtract(FN, LN, date1, date2, type);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(process1 == true){
view.getFrame3().setVisible(false);
view.getFrame2().setVisible(true);
JOptionPane.showMessageDialog((Component) (e.getSource()),
"pealse Check the output file for the data");
}
else
{
view.getFrame3().setVisible(false);
view.getFrame2().setVisible(true);
JOptionPane.showMessageDialog((Component) (e.getSource()),
" No Records found or Data Extraction failed!!");
}
}
}
}
I want to achieve this by making my current frame view.getFrame2() invisible and make a view.getFrame3() visible.
Don't be hiding/showing different windows. Users don't like frames disappearing. Instead you can simply display a modal JDialog containing your image on top of your main frame.
Or another approach is to use a GlassPane that paints over top of your main frame. See Disabled Glass Pane for an example of this approach. The existing example doesn't use an Icon, but you can easily change that.
You can use a label for insert the image.
Also I think CardLayout more suitable to your work. Here is some sample code. Consider that the Sample is a JFrame. You will see the Panel changes as you press the "Next" button.
public Sample() {
p = new JPanel();
p.setLayout(new CardLayout());
p1 = new JPanel();
p1.setLayout(new BorderLayout());
p1.add(new JLabel(new ImageIcon(new URL("http://icons.iconarchive.com/icons/chrisbanks2/cold-fusion-hd/128/ace-of-spades-icon.png"))));
p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(new JLabel(new ImageIcon(new URL("http://icons.iconarchive.com/icons/chrisbanks2/cold-fusion-hd/128/ace-of-hearts-icon.png"))));
p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(new JLabel(new ImageIcon(new URL("http://icons.iconarchive.com/icons/chrisbanks2/cold-fusion-hd/128/angrybirds-2-icon.png"))));
p.add(p1, "0");
p.add(p2, "1");
p.add(p3, "2");
b = new Button("Next");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rotator++;
if (rotator == 3) {
rotator = 0;
}
CardLayout layout = (CardLayout) p.getLayout();
layout.show(p, "" + rotator);
System.out.println("Rotator " + rotator);
}
});
add(p, "Center");
add(b, "North");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Java -- How to create a moveable menu [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Does anyone have any example code to make a draggable menu?
I am new to Java and I am trying to find a way to make a menu that is draggable with the mouse. Like a lot of programs have. You can drag the top menu bar around the screen so that you can drop it in other locations. I think that Java can do this as well because I have seen some applications that I think were written in Java do this very same thing.
Question: How do I create a draggable menu in a JFrame in Java?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
public class MyExample extends JFrame {
public MyExample() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit");
eMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0); //exit the system
}
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
setTitle("My Menu");
setSize(300, 100);
setLocationRelativeTo(); //I tried draggable
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MyExample e = new MyExample();
e.setVisible(true);
}
}
I want to be able to drag the menu from the top of the JFrame to another location out of the window and leave it there. I have used Toolbar and that worked good but I was trying to see if this can be done with a menu. If you look at any software application the usually is a grabable area right next tot he File location. This you can click and drag around the area.
ImageIcon icon = new ImageIcon(getClass().getResource("10cd.jpg"));
JMenu file1 = new JMenu("File");
file1.setMnemonic(KeyEvent.VK_F);
JMenu file2 = new JMenu("Open");
file2.setMnemonic(KeyEvent.VK_F);
JMenu file3 = new JMenu("A");
file3.setMnemonic(KeyEvent.VK_F);
JMenu file4 = new JMenu("B");
file4.setMnemonic(KeyEvent.VK_F);
JMenu file5 = new JMenu("C");
file5.setMnemonic(KeyEvent.VK_F);
JMenu file6 = new JMenu("D");
file6.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem1a = new JMenuItem("File 1"/*, icon*///);
/*eMenuItem1a.setMnemonic(KeyEvent.VK_E);
eMenuItem1a.setToolTipText("Exit application");
JMenuItem eMenuItem1b = new JMenuItem("File 2"/*, icon*///);
/* eMenuItem1b.setMnemonic(KeyEvent.VK_E);
eMenuItem1b.setToolTipText("Exit application");
JMenuItem eMenuItem1c = new JMenuItem("File 3"/*, icon*///);
/* eMenuItem1c.setMnemonic(KeyEvent.VK_E);
eMenuItem1c.setToolTipText("Exit application");
JMenuItem eMenuItem2 = new JMenuItem("Exit"/*, icon*///);
/* eMenuItem2.setMnemonic(KeyEvent.VK_E);
eMenuItem2.setToolTipText("Exit application");
JMenuItem eMenuItem3 = new JMenuItem("Exit"/*, icon*///);
/*eMenuItem3.setMnemonic(KeyEvent.VK_E);
eMenuItem3.setToolTipText("Exit application");
JMenuItem eMenuItem4 = new JMenuItem("Exit"/*, icon*///);
/*eMenuItem4.setMnemonic(KeyEvent.VK_E);
eMenuItem4.setToolTipText("Exit application");
eMenuItem1a.addActionListener(new myListenerOne());
eMenuItem1b.addActionListener(new myListenerTwo());
eMenuItem1c.addActionListener(new myListenerThree());
eMenuItem2.addActionListener(new myListenerOne());
eMenuItem3.addActionListener(new myListenerTwo());
eMenuItem4.addActionListener(new myListenerThree());
file1.add(eMenuItem1a);
file1.add(eMenuItem1b);
file1.add(eMenuItem1c);
file2.add(eMenuItem2);
file3.add(eMenuItem3);
file4.add(eMenuItem4);
menubar.add(file1);
menubar.add(file2);
menubar.add(file3);
menubar.add(file4);
menubar.add(file5);
menubar.add(file6);
setJMenuBar(menubar);
//Actionlisteners below
class myListenerOne implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 1");
System.exit(0);
}
}
class myListenerTwo implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 2");
System.exit(0);
}
}
class myListenerThree implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 3");
System.exit(0);
}
}
Here is another menu example that I forgot to include this morning. Was sick and just didn't think about it actually. Anyway, what I was wondering was if the menu could be set to a movable menu, so that when you click on it and drag it that it can be moved to any where in the frame. I have seen this done on some java applications I have used but just haven't seen it in a while.
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.net.URL;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ToolBarDemo extends JPanel
implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public ToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other",
"Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP,
"Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other",
"Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Look for the image.
String imgLocation = imageName + ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have "
+ description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Doug's Test ToolBarDemo!!!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ToolBarDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
The following code adds a JToolBar to the frame. I like this because it is draggable but it looks different than a regular menu. I was more interested in if you could set a menu to draggable.
Try using a JToolBar if you don't want to create your own floating window.
http://docs.oracle.com/javase/tutorial/uiswing/components/toolbar.html

Fullscreen freezes after closing JOptionPane

package sample;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class NewClass {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final JFrame frame = new JFrame();
final JDesktopPane d = new JDesktopPane();
frame.setTitle("Frame");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
device.setDisplayMode(new DisplayMode(800, 600, 32, 60));
frame.setVisible(true);
JButton btn = new JButton();
btn.setText("Button");
final JPanel panel = new JPanel();
panel.add(btn);
frame.add(panel);
final JFileChooser chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) {
System.out.println("File selected: " + chooser.getSelectedFile());
chooser.getFocusCycleRootAncestor().setVisible(false);
} else {
chooser.getFocusCycleRootAncestor().setVisible(false);
}
}
});
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showInternalOptionDialog(frame.getContentPane(), chooser, "Browse", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
}
});
}
}
This code looks weird for you, but thats the only way to preserve my full screen using GraphicsDevice. My problem is that, when I click the cancel or open button of the JFileChooser, my screen freezes using this code chooser.getFocusCycleRootAncestor().setVisible(false);. How can I close the JOPtionPane using internal dialog without freezing my screen or closing the whole screen.
you problem is not in
chooser.getFocusCycleRootAncestor().setVisible(false);
if you make these changes, your code will work flawlessly
just remove this part
JOptionPane.showInternalOptionDialog(frame.getContentPane(),chooser, "Browse",JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
and add this code instead
chooser.showOpenDialog(frame);
let me know if you have further concerns
The problem is, the program still thinks that there is a modal dialog open, which is restricting focus to the modal dialog...
Try changing your chooser's actionListener to something like this...
chooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container parent = chooser.getParent();
while (!(parent instanceof JOptionPane)) {
parent = parent.getParent();
}
JOptionPane op = (JOptionPane) parent;
op.setValue("done");
if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) {
System.out.println("File selected: " + chooser.getSelectedFile());
} else {
}
}
});
This basically "tricks" the JOptionPane into thinking that the user has selected a value (which you've actually not provided anything for) and closes the dialog, returning control back to your application

Categories