I am really new for Java. I have question about getting the JInternalFrame . I searched the web and find the example. I modified the example a little bit, adding a close menuitem but it didn't work my code. In the project if I closed the JInternalFrame without select it first, then I have error. I tried to loop through the WindowMenu for getting the selected JcheckboxMenuitem, but it didn't get any components. Would someone tell me what to do.
There is the code:
// This is example is from Kjell Dirdal.
// Referenced from http://www.javaworld.com/javaworld/jw-05-2001/jw-0525-mdi.html
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyVetoException;
import javax.swing.DefaultDesktopManager;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class KjellDirdalNotepad extends JFrame {
private MDIDesktopPane desktop = new MDIDesktopPane();
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem newMenu = new JMenuItem("New");
private JScrollPane scrollPane = new JScrollPane();
private JMenuItem closeMenu=new JMenuItem("Close");
private int index=1;
private WindowMenu wMenu=null;
public KjellDirdalNotepad() {
menuBar.add(fileMenu);
wMenu=new WindowMenu(desktop);
menuBar.add(wMenu);
fileMenu.add(newMenu);
fileMenu.add(closeMenu);
setJMenuBar(menuBar);
setTitle("MDI Test");
scrollPane.getViewport().add(desktop);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
newMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
desktop.add(new TextFrame(String.valueOf(index)));
index=index+1;
}
});
//I added the close menu
closeMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JInternalFrame f=desktop.getSelectedFrame();
if (f==null)
{
for (Component child: wMenu.getComponents()){
if (child instanceof WindowMenu.ChildMenuItem){
JCheckBoxMenuItem item=(JCheckBoxMenuItem) child;
if( item.isSelected()){
DisplayTestMsg(item.getText());
}
}
}
}
else{
f.dispose();
}
}
});
}
public void DisplayTestMsg(String msg){
//custom title, error icon
JTextArea textArea=new JTextArea(msg);
textArea.setColumns(30);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setSize(textArea.getPreferredSize().width, 1);
JOptionPane.showMessageDialog(null,
textArea,
"Test",
JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
KjellDirdalNotepad notepad = new KjellDirdalNotepad();
notepad.setSize(600, 400);
notepad.setVisible(true);
}
}
class TextFrame extends JInternalFrame {
private JTextArea textArea = new JTextArea();
private JScrollPane scrollPane = new JScrollPane();
public TextFrame(String title) {
setSize(200, 300);
setTitle("Edit Text-" + title);
setMaximizable(true);
setIconifiable(true);
setClosable(true);
setResizable(true);
scrollPane.getViewport().add(textArea);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
}
}
/**
* An extension of WDesktopPane that supports often used MDI functionality. This
* class also handles setting scroll bars for when windows move too far to the
* left or bottom, providing the MDIDesktopPane is in a ScrollPane.
*/
class MDIDesktopPane extends JDesktopPane {
private static int FRAME_OFFSET = 20;
private MDIDesktopManager manager;
public MDIDesktopPane() {
manager = new MDIDesktopManager(this);
setDesktopManager(manager);
setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
}
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x, y, w, h);
checkDesktopSize();
}
public Component add(JInternalFrame frame) {
JInternalFrame[] array = getAllFrames();
Point p;
int w;
int h;
Component retval = super.add(frame);
checkDesktopSize();
if (array.length > 0) {
p = array[0].getLocation();
p.x = p.x + FRAME_OFFSET;
p.y = p.y + FRAME_OFFSET;
} else {
p = new Point(0, 0);
}
frame.setLocation(p.x, p.y);
if (frame.isResizable()) {
w = getWidth() - (getWidth() / 3);
h = getHeight() - (getHeight() / 3);
if (w < frame.getMinimumSize().getWidth())
w = (int) frame.getMinimumSize().getWidth();
if (h < frame.getMinimumSize().getHeight())
h = (int) frame.getMinimumSize().getHeight();
frame.setSize(w, h);
}
moveToFront(frame);
frame.setVisible(true);
try {
frame.setSelected(true);
} catch (PropertyVetoException e) {
frame.toBack();
}
return retval;
}
public void remove(Component c) {
super.remove(c);
checkDesktopSize();
}
/**
* Cascade all internal frames
*/
public void cascadeFrames() {
int x = 0;
int y = 0;
JInternalFrame allFrames[] = getAllFrames();
manager.setNormalSize();
int frameHeight = (getBounds().height - 5) - allFrames.length * FRAME_OFFSET;
int frameWidth = (getBounds().width - 5) - allFrames.length * FRAME_OFFSET;
for (int i = allFrames.length - 1; i >= 0; i--) {
allFrames[i].setSize(frameWidth, frameHeight);
allFrames[i].setLocation(x, y);
x = x + FRAME_OFFSET;
y = y + FRAME_OFFSET;
}
}
/**
* Tile all internal frames
*/
public void tileFrames() {
java.awt.Component allFrames[] = getAllFrames();
manager.setNormalSize();
int frameHeight = getBounds().height / allFrames.length;
int y = 0;
for (int i = 0; i < allFrames.length; i++) {
allFrames[i].setSize(getBounds().width, frameHeight);
allFrames[i].setLocation(0, y);
y = y + frameHeight;
}
}
/**
* Sets all component size properties ( maximum, minimum, preferred) to the
* given dimension.
*/
public void setAllSize(Dimension d) {
setMinimumSize(d);
setMaximumSize(d);
setPreferredSize(d);
}
/**
* Sets all component size properties ( maximum, minimum, preferred) to the
* given width and height.
*/
public void setAllSize(int width, int height) {
setAllSize(new Dimension(width, height));
}
private void checkDesktopSize() {
if (getParent() != null && isVisible())
manager.resizeDesktop();
}
}
/**
* Private class used to replace the standard DesktopManager for JDesktopPane.
* Used to provide scrollbar functionality.
*/
class MDIDesktopManager extends DefaultDesktopManager {
private MDIDesktopPane desktop;
public MDIDesktopManager(MDIDesktopPane desktop) {
this.desktop = desktop;
}
public void endResizingFrame(JComponent f) {
super.endResizingFrame(f);
resizeDesktop();
}
public void endDraggingFrame(JComponent f) {
super.endDraggingFrame(f);
resizeDesktop();
}
public void setNormalSize() {
JScrollPane scrollPane = getScrollPane();
int x = 0;
int y = 0;
Insets scrollInsets = getScrollPaneInsets();
if (scrollPane != null) {
Dimension d = scrollPane.getVisibleRect().getSize();
if (scrollPane.getBorder() != null) {
d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, d.getHeight()
- scrollInsets.top - scrollInsets.bottom);
}
d.setSize(d.getWidth() - 20, d.getHeight() - 20);
desktop.setAllSize(x, y);
scrollPane.invalidate();
scrollPane.validate();
}
}
private Insets getScrollPaneInsets() {
JScrollPane scrollPane = getScrollPane();
if (scrollPane == null)
return new Insets(0, 0, 0, 0);
else
return getScrollPane().getBorder().getBorderInsets(scrollPane);
}
private JScrollPane getScrollPane() {
if (desktop.getParent() instanceof JViewport) {
JViewport viewPort = (JViewport) desktop.getParent();
if (viewPort.getParent() instanceof JScrollPane)
return (JScrollPane) viewPort.getParent();
}
return null;
}
protected void resizeDesktop() {
int x = 0;
int y = 0;
JScrollPane scrollPane = getScrollPane();
Insets scrollInsets = getScrollPaneInsets();
if (scrollPane != null) {
JInternalFrame allFrames[] = desktop.getAllFrames();
for (int i = 0; i < allFrames.length; i++) {
if (allFrames[i].getX() + allFrames[i].getWidth() > x) {
x = allFrames[i].getX() + allFrames[i].getWidth();
}
if (allFrames[i].getY() + allFrames[i].getHeight() > y) {
y = allFrames[i].getY() + allFrames[i].getHeight();
}
}
Dimension d = scrollPane.getVisibleRect().getSize();
if (scrollPane.getBorder() != null) {
d.setSize(d.getWidth() - scrollInsets.left - scrollInsets.right, d.getHeight()
- scrollInsets.top - scrollInsets.bottom);
}
if (x <= d.getWidth())
x = ((int) d.getWidth()) - 20;
if (y <= d.getHeight())
y = ((int) d.getHeight()) - 20;
desktop.setAllSize(x, y);
scrollPane.invalidate();
scrollPane.validate();
}
}
}
/**
* Menu component that handles the functionality expected of a standard
* "Windows" menu for MDI applications.
*/
class WindowMenu extends JMenu {
private MDIDesktopPane desktop;
private JMenuItem cascade = new JMenuItem("Cascade");
private JMenuItem tile = new JMenuItem("Tile");
public WindowMenu(MDIDesktopPane desktop) {
this.desktop = desktop;
setText("Window");
cascade.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
WindowMenu.this.desktop.cascadeFrames();
}
});
tile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
WindowMenu.this.desktop.tileFrames();
}
});
addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
removeAll();
}
public void menuSelected(MenuEvent e) {
buildChildMenus();
}
});
}
/* Sets up the children menus depending on the current desktop state */
private void buildChildMenus() {
int i;
ChildMenuItem menu;
JInternalFrame[] array = desktop.getAllFrames();
add(cascade);
add(tile);
if (array.length > 0)
addSeparator();
cascade.setEnabled(array.length > 0);
tile.setEnabled(array.length > 0);
for (i = 0; i < array.length; i++) {
menu = new ChildMenuItem(array[i]);
menu.setState(i == 0);
menu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JInternalFrame frame = ((ChildMenuItem) ae.getSource()).getFrame();
frame.moveToFront();
try {
frame.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
});
menu.setIcon(array[i].getFrameIcon());
add(menu);
}
}
/*
* This JCheckBoxMenuItem descendant is used to track the child frame that
* corresponds to a give menu.
*/
class ChildMenuItem extends JCheckBoxMenuItem {
private JInternalFrame frame;
public ChildMenuItem(JInternalFrame frame) {
super(frame.getTitle());
this.frame = frame;
}
public JInternalFrame getFrame() {
return frame;
}
}
}
If you want to remove the JPanel when a button is pressed, you can call JFrame.remove(panel) such as:
final JFrame frame = new JFrame("test");
final JPanel panel = new JPanel();
//add the panel at the start
frame.add(panel);
// when the buttons clicked
button.addActionListener(new ActionListener() {
#Override
public void ActionPerformed(ActionEvent e) {
frame.remove(panel);
frame.repaint();
};
});
I figured it out. I added the method on Class WindowMenu as belows. This method is called when the close button is click without selected internal frame.
public JInternalFrame getFrontFrame(){
InternalFrame[] array = desktop.getAllFrames();
JInternalFrame f=(JInternalFrame)array[0];
return f;
}
Related
http://pastebin.com/PXLFJjNG
I'm trying to figure out threading and animations so I made this really basic program where you can press buttons to move a rectangle up and down. The problem is that if you keep pressing the UP button till the rectangle reaches the top of the screen there's suddenly an extra blue rectangle.
This problem is kinda hard to explain just run the program and keep pressing UP and when you get to the top there's suddenly 2 rectangles being drawn. Is it a problem with my paint component?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RectangleMovement implements Runnable {
JFrame frame;
MyPanel panel;
private int x = 100;
private int y = 100;
private int playerX = 400;
private int playerY = 350;
private int horizontalGoal = 0;
private int verticalGoal = 0;
public static void main(String[] args) {
new RectangleMovement().go();
}
private void go() {
frame = new JFrame("Worst Game Ever");
panel = new MyPanel();
MyPanel buttonPanel = new MyPanel();
JButton left = new JButton("Left");
JButton right = new JButton("Right");
JButton down = new JButton("Down");
JButton up = new JButton("Up");
left.addActionListener(new LeftButton());
right.addActionListener(new RightButton());
down.addActionListener(new DownButton());
up.addActionListener(new UpButton());
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(left);
buttonPanel.add(down);
buttonPanel.add(up);
buttonPanel.add(right);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.SOUTH, buttonPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Thread player = new Thread(this);
player.start();
animate();
}
private class MyPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
g.setColor(Color.RED);
g.fillRect(x, y, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(playerX, playerY, 10, 10);
}
}
class LeftButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
horizontalGoal = -5;
}
}
class RightButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
horizontalGoal = 5;
}
}
class UpButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
verticalGoal = -5;
}
}
class DownButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
verticalGoal = 5;
}
}
/*
* Animates the player
*/
public void run() {
while (true) {
if (horizontalGoal < 0 && playerX > 0) {
playerX--;
horizontalGoal++;
} else if (horizontalGoal > 0 && playerX + 20 < frame.getWidth()) {
playerX++;
horizontalGoal--;
}
if (verticalGoal < 0 && playerY > 0) {
playerY--;
verticalGoal++;
} else if (verticalGoal > 0 && playerY + 10 < 400) {
playerY++;
verticalGoal--;
}
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (intersects()){
playerX = 400;
playerY = 350;
}
frame.repaint();
}
}
private void animate() {
boolean direction = true;
while (true) {
if (y <= 100) {
direction = true;
} else if (y >= 400) {
direction = false;
}
if (direction) {
y++;
} else {
y--;
}
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.repaint();
}
}
private boolean intersects() {
if (x <= playerX && playerX <= x + 10 && y <= playerY
&& playerY <= y + 10) {
return true;
}
return false;
}
}
Your buttonPanel is the Problem. It is also a MyPanel which uses your own paintComponent method. So if your player should be drawn playerY = 10. It is drawn on your game panel and your buttonPanel.
Change your ButtonPanel from
MyPanel buttonPanel = new MyPanel();
to
Panel buttonPanel = new Panel();
and your probelm is gone :-)
When the program is running, the button is drawn 10X10.
I changed the button 20X20 by Modify Menu.
However, the button is not visible.
Appears when you move the mouse over the button.
Do not be a repaint.
revalidate also not the same.
package com.test;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MenuTest extends JFrame {
private Dimension dimen, dimen1;
private int xpos, ypos;
private JButton[][] btn = null;
private JPanel p;
private GridLayout grid;
private CardLayout card;
private int rownum;
private int colnum;
private int mineLevel;
public MenuTest() {
super("GAME");
p = new JPanel();
grid = new GridLayout();
card = new CardLayout();
createMenu();
starting();
}
private void createMenu() {
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
JMenu filemenu = new JMenu("파일(F)");
filemenu.setMnemonic('F');
JMenuItem startmenu = new JMenuItem("게임 시작(S)");
startmenu.setMnemonic('S');
startmenu.setActionCommand("START");
startmenu.addActionListener(new MenuActionListener());
filemenu.add(startmenu);
JMenuItem minecntmenu = new JMenuItem("변경(M)");
minecntmenu.setMnemonic('M');
minecntmenu.setActionCommand("MODIFY");
minecntmenu.addActionListener(new MenuActionListener());
filemenu.add(minecntmenu);
JMenuItem close = new JMenuItem("닫기(C)");
close.setMnemonic('C');
filemenu.add(close);
bar.add(filemenu); //JMenuBar에 JMenu 부착
//도움말 메뉴 만들기--------------------------------
JMenu helpmenu = new JMenu("도움말(D)");
helpmenu.setMnemonic('D'); //단축키를 Alf + D 로 설정
JMenuItem help = new JMenuItem("Help(H)");
help.setMnemonic('H');
helpmenu.add(help);
bar.add(helpmenu);
}
private class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("START")) {
JOptionPane.showMessageDialog(null, "게임시작", "게임", JOptionPane.YES_NO_OPTION);
} else if (e.getActionCommand().equals("MODIFY")) {
modify();
JOptionPane.showMessageDialog(null, "변경", "게임", JOptionPane.YES_NO_OPTION);
}
}
}
private void modify() {
btn = null;
setRowColnum(20, 20);
MapInit(20);
LayoutSet(400, 500);
}
private void starting() {
setRowColnum(10, 10);
MapInit(10);
LayoutSet(200, 250);
}
private void setRowColnum(int rownum, int colnum) {
this.rownum = rownum;
this.colnum = colnum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MenuTest mt = new MenuTest();
}
public void LayoutSet(int w, int h) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(w, h);
dimen = Toolkit.getDefaultToolkit().getScreenSize();
dimen1 = this.getSize();
xpos = (int) (dimen.getWidth() / 2 - dimen1.getWidth() / 2);
ypos = (int) (dimen.getHeight() / 2 - dimen1.getHeight() / 2);
this.setLocation(xpos, ypos);
this.setVisible(true);
this.setResizable(false);
}
public void MapInit(int minecnt) {
p.removeAll();
setBtn(rownum, colnum);
card = new CardLayout(5, 5);
this.setLayout(card);
grid = new GridLayout(rownum, colnum, 0, 0);
p = new JPanel(grid);
int action_num = 0;
for (int i = 0; i < btn.length; i++) {
for (int j = 0; j < btn[i].length; j++) {
action_num = (i * 10 + j);
btn[i][j] = new JButton();
p.add(btn[i][j]);
}
}
this.repaint();
this.add("View", p);
}
private void setBtn(int row, int col) {
btn = new JButton[row][col];
}
}
When you add/remove components from a visible GUI the basic code is:
panel.remove(...);
panel.add(...);
...
panel.revalidate();
panel.reapint();
After removing/adding all the components you need to do the revalidate() so the layout manager is invoked and all the components are given a size and location. Then the repaint() makes sure the components are painted.
I need to add a label on the right hand side of a JMenuItem, like the labels shown below:
I have an application that uses Ctrl++ and Ctrl+- to zoom into an image. However, the + key by default (without Shift) is the = key. When I try adding accelerators for these menu items, the Ctrl+- shortcut label displays as "Ctrl+Minus" (I would prefer "Ctrl -") and the Ctrl++ shortcut label displays as "Ctrl+Equals" (even worse - in the interest of user experience, I would prefer "Ctrl +"):
menuBar_view_zoomIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, ActionEvent.CTRL_MASK));
I want Ctrl++ to display as "Ctrl +" and Ctrl+- to display as "Ctrl -". How can this be done?
not an answer, you need to search for
paint() to heavy, paintComponent() for lightweight JPopup, JMenu (for custom painting can be switch to isHeavyWeight...)
overlay JLabel into container (few question about JTable by #Guillaume Polet and #Robin)
create own JMenu/JPopup (see my comment to your question)
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.basic.BasicArrowButton;
public class ComboBoxMenuExample extends JFrame {
public ComboBoxMenuExample() {
super("ComboBoxMenu Example");
String[] itemStr = {"name", "Red", "Blue", "number", "255,0,0", "0,0,255",
/*separator*/ "system", "control", "controlHighlight", "controlShadow", "text"};
JMenuItem[] menuItems = new JMenuItem[7];
menuItems[0] = new JMenuItem(itemStr[1]);
menuItems[1] = new JMenuItem(itemStr[2]);
menuItems[2] = new JMenuItem(itemStr[4]);
menuItems[3] = new JMenuItem(itemStr[5]);
menuItems[4] = new JMenuItem(itemStr[8]);
menuItems[5] = new JMenuItem(itemStr[9]);
menuItems[6] = new JMenuItem(itemStr[10]);
JMenu[] menus = new JMenu[4];
menus[0] = new JMenu(itemStr[0]);
menus[1] = new JMenu(itemStr[3]);
menus[2] = new JMenu(itemStr[6]);
menus[3] = new JMenu(itemStr[7]);
menus[0].add(menuItems[0]);
menus[0].add(menuItems[1]);
menus[1].add(menuItems[2]);
menus[1].add(menuItems[3]);
menus[3].add(menuItems[4]);
menus[3].add(menuItems[5]);
menus[2].add(menus[3]);
menus[2].add(menuItems[6]);
JMenu menu = ComboMenuBar.createMenu(menuItems[0].getText());
menu.add(menus[0]);
menu.add(menus[1]);
menu.addSeparator();
menu.add(menus[2]);
ComboMenuBar comboMenu = new ComboMenuBar(menu);
JComboBox combo = new JComboBox();
combo.addItem(itemStr[1]);
combo.addItem(itemStr[2]);
combo.addItem(itemStr[4]);
combo.addItem(itemStr[5]);
combo.addItem(itemStr[8]);
combo.addItem(itemStr[9]);
combo.addItem(itemStr[10]);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(new ComboPanel("Fake ComboBox", comboMenu));
getContentPane().add(new ComboPanel("ComboBox", combo));
}
class ComboPanel extends JPanel {
ComboPanel(String title, JComponent c) {
setLayout(new FlowLayout());
setBorder(new TitledBorder(title));
add(c);
}
}
public static void main(String args[]) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception evt) {
}
ComboBoxMenuExample frame = new ComboBoxMenuExample();
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setSize(370, 100);
frame.setVisible(true);
}
}
class ComboMenuBar extends JMenuBar {
JMenu menu;
Dimension preferredSize;
public ComboMenuBar(JMenu menu) {
this.menu = menu;
Color color = UIManager.getColor("Menu.selectionBackground");
UIManager.put("Menu.selectionBackground", UIManager.getColor("Menu.background"));
UIManager.put("Menu.selectionBackground", color);
menu.updateUI();
MenuItemListener listener = new MenuItemListener();
setListener(menu, listener);
add(menu);
}
class MenuItemListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
menu.setText(item.getText());
menu.requestFocus();
}
}
private void setListener(JMenuItem item, ActionListener listener) {
if (item instanceof JMenu) {
JMenu menu1 = (JMenu) item;
int n = menu1.getItemCount();
for (int i = 0; i < n; i++) {
setListener(menu1.getItem(i), listener);
}
} else if (item != null) { // null means separator
item.addActionListener(listener);
}
}
public String getSelectedItem() {
return menu.getText();
}
#Override
public void setPreferredSize(Dimension size) {
preferredSize = size;
}
#Override
public Dimension getPreferredSize() {
if (preferredSize == null) {
Dimension sd = super.getPreferredSize();
Dimension menuD = getItemSize(menu);
Insets margin = menu.getMargin();
Dimension retD = new Dimension(menuD.width, margin.top
+ margin.bottom + menuD.height);
menu.setPreferredSize(retD);
preferredSize = retD;
}
return preferredSize;
}
private Dimension getItemSize(JMenu menu) {
Dimension d = new Dimension(0, 0);
int n = menu.getItemCount();
for (int i = 0; i < n; i++) {
Dimension itemD;
JMenuItem item = menu.getItem(i);
if (item instanceof JMenu) {
itemD = getItemSize((JMenu) item);
} else if (item != null) {
itemD = item.getPreferredSize();
} else {
itemD = new Dimension(0, 0); // separator
}
d.width = Math.max(d.width, itemD.width);
d.height = Math.max(d.height, itemD.height);
}
return d;
}
public static class ComboMenu extends JMenu {
ArrowIcon iconRenderer;
public ComboMenu(String label) {
super(label);
iconRenderer = new ArrowIcon(SwingConstants.SOUTH, true);
setBorder(new EtchedBorder());
setIcon(new BlankIcon(null, 11));
setHorizontalTextPosition(JButton.LEFT);
setFocusPainted(true);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension d = this.getPreferredSize();
int x = Math.max(0, d.width - iconRenderer.getIconWidth() - 3);
int y = Math.max(0,
(d.height - iconRenderer.getIconHeight()) / 2 - 2);
iconRenderer.paintIcon(this, g, x, y);
}
}
public static JMenu createMenu(String label) {
return new ComboMenu(label);
}
}
class ArrowIcon implements Icon, SwingConstants {
private static final int DEFAULT_SIZE = 11;
//private static final int DEFAULT_SIZE = 5;
private int size;
private int iconSize;
private int direction;
private boolean isEnabled;
private BasicArrowButton iconRenderer;
public ArrowIcon(int direction, boolean isPressedView) {
this(DEFAULT_SIZE, direction, isPressedView);
}
public ArrowIcon(int iconSize, int direction, boolean isEnabled) {
this.size = iconSize / 2;
this.iconSize = iconSize;
this.direction = direction;
this.isEnabled = isEnabled;
iconRenderer = new BasicArrowButton(direction);
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
iconRenderer.paintTriangle(g, x, y, size, direction, isEnabled);
}
#Override
public int getIconWidth() {
//int retCode;
switch (direction) {
case NORTH:
case SOUTH:
return iconSize;
case EAST:
case WEST:
return size;
}
return iconSize;
}
#Override
public int getIconHeight() {
switch (direction) {
case NORTH:
case SOUTH:
return size;
case EAST:
case WEST:
return iconSize;
}
return size;
}
}
class BlankIcon implements Icon {
private Color fillColor;
private int size;
public BlankIcon() {
this(null, 11);
}
public BlankIcon(Color color, int size) {
//UIManager.getColor("control")
//UIManager.getColor("controlShadow")
fillColor = color;
this.size = size;
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
if (fillColor != null) {
g.setColor(fillColor);
g.drawRect(x, y, size - 1, size - 1);
}
}
#Override
public int getIconWidth() {
return size;
}
#Override
public int getIconHeight() {
return size;
}
}
I am trying to make a JPanel slide in from the side using this class i made:
public class AnimationClass {
private int i;
private int y;
private JPanel panel;
private int xTo;
private Timer timer;
private int xFrom;
synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;
panel.setSize(width, height);
timer = new Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
for (int i = xFrom; i > xTo; i--) {
panel.setLocation(i, y);
panel.repaint();
i--;
timer.stop();
timer.setDelay(100);
if (i >= xTo) {
timer.stop();
}
}
timer.stop();
}
});
timer.start();
}
}
Well, i dont know what the problem is. I've tried a lot of different things, but i doesn't seem like I can get it to work.
The timer should be changing the location on each tick, until it is in place, instead, on each tick, you're running through a for-next loop, which is blocking the EDT until the loop finishes, preventing from updating the UI
Update with example
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestAnimatedPane {
public static void main(String[] args) {
new TestAnimatedPane();
}
public TestAnimatedPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel panel;
public TestPane() {
setLayout(null);
panel = new JPanel();
panel.setBackground(Color.RED);
add(panel);
Dimension size = getPreferredSize();
Rectangle from = new Rectangle(size.width, (size.height - 50) / 2, 50, 50);
Rectangle to = new Rectangle((size.width - 50) / 2, (size.height - 50) / 2, 50, 50);
Animate animate = new Animate(panel, from, to);
animate.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public static class Animate {
public static final int RUN_TIME = 2000;
private JPanel panel;
private Rectangle from;
private Rectangle to;
private long startTime;
public Animate(JPanel panel, Rectangle from, Rectangle to) {
this.panel = panel;
this.from = from;
this.to = to;
}
public void start() {
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long duration = System.currentTimeMillis() - startTime;
double progress = (double)duration / (double)RUN_TIME;
if (progress > 1f) {
progress = 1f;
((Timer)e.getSource()).stop();
}
Rectangle target = calculateProgress(from, to, progress);
panel.setBounds(target);
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(0);
startTime = System.currentTimeMillis();
timer.start();
}
}
public static Rectangle calculateProgress(Rectangle startBounds, Rectangle targetBounds, double progress) {
Rectangle bounds = new Rectangle();
if (startBounds != null && targetBounds != null) {
bounds.setLocation(calculateProgress(startBounds.getLocation(), targetBounds.getLocation(), progress));
bounds.setSize(calculateProgress(startBounds.getSize(), targetBounds.getSize(), progress));
}
return bounds;
}
public static Point calculateProgress(Point startPoint, Point targetPoint, double progress) {
Point point = new Point();
if (startPoint != null && targetPoint != null) {
point.x = calculateProgress(startPoint.x, targetPoint.x, progress);
point.y = calculateProgress(startPoint.y, targetPoint.y, progress);
}
return point;
}
public static int calculateProgress(int startValue, int endValue, double fraction) {
int value = 0;
int distance = endValue - startValue;
value = (int)Math.round((double)distance * fraction);
value += startValue;
return value;
}
public static Dimension calculateProgress(Dimension startSize, Dimension targetSize, double progress) {
Dimension size = new Dimension();
if (startSize != null && targetSize != null) {
size.width = calculateProgress(startSize.width, targetSize.width, progress);
size.height = calculateProgress(startSize.height, targetSize.height, progress);
}
return size;
}
}
Update
I should have added this in last night (1 year who didn't want to go to bed, 2 parents that did, say no more...)
Animation is complex topic, especially when you start looking at variable speed (the example is static).
Instead of reinventing the wheel, you should seriously consider taking a look at...
Timing Framework - This is base animation framework, that makes no assumptions about how you might like to use it.
Trident - Similar to the Timing Framework, but also has support for Swing based components (via reflection) build in
Universal Tween Engine
This well-factored example easily admits the variation below. It leverages the enclosed panel's preferred size in a JLayeredPane.
/**
* #see https://stackoverflow.com/a/16322007/230513
* #see https://stackoverflow.com/a/16316345/230513
*/
public class TestPane extends JLayeredPane {
private static final int WIDE = 200;
private static final int HIGH = 5 * WIDE / 8; // ~1/phi
private JPanel panel;
public TestPane() {
panel = new JPanel();
panel.setBackground(Color.RED);
panel.add(new JButton("Test"));
add(panel);
Dimension size = panel.getPreferredSize();
int half = HIGH / 2 - size.height / 2;
Rectangle from = new Rectangle(size);
from.translate(WIDE, half);
Rectangle to = new Rectangle(size);
to.translate(0, half);
panel.setBounds(from);
Animate animate = new Animate(panel, from, to);
animate.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(WIDE, HIGH);
}
}
There are a number of problems in the OP's code. As MadProrammer points, should only be moving one step per timer tick. Here is a simple,tested correction to the OPs code which moves the JPanel one pixel at a time, 25 times a second. Note the comments:
synchronized void slidePanelInFromRight(JPanel panelInput, int xFromInput, int xToInput, int yInput, int width, int height) {
this.panel = panelInput;
this.xFrom = xFromInput;
this.xTo = xToInput;
this.y = yInput;
panel.setSize(width, height);
// timer runs 25 times per second
timer = new Timer(40, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Must 'remember' where we have slid panel to by using instance variable rather than automatic variable
// Only move one step at a time.
// No need to restart timer, it continues to run until stopped
if (xFrom > xTo){
xFrom = xFrom - 1;
panel.setLocation(xFrom, y);
panel.repaint();
} else {
timer.stop();
}
panel.setLocation(xFrom, y);
panel.repaint();
}
});
timer.start();
}
example to slid Anything
package TestingPackage;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ToggleBtn extends JPanel {
JFrame frame;
JPanel panelOut;
JLabel labelOn;
JLabel labelOff;
JButton btn;
int count = 1;
public ToggleBtn() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(500, 300, 300, 300);
frame.setLayout(null);
panelOut = new JPanel(null);
panelOut.setBounds(50, 100, 120, 30);
panelOut.setBackground(Color.gray);
frame.add(panelOut);
btn = new JButton("::");
btn.setBounds(0, 0, 60, 30);
panelOut.add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
startThread();
}
});
labelOn = new JLabel("ON");
labelOn.setBounds(0, 0, 60, 30);
panelOut.add(labelOn);
labelOff = new JLabel("OFF");
labelOff.setBounds(60, 0, 60, 30);
panelOut.add(labelOff);
frame.setVisible(true);
}
public void startThread() {
count++;
new Move().start();
}
public static void main(String[] args) {
new ToggleBtn();
}
class Move extends Thread {
#Override
public void run() {
if (count % 2 == 0) {
System.out.println("if");
for (int i = 0; i <= 60; i++) {
try {
Thread.sleep(3);
} catch (InterruptedException ex) {
Logger.getLogger(ToggleBtn.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setBounds(i, 0, 60, 30);
}
} else {
System.out.println("else");
for (int i = 60; i >= 0; i--) {
try {
Thread.sleep(3);
} catch (InterruptedException ex) {
Logger.getLogger(ToggleBtn.class.getName()).log(Level.SEVERE, null, ex);
}
btn.setBounds(i, 0, 60, 30);
}
}
}
}
}
In Windows 7, and Java 1.7 (or if 1.6, comment-out the two lines indicated), create a NetBeans/Eclipse project named "test" with two classes, Test and DroppableFrame, and paste this code into it. And then run it.
If you run with modal = true, it flickers. If you run with modal = false, it doesn't. What am I doing wrong?
// test.java
package test;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Test implements KeyListener, MouseListener
{
public Test(boolean m_modal)
{
Dimension prefSize;
Insets inset;
Font fontLabel, fontInput, fontButtons;
int buttonCenters, buttonBackoff, buttonWidth, buttonCount, thisButton, buttonTop;
String caption;
JLayeredPane m_pane;
JLabel m_lblBackground;
JScrollPane m_txtInputScroll;
int m_width, m_height, m_actual_width, m_actual_height;
boolean m_singleLineInput = true;
String m_caption = "Sample Modal Input";
m_width = 450;
m_height = m_singleLineInput ? /*single line*/180 : /*multi-line*/250;
m_frame = new DroppableFrame(false);
caption = m_caption;
m_frame.setTitle(caption);
// Compute the actual size we need for our window, so it's properly centered
m_frame.pack();
Insets fi = m_frame.getInsets();
m_actual_width = m_width + fi.left + fi.right;
m_actual_height = m_height + fi.top + fi.bottom;
m_frame.setSize(m_width + fi.left + fi.right,
m_height + fi.top + fi.bottom);
prefSize = new Dimension(m_width + fi.left + fi.right,
m_height + fi.top + fi.bottom);
m_frame.setMinimumSize(prefSize);
m_frame.setPreferredSize(prefSize);
m_frame.setMinimumSize(prefSize);
m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
m_frame.setSize(m_width, m_height);
m_frame.setLocationRelativeTo(null); // Center window
m_frame.setLayout(null); // We handle all redraws
Container c = m_frame.getContentPane();
c.setBackground(Color.WHITE);
c.setForeground(Color.BLACK);
m_pane = new JLayeredPane();
m_pane.setLayout(null);
m_pane.setBounds(0, 0, m_width, m_height);
m_pane.setVisible(true);
m_pane.setBorder(BorderFactory.createEmptyBorder());
c.add(m_pane);
// Set the background image
m_lblBackground = new JLabel();
m_lblBackground.setBounds(0, 0, m_width, m_height);
m_lblBackground.setHorizontalAlignment(JLabel.LEFT);
m_lblBackground.setVerticalAlignment(JLabel.TOP);
m_lblBackground.setVisible(true);
m_lblBackground.setBackground(Color.WHITE);
m_pane.add(m_lblBackground);
m_pane.moveToFront(m_lblBackground);
// Create the fonts
fontLabel = new Font("Calibri", Font.BOLD, 20);
fontInput = new Font("Calibri", Font.BOLD, 14);
fontButtons = fontLabel;
// Create the visible label contents
JLabel m_lblLabel = new JLabel();
m_lblLabel.setBounds(15, 52, 423, 28);
m_lblLabel.setHorizontalAlignment(JLabel.LEFT);
m_lblLabel.setVerticalAlignment(JLabel.CENTER);
m_lblLabel.setFont(fontLabel);
m_lblLabel.setForeground(Color.BLUE);
m_lblLabel.setText("A sample input:");
m_lblLabel.setVisible(true);
m_pane.add(m_lblLabel);
m_pane.moveToFront(m_lblLabel);
// Create the input box
if (m_singleLineInput)
{ // It's a single-line input box
m_txtInputSingleLine = new JTextField();
m_txtInputSingleLine.setBounds(15, 85, 421, 25);
m_txtInputSingleLine.setFont(fontInput);
m_txtInputSingleLine.setText("Initial Value");
m_txtInputSingleLine.setVisible(true);
m_txtInputSingleLine.addKeyListener(this);
m_pane.add(m_txtInputSingleLine);
m_pane.moveToFront(m_txtInputSingleLine);
} else {
m_txtInput = new JTextArea();
m_txtInputScroll = new JScrollPane(m_txtInput);
m_txtInputScroll.setBounds(15, 83, 421, 100);
m_txtInputScroll.setAutoscrolls(true);
m_txtInputScroll.setVisible(true);
m_txtInput.setFont(fontInput);
m_txtInput.setLineWrap(true);
m_txtInput.setWrapStyleWord(true);
m_txtInput.setTabSize(2);
m_txtInput.setText("Initial Value");
m_txtInput.setVisible(true);
m_pane.add(m_txtInputScroll);
m_pane.moveToFront(m_txtInputScroll);
}
// Determine which buttons are specified
buttonCount = 0;
m_buttons = _CANCEL_BUTTON + _OKAY_BUTTON;
if ((m_buttons & _NEXT_BUTTON) != 0)
{
m_btnNext = new JButton("Next");
m_btnNext.setFont(fontButtons);
m_btnNext.addMouseListener(this);
inset = m_btnNext.getInsets();
inset.left = 3;
inset.right = 3;
m_btnNext.setMargin(inset);
m_pane.add(m_btnNext);
m_pane.moveToFront(m_btnNext);
++buttonCount;
}
if ((m_buttons & _CANCEL_BUTTON) != 0)
{
m_btnCancel = new JButton("Cancel");
m_btnCancel.setFont(fontButtons);
m_btnCancel.addMouseListener(this);
inset = m_btnCancel.getInsets();
inset.left = 3;
inset.right = 3;
m_btnCancel.setMargin(inset);
m_pane.add(m_btnCancel);
m_pane.moveToFront(m_btnCancel);
++buttonCount;
}
if ((m_buttons & _ACCEPT_BUTTON) != 0)
{
m_btnAccept = new JButton("Accept");
m_btnAccept.setFont(fontButtons);
m_btnAccept.addMouseListener(this);
inset = m_btnAccept.getInsets();
inset.left = 3;
inset.right = 3;
m_btnAccept.setMargin(inset);
m_pane.add(m_btnAccept);
m_pane.moveToFront(m_btnAccept);
++buttonCount;
}
if ((m_buttons & _OKAY_BUTTON) != 0)
{
m_btnOkay = new JButton("Okay");
m_btnOkay.setFont(fontButtons);
m_btnOkay.addMouseListener(this);
inset = m_btnOkay.getInsets();
inset.left = 3;
inset.right = 3;
m_btnOkay.setMargin(inset);
m_pane.add(m_btnOkay);
m_pane.moveToFront(m_btnOkay);
++buttonCount;
}
// Determine the coordinates for each button
buttonCenters = (m_width / (buttonCount + 1));
buttonWidth = (int)((double)buttonCenters * 0.80);
buttonBackoff = (m_width / (buttonCount + 2)) / 2;
// Position the buttons
thisButton = 1;
buttonTop = m_singleLineInput ? 130 : 200;
if (m_btnNext != null)
{ // Position and make visible this button
m_btnNext.setBounds( + (thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnNext.setVisible(true);
++thisButton;
}
if (m_btnCancel != null)
{ // Position and make visible this button
m_btnCancel.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnCancel.setVisible(true);
++thisButton;
}
if (m_btnAccept!= null)
{ // Position and make visible this button
m_btnAccept.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnAccept.setVisible(true);
++thisButton;
}
if (m_btnOkay != null)
{ // Position and make visible this button
m_btnOkay.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnOkay.setVisible(true);
++thisButton;
}
// The modal code causes some slow component rendering.
// Needs looked at to figure out why
if (m_modal)
{ // Make it a modal window
m_frame.setModal(m_width, m_height, fi, m_pane);
} else {
// Make it a non-modal window
m_frame.setVisible(true);
m_frame.forceWindowToHaveFocus();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
m_frame.dispose();
System.exit(0);
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args)
{
boolean modal = true;
Test t = new Test(modal);
}
private DroppableFrame m_frame;
private int m_buttons;
private JTextField m_txtInputSingleLine;
private JTextArea m_txtInput;
private JButton m_btnNext;
private JButton m_btnCancel;
private JButton m_btnAccept;
private JButton m_btnOkay;
public static final int _NEXT_BUTTON = 1;
public static final int _CANCEL_BUTTON = 2;
public static final int _ACCEPT_BUTTON = 4;
public static final int _OKAY_BUTTON = 8;
public static final int _NEXT_CANCEL = 3;
public static final int _ACCEPT_CANCEL = 6;
public static final int _OKAY_CANCEL = 10;
}
// DroppableFrame.java
package test;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.io.*;
import java.util.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.*;
public class DroppableFrame extends JFrame
implements DropTargetListener,
DragSourceListener,
DragGestureListener,
ComponentListener
{
public DroppableFrame(boolean isResizeable)
{
super("JFrame");
m_dragSource = DragSource.getDefaultDragSource();
m_dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
this.setDropTarget(new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this));
addComponentListener(this);
m_isResizeable = isResizeable;
m_modal = false;
setResizable(isResizeable);
}
/**
* Sets the frame to a modal state
* #param width
* #param height
*/
public void setModal(int width,
int height,
Insets fi,
JLayeredPane m_pan)
{
int i;
Component[] comps;
Component c;
Point p;
m_modal = true;
m_modalDialog = new Dialog((JFrame)null, getTitle(), true);
m_modalDialog.setLayout(null);
m_modalDialog.setResizable(m_isResizeable);
m_modalDialog.setSize(width + fi.left + fi.right, height + fi.top + (fi.bottom * 2));
m_modalDialog.setAlwaysOnTop(true);
m_modalDialog.setLocationRelativeTo(null);
if (m_pan != null)
{ // Add/copy the pane's components
comps = m_pan.getComponents();
if (comps != null)
for (i = 0; i < comps.length; i++)
{ // Add and reposition the component taking into account the insets
c = m_modalDialog.add(comps[i]);
p = c.getLocation();
c.setLocation(p.x + fi.left, p.y + fi.top + fi.bottom);
}
}
m_modalDialog.setVisible(true);
}
#Override
public void paint(Graphics g)
{
Dimension d = getSize();
Dimension m = getMaximumSize();
boolean resize = d.width > m.width || d.height > m.height;
d.width = Math.min(m.width, d.width);
d.height = Math.min(m.height, d.height);
if (resize)
{
Point p = getLocation();
setVisible(false);
setSize(d);
setLocation(p);
setVisible(true);
}
super.paint(g);
}
#Override
public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent){}
#Override
public void dragEnter(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dragExit(DragSourceEvent DragSourceEvent){}
#Override
public void dragOver(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dragEnter (DropTargetDragEvent dropTargetDragEvent)
{
dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
#Override
public void dragExit (DropTargetEvent dropTargetEvent) {}
#Override
public void dragOver (DropTargetDragEvent dropTargetDragEvent) {}
#Override
public void dropActionChanged (DropTargetDragEvent dropTargetDragEvent){}
#Override
public synchronized void drop(DropTargetDropEvent dropTargetDropEvent)
{
try
{
Transferable tr = dropTargetDropEvent.getTransferable();
if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
{
dropTargetDropEvent.acceptDrop (DnDConstants.ACTION_COPY_OR_MOVE);
java.util.List fileList = (java.util.List)tr.getTransferData(DataFlavor.javaFileListFlavor);
Iterator iterator = fileList.iterator();
while (iterator.hasNext())
{
File file = (File)iterator.next();
if (file.getName().toLowerCase().endsWith(".xml"))
{ // Do something with the file here
} else {
System.out.println("Ignored dropped file: " + file.getAbsolutePath());
}
}
dropTargetDropEvent.getDropTargetContext().dropComplete(true);
} else {
dropTargetDropEvent.rejectDrop();
}
} catch (IOException io) {
dropTargetDropEvent.rejectDrop();
} catch (UnsupportedFlavorException ufe) {
dropTargetDropEvent.rejectDrop();
}
}
#Override
public void dragGestureRecognized(DragGestureEvent dragGestureEvent)
{
}
public void setTranslucency(float opaquePercent)
{
try
{
if (System.getProperty("java.version").substring(0,3).compareTo("1.6") <= 0)
{ // Code for translucency works in 1.6, raises exception in 1.7
Class awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
Method mSetWindowOpacity;
mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
if (mSetWindowOpacity != null)
{
if (!m_modal)
mSetWindowOpacity.invoke(null, this, opaquePercent);
}
} else {
// If compiling in 1.6 or earlier, comment-out these next two lines
if (!m_modal)
setOpacity(opaquePercent);
}
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
} catch (ClassNotFoundException ex) {
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
} catch (IllegalComponentStateException ex) {
} catch (Throwable t) {
} finally {
}
}
#Override
public void componentResized(ComponentEvent e)
{
Dimension d = getSize();
Dimension m = getMaximumSize();
boolean resize = d.width > m.width || d.height > m.height;
d.width = Math.min(m.width, d.width);
d.height = Math.min(m.height, d.height);
if (resize)
setSize(d);
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
#Override
public void dispose()
{
if (m_modal)
{
m_modalDialog.setVisible(false);
m_modalDialog = null;
}
super.dispose();
}
public void forceWindowToHaveFocus()
{
Rectangle bounds;
Insets insets;
Robot robot = null;
if (m_modal)
m_modalDialog.setVisible(true);
setVisible(true);
toFront();
bounds = getBounds();
insets = getInsets();
try {
robot = new Robot();
robot.mouseMove(bounds.x + bounds.width / 2, bounds.y + insets.top / 2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (AWTException ex) {
}
}
protected DragSource m_dragSource;
protected boolean m_isResizeable;
protected boolean m_modal;
protected Dialog m_modalDialog;
}
Looks like you're adding Swing components to an AWT Dialog. This will definitely cause problems. Using JDialog seems to remove the flickering.