Making a java swing frame movable and setUndecorated - java

I have created a frame without the title bar, for that I used the setUndecorated(true); method but after that the frame is became unmovable for some reason.
How can I make my frame movable and still hide my title bar?

The following code will create a JFrame without a title bar, which you can still move around:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class FrameDragListenerExample {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
final JFrame frame = new JFrame("Hello");
frame.setUndecorated(true);
frame.setBounds(0, 0, 400, 400);
JPanel contentPane = new JPanel(new BorderLayout());
JLabel label = new JLabel("Click anywhere in the Jframe and drag");
label.setFont(label.getFont().deriveFont(16f));
label.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
contentPane.add(label);
frame.setContentPane(contentPane);
FrameDragListener frameDragListener = new FrameDragListener(frame);
frame.addMouseListener(frameDragListener);
frame.addMouseMotionListener(frameDragListener);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
public static class FrameDragListener extends MouseAdapter {
private final JFrame frame;
private Point mouseDownCompCoords = null;
public FrameDragListener(JFrame frame) {
this.frame = frame;
}
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y);
}
}
}
You can still drag it around by dragging the body of the frame.

Maybe this will help you Moving Window

I encapsulate a extended JFrame class for you, I called it MoveaFrame, you just need to "extend MoveaFrame" in your practice:
Just copy below codes to your project, and extend it, you can make your Frame window draggable!
Extend MoveJFrame like extend a JFrame, you can directly drag your window:
public class ContactUi extends MoveJFrame implements Runnable {
The MoveJFrame class code, just copy it and extend it like extend JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
public class MoveJFrame extends JFrame {
public MoveJFrame() {
this.setUndecorated(true);
FrameDragListener frameDragListener = new FrameDragListener(this);
this.addMouseListener(frameDragListener);
this.addMouseMotionListener(frameDragListener);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) throws IOException {
new MoveJFrame();
}
public static class FrameDragListener extends MouseAdapter {
private final JFrame frame;
private Point mouseDownCompCoords = null;
public FrameDragListener(JFrame frame) {
this.frame = frame;
}
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y);
}
}
}

Related

coordinates specification for panels

How can I specify the coordinates of the following panel, instead of having it aligned to the center.
I have tried a lot and used different layouts, but still couldn't get it to work. Please help me solving this problem. Thanks!
Here is my code..
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Lesson2 extends JFrame {
private static final long serialVersionUID = -198253288329146091L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Lesson2 frame = new Lesson2();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Lesson2() {
contentPane = new JPanel();
setContentPane(contentPane);
JPanel panel = new JPanel() {
private static final long serialVersionUID = -5974584127539186578L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 500);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
};
contentPane.add(panel);
}
}
Here is an example of how it looks now
https://prnt.sc/moe3al
Here is the final code edited using a nulled layout with a set size
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Lesson1 extends JFrame {
private static final long serialVersionUID = -198253288329146091L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Lesson1 frame = new Lesson1();
frame.setSize(1000, 1000);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Lesson1() {
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel() {
private static final long serialVersionUID = -5974584127539186578L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 500);
}
};
panel.setLayout(null);
panel.setSize(500, 500);
contentPane.add(panel);
}
}
All Swing/AWT containers use FlowLayout as the default layout manager, which results in the component being centered. If you want more control, you can use Absolute Positioning by calling contentPane.setLayout(null) and setting the component's coordinates via panel.setBounds(), but be aware that it may not handle window resize elegantly.

I need a JPanel to be displayed when I click on a JToggleButton

I have a JFrame divided in two on one side I have a JPanel that has some JToggleButtons on it. in the other side I need to show the right JPanel when one of the JToggleButtons is clicked. Right now am using only one thread to do this.
here is the JFrame
public class AppFrame extends JFrame{
private JPanel content ;
private JPanel menu;
public AppFrame() {
super("Title");
setLayout(BorderLayout());
//content is gonna hold JPanel1 or JPanel2
content = new JPanel();
menu = new menu();
this.add(menu, BorderLayout.WEST);
this.add(content , BorderLayout.CENTER);
}
public void setContet(JPanel activePanel){
content = activePanel;
this.add(content , BorderLayout.CENTER);
}
}
here is the JPanel holding the JToggleButtons (MenuJPanel)
public class MenuJPanel extends JPanel{
private final LayoutManager innerLayout = new GridLayout(3,1,1,1);
private final JToggleButton button1;
private final JToggleButton button1;
public MenuPanel() {
super();
SwitchHandler sHandler = new SwitchHandler();
this.setLayout(innerLayout);
this.add(button1);
this.add(button2);
button1.addActionListener(sHandler);
button2.addActionListener(sHandler);
}
class SwitchHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1){
button2.setSelected(false);
//at this point I want the frame to display JPanel1
//I tried this
AppFrame frame = (AppFrame)getTopLevelAncestor();
frame.setContet(new JPanel1());
} else {
button1.setSelected(false);
//at this point I want the frame to display JPanel2
//I tried this
AppFrame frame = (AppFrame)getTopLevelAncestor();
frame.setContet(new JPanel2());
}
}
}
Can someone tell me how can I open these panels in the frame when the event is triggered.
thanks
The basic answer is to use a CardLayout, see How to Use CardLayout for more details.
There's so many ways you might be able to do this, but I prefer to use some kind of "navigation controller" which is responsible for actually taking care of the dirty details of making it work, this means if you decide to change the way you switch views, the reset of your code doesn't care, for example...
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public enum Page {
MENU("menu"),
HERE("here"),
THERE("there");
private String pageName;
private Page(String name) {
pageName = name;
}
public String getPageName() {
return pageName;
}
}
public interface Navigator {
public void showPage(Page page);
}
public class TestPane extends JPanel implements Navigator {
private CardLayout cardLayout;
public TestPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
add(new MenuPanel(this), Page.MENU.getPageName());
add(new StuffOverHere(), Page.HERE.getPageName());
add(new StuffOverThere(), Page.THERE.getPageName());
showPage(Page.MENU);
}
#Override
public void showPage(Page page) {
cardLayout.show(this, page.getPageName());
}
}
public class StuffOverHere extends JPanel {
public StuffOverHere() {
setLayout(new GridBagLayout());
JLabel label = new JLabel("Over here");
add(label);
}
}
public class StuffOverThere extends JPanel {
public StuffOverThere() {
setLayout(new GridBagLayout());
JLabel label = new JLabel("Over there");
add(label);
}
}
public class MenuPanel extends JPanel {
private final LayoutManager innerLayout = new GridLayout(3, 1, 1, 1);
private final JToggleButton button1 = new JToggleButton("Stuff over here");
private final JToggleButton button2 = new JToggleButton("Stuff over there");
private Navigator navigator;
public MenuPanel(Navigator navigator) {
super();
SwitchHandler sHandler = new SwitchHandler();
this.setLayout(innerLayout);
this.add(button1);
this.add(button2);
button1.addActionListener(sHandler);
button2.addActionListener(sHandler);
this.navigator = navigator;
}
class SwitchHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
navigator.showPage(Page.HERE);
} else {
navigator.showPage(Page.THERE);
}
}
}
}
}

How to Dispose an opened Jframe from Other

Hi i was wondering how to Dispose a jFrame from another one, cause i want to create a new instance of that class with new values in its textfields, so the First jFrame is this:
public class Frame1 extends javax.swing.JFrame implements ActionListener {
Frame2 f;
public Frame1() {
initComponents();
this.setLocationRelativeTo(null);
}
private void rbtnShowFrame2ActionPerformed(java.awt.event.ActionEvent evt) {
f = new Frame2();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
this.dispose(); //I TRIED TO DISPOSING IT HERE BUT DOESN'T WORK
}
}
So i want in the other jFrame Dispose the jFrame1 only if i trigger the event action performed of a botton, if this doesn't happen i do't want to dispose it, i don't know if i can do it with ActionListener, this is the Second jFrame:
public class Frame2 extends javax.swing.JFrame {
public Frame2() {
initComponents();
this.setLocationRelativeTo(null);
Frame1 f1 = new Frame1();
this.cmdOk.addActionListener(cGUI);
}
private void cmdOkActionPerformed(java.awt.event.ActionEvent evt) {
//Here is where i want to dispose() the other jFrame1
//to create a new instance and pass the value using public static jTextFields
f1.labelNumeroCotizacion.setText(this.labelNumCotizacionEnviar.getText());
f1.setVisible(true);
}
}
Sorry for my Code, i am newbie using OOP! thanks for all guys....
Here is an example of how to dispose a JFrame from another JFrame:
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Demo
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
FrameA one = new FrameA();
FrameB two = new FrameB(one);
one.setVisible(true);
two.setVisible(true);
}
});
}
}
class FrameA extends JFrame
{
private static final long serialVersionUID = 1812279930292019387L;
public FrameA()
{
super("Frame A");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
setResizable(false);
}
}
class FrameB extends JFrame
{
private static final long serialVersionUID = 5126089271972476434L;
public FrameB(final JFrame otherFrame)
{
super("Frame B");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
setLocationRelativeTo(otherFrame);
JButton button = new JButton("Dispose Other");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
otherFrame.dispose();
}
});
add(button);
setResizable(false);
}
}

rectangular component disappears upon resizing the frame

I have a following code ( trying to learn swing and java). I created a ladder using rectangular components using class and placed on the main frame. Everything works okay but if I resize it even slightly, the ShapeManager object (i.e, the ladder) disappears. I don't know what is going on. Any help please.
GUIMain Class:
package mainProg;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
public class GUIMain {
static JPanel mainPanel;
static JButton[] newButtons;
static ShapeManager newShape;
private static class BtnEvtHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
//System.exit(0);
JOptionPane.showMessageDialog( null, "WELCOME" );
}
}
private static JButton[] createButtons() {
JButton[] buttonArray= new JButton[2];
buttonArray[0]=new JButton("OK");
buttonArray[1]=new JButton("MOVE");
BtnEvtHandler okButtonHandler= new BtnEvtHandler();
( buttonArray[0]).addActionListener(okButtonHandler);
return buttonArray;
}
private static ShapeManager createShape(int x) {
ShapeManager newContent=new ShapeManager(x);
return newContent;
}
private static JPanel mainContainer() {
JPanel mainPanel= new JPanel();
mainPanel.setSize(400, 400);
return mainPanel;
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(false);
JFrame frame = new JFrame(" DB ");
mainPanel= mainContainer();
mainPanel.setLayout(new BorderLayout(10, 10));
newButtons= createButtons();
newShape= createShape(20);
newButtons[0].setHorizontalAlignment(0);
mainPanel.add(newButtons[0],BorderLayout.PAGE_START);
newButtons[1].setHorizontalAlignment(0);
mainPanel.add(newButtons[1],BorderLayout.PAGE_END);
newShape.setPreferredSize(new Dimension(400, 400));
mainPanel.add(newShape, BorderLayout.LINE_END);
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocation(500,200);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
ShapeManager Class:
package mainProg;
import javax.swing.JPanel;
import java.awt.*;
#SuppressWarnings("serial")
class ShapeManager extends JPanel {
int rectPos;
ShapeManager(int rectPos) {
setPreferredSize(new Dimension(400,400));
this.rectPos=rectPos;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
while (rectPos<150) {
g.setColor(Color.BLUE);
g.drawRect(rectPos+10, rectPos+10, 100, 10);
g.fillRect(rectPos+10, rectPos+10, 100, 10);
rectPos=rectPos+10;
}
}
}
You never reset rectangle position, so after the first paint it remains above 150. You need to reset it after you exit your while loop.
Try this:
g.setColor(Color.BLUE);
int position = rectPos;
while (position<150) {
position += 10;
g.drawRect(position, position, 100, 10);
g.fillRect(position, position, 100, 10);
}

how to make JDialog inactive

I want to make JDialog-based window inactive, so all controls apeared disabled (in grey color). setEnabled(false) just makes impossible to click any control, even close window. But nothing turns gray. Help please.
EDIT: Here is sample code.
import javax.swing.JButton;
import javax.swing.JDialog;
public class Analyzer extends JDialog{
public Analyzer() {
JButton but = new JButton("test");
setLayout(null);
but.setBounds(10,10,100,100);
add(but);
setSize( 200, 200);
setVisible(true);
setEnabled(false);
}
public static void main(String[] args) {
new Analyzer();
}
}
The two ways I know to do this, one where you disable the components of a dialog recursively, and the second where you disable the entire dialog (including ability to drag the dialog):
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class DisableEg extends JPanel {
public static final String DISABLE_DIALOG_COMPONENTS = "Disable Dialog Components";
public static final String ENABLE_DIALOG_COMPONENTS = "Enable Dialog Components";
public static final String DISABLE_DIALOG = "Disable Dialog";
public static final String ENABLE_DIALOG = "Enable Dialog";
private static final int LOC_SHIFT = 150;
private Analyzer analyzer;
public DisableEg(JFrame frame) {
analyzer = new Analyzer(frame);
analyzer.pack();
analyzer.setLocationRelativeTo(frame);
Point location = analyzer.getLocation();
location = new Point(location.x - LOC_SHIFT, location.y - LOC_SHIFT);
analyzer.setLocation(location);
analyzer.setVisible(true);
add(new JButton(new AbstractAction(DISABLE_DIALOG_COMPONENTS) {
#Override
public void actionPerformed(ActionEvent evt) {
AbstractButton btn = (AbstractButton) evt.getSource();
if (btn.getText().equals(DISABLE_DIALOG_COMPONENTS)) {
btn.setText(ENABLE_DIALOG_COMPONENTS);
analyzer.setComponentEnabled(false);
} else {
btn.setText(DISABLE_DIALOG_COMPONENTS);
analyzer.setComponentEnabled(true);
}
}
}));
add(new JButton(new AbstractAction(DISABLE_DIALOG) {
#Override
public void actionPerformed(ActionEvent evt) {
AbstractButton btn = (AbstractButton) evt.getSource();
if (btn.getText().equals(DISABLE_DIALOG)) {
btn.setText(ENABLE_DIALOG);
analyzer.setEnabled(false);
} else {
btn.setText(DISABLE_DIALOG);
analyzer.setEnabled(true);
}
}
}));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Disable Example");
DisableEg mainPanel = new DisableEg(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class Analyzer extends JDialog {
public Analyzer(JFrame frame) {
super(frame, "Analyzer Dialog", false);
JButton but = new JButton("test");
setLayout(new FlowLayout());
add(but);
setPreferredSize(new Dimension(200, 200));
}
public void setComponentEnabled(boolean enabled) {
setComponentEnabled(enabled, getContentPane());
// !! if you have menus to disable, you may need instead
// setComponentEnabled(enabled, this); // !!
}
private void setComponentEnabled(boolean enabled, Component component) {
component.setEnabled(enabled);
if (component instanceof Container) {
Component[] components = ((Container) component).getComponents();
if (components != null && components.length > 0) {
for (Component heldComponent : components) {
setComponentEnabled(enabled, heldComponent);
}
}
}
}
}
The typical way to do this is to use a glassPane, but Java 7 introduced JLayer that should do the trick too.

Categories

Resources