Below is SSCCE to describe my problem.
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class APanel extends JPanel{
public APanel() {
this.setVisible(true);
this.setBackground(Color.red);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2)
{
}
System.out.println("Child panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PPanel extends JPanel{
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
this.setLayout(new GridLayout(0,1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.setBackground(Color.blue);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Parent panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
How can I do the following:
If e.getClickCount()==1 then the parent MouseListener will active and it will print "parent panel clicked!".
If e.getClickCount()==2 then the children MouseListner will active and print out "child panel clicked!".
Edit1: Closer to the proposed solution.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
Component component = (Component)e.getSource();
component.getParent().dispatchEvent(e);
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("single from child");
}
});
}
In case, a mouseEvent needs to pass through multiplevel of containers, this link might be of interest.
If you elect to interpret double clicks, consider using the user's preferred interval, as suggested here.
Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
I think (as I know) that not is possible redirect Mouse event from child to its parent, just get parent from Component that is under the MouseCursor, or get parent from Component that's received Events from MouseClick
sure maybe someone can help you with that :-), but here is code which you needed for success with that
parent:
import java.awt.*;
import javax.swing.*;
public class PPanel extends JPanel {
private static final long serialVersionUID = 1L;
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
setLayout(new GridLayout(0, 1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
add(panel1);
add(panel2);
add(panel3);
setBackground(Color.blue);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
}
Child:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(400, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("single from child");
}
});
}
Related
With Swing I try to maintain a dynamic list. To show the problem, I have broken down the case to a simple sample and will attach the code here.
The JFrame DynamicDisplaySubPanelMain implements the JPanel DynamicSubPanel2.
This JPanel display the content of a List row by row. At the end an additional row allows to add a String to the list. The JPanel shall then automaically show the longer list and provide a new line to add another String.
Adding Strings works fine - but the changed List is not displayed. Can anyone tell what the reason might be.
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class DynamicSubPanelMain extends JFrame {
private static final long serialVersionUID = 1L;
public DynamicSubPanelMain() {
super("My Sample dynamic List");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 500);
DynamicSubPanel2 myPane = new DynamicSubPanel2();
getContentPane().add(myPane, BorderLayout.CENTER);
}
public static void main(String[] args) throws Exception {
DynamicSubPanelMain menu = new DynamicSubPanelMain();
menu.setVisible(true);
}
}
And here the JPanel:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.brunchboy.util.swing.relativelayout.AttributeConstraint;
import com.brunchboy.util.swing.relativelayout.AttributeType;
import com.brunchboy.util.swing.relativelayout.DependencyManager;
import com.brunchboy.util.swing.relativelayout.RelativeLayout;
import de.gombers.tools.helpers.Tools;
public class DynamicSubPanel2 extends JPanel {
private static final long serialVersionUID = 1L;
static final Logger LOGGER = LoggerFactory.getLogger(Tools.getSimpleClassName());
private RelativeLayout relativeLayout = new RelativeLayout();
private int nextIndex=-1;
private int ARRAY_SIZE=100;
private JButton[] actionJB = new JButton[ARRAY_SIZE];
protected JTextField[] workspaceTF = new JTextField[ARRAY_SIZE];
private List<String> list = new ArrayList<>();
public DynamicSubPanel2() {
nextIndex=-1;
list.add("My first object");
list.add("My second object");
rebuildPanel();
}
private void rebuildPanel() {
relativeLayout = new RelativeLayout();
this.setLayout(relativeLayout);
String thisItem;
String aboveItem=DependencyManager.ROOT_NAME;
String prevItem=DependencyManager.ROOT_NAME;
int linespace= 0;
int boundary = 5;
int gap = 5;
int buttonWidth = 110;
for (String text : list) {
nextIndex++;
actionJB[nextIndex]= new JButton("Edit");
thisItem="editJB"+nextIndex;
actionJB[nextIndex].setActionCommand("Edit");
actionJB[nextIndex].addActionListener(new EditListener(text, nextIndex));
relativeLayout.addConstraint(thisItem, AttributeType.TOP,
new AttributeConstraint(aboveItem, AttributeType.TOP, linespace));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.LEFT, boundary));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(thisItem, AttributeType.LEFT, buttonWidth));
this.add(actionJB[nextIndex], thisItem) ;
prevItem=thisItem;
aboveItem=thisItem;
workspaceTF[nextIndex]= new JTextField(text);
workspaceTF[nextIndex].setEditable(false);
thisItem="workspaceTF"+nextIndex;
workspaceTF[nextIndex].setEditable(false);
relativeLayout.addConstraint(thisItem, AttributeType.BOTTOM,
new AttributeConstraint(prevItem, AttributeType.BOTTOM));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(prevItem, AttributeType.RIGHT, gap));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.RIGHT, -boundary));
this.add(workspaceTF[nextIndex], thisItem) ;
prevItem=thisItem;
linespace= 30;
}
nextIndex++;
actionJB[nextIndex] = new JButton("Add");
thisItem="addJB"+nextIndex;
actionJB[nextIndex].setActionCommand("Add");
actionJB[nextIndex].addActionListener(new AddListener(nextIndex));
relativeLayout.addConstraint(thisItem, AttributeType.TOP,
new AttributeConstraint(aboveItem, AttributeType.TOP, linespace));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.LEFT, boundary));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(thisItem, AttributeType.LEFT, buttonWidth));
this.add(actionJB[nextIndex], thisItem) ;
prevItem=thisItem;
aboveItem=thisItem;
LOGGER.info("{}", list.size());
workspaceTF[nextIndex]= new JTextField(list.size());
thisItem="workspaceTF"+nextIndex;
relativeLayout.addConstraint(thisItem, AttributeType.BOTTOM,
new AttributeConstraint(prevItem, AttributeType.BOTTOM));
relativeLayout.addConstraint(thisItem, AttributeType.LEFT,
new AttributeConstraint(prevItem, AttributeType.RIGHT, gap));
relativeLayout.addConstraint(thisItem, AttributeType.RIGHT,
new AttributeConstraint(DependencyManager.ROOT_NAME, AttributeType.RIGHT, -boundary));
this.add(workspaceTF[nextIndex], thisItem) ;
prevItem=thisItem;
}
public JPanel getPanel() {
return this;
}
class EditListener implements ActionListener {
private String text;
private int tfIndex;
public EditListener(String text, int tfIndex) {
this.text = text;
this.tfIndex = tfIndex;
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Edit")) {
EditWorker worker = new EditWorker(tfIndex);
worker.execute();
}
else if (event.getActionCommand().equals("Save")) {
SaveWorker worker = new SaveWorker(text, tfIndex);
worker.execute();
}
}
}
class EditWorker extends SwingWorker {
private int tfIndex;
public EditWorker(int tfIndex) {
this.tfIndex = tfIndex;
}
public Object doInBackground() throws InterruptedException, IOException {
return null;
}
public void done() {
workspaceTF[tfIndex].setBackground(Color.WHITE);
workspaceTF[tfIndex].setEditable(true);
actionJB[tfIndex].setText("Save");
actionJB[tfIndex].setActionCommand("Save");
}
}
class SaveWorker extends SwingWorker {
private String text;
private int tfIndex;
public SaveWorker(String text, int tfIndex) {
this.text = text;
this.tfIndex = tfIndex;
}
public Object doInBackground() throws InterruptedException, IOException {
list.remove(text);
list.add(workspaceTF[tfIndex].getText());
return null;
}
public void done() {
workspaceTF[tfIndex].setEditable(false);
workspaceTF[tfIndex].setBackground(Color.LIGHT_GRAY);
actionJB[tfIndex].setText("Edit");
actionJB[tfIndex].setActionCommand("Edit");
}
}
class AddListener implements ActionListener {
private int tfIndex;
public AddListener(int tfIndex) {
this.tfIndex = tfIndex;
}
#Override
public void actionPerformed(ActionEvent event) {
AddWorker worker = new AddWorker(tfIndex, this);
worker.execute();
}
}
class AddWorker extends SwingWorker {
private int tfIndex;
private boolean success;
private AddListener listener;
public AddWorker(int tfIndex, AddListener listener) {
this.tfIndex = tfIndex;
this.listener = listener;
}
public Object doInBackground() throws InterruptedException, IOException {
list.add(workspaceTF[tfIndex].getText());
return null;
}
public void done() {
rebuildPanel();
getPanel().repaint();
}
}
}
I'm developing a Java Swing map application, it gets a url and loads maps from Google maps at different zoom levels.
But the address bar in the maps are annoying, I want to get rid of it or reduce it's space.
In my code below, I first tried: Use_iFrame_B=false;
This will get a map with large address bar like this, and zooming isn't working :
Then I tried: Use_iFrame_B=true;
This will show maps with zooming, but has large edges:
So, my questions are :
When Use_iFrame_B=false, how to hide the address bar in the first case and still show an indicator [ red balloon ] on the address ?
How to make zoom work in the above case [ Use_iFrame_B=false ].
If 1 and 2 above are not doable, then I'd prefer to use iFrame which will show a smaller more meaningful address and zooming also works. But it leaves large edges, how to get rid of those edges when Use_iFrame_B=true?
Here are my programs:
import java.awt.*;
import java.io.File;
import java.net.URL;
import javafx.embed.swing.JFXPanel;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.web.*;
import javax.swing.*;
import javax.swing.border.*;
/**
Note using the browser might require setting the properties
- http.proxyHost
- http.proxyPort
e.g. -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080
*/
public class JavaFX_Browser_Panel extends JPanel
{
static int Edge_W=0,Edge_H=0;
private int PANEL_WIDTH_INT=1200,PANEL_HEIGHT_INT=900;
private JFXPanel browserFxPanel;
private Pane browser;
WebView view;
WebEngine eng;
// static String Url,Urls[]=new String[]{"http://www.Yahoo.com","www.Google.com","dell.com","C:/Dir_Fit/Yahoo_Maps_Frame.html","C:/Dir_Broadband_TV/TV.html"};
// static String Url,Urls[]=new String[]{"C:/Dir_Broadband_TV/TV.html"};
// static String Url,Urls[]=new String[]{"http://screen.yahoo.com/cecily-strong-snl-skits/hermes-000000630.html"};
static String Url,Urls[]=new String[]{"https://www.google.com/maps/#33.8470183,-84.3677322,11z"};
public JavaFX_Browser_Panel() { init(); }
public JavaFX_Browser_Panel(int W,int H)
{
PANEL_WIDTH_INT=W+Edge_W;
PANEL_HEIGHT_INT=H+Edge_H;
init();
}
public JavaFX_Browser_Panel(String Url)
{
this.Url=Url;
init();
setURL(Url);
}
void init()
{
FlowLayout FL=new FlowLayout();
FL.setHgap(0);
FL.setVgap(0);
setLayout(FL);
browserFxPanel=new JFXPanel();
// browserFxPanel.setBorder(new EmptyBorder(0,0,0,0));
add(browserFxPanel);
setPreferredSize(new Dimension(PANEL_WIDTH_INT,PANEL_HEIGHT_INT));
Platform.runLater(new Runnable() { public void run() { createScene(); } });
}
public static void Set_Edge(int W,int H)
{
Edge_W=W;
Edge_H=H;
}
public String getURL() { return eng.getLocation(); }
public String goBack()
{
final WebHistory history=eng.getHistory();
ObservableList<WebHistory.Entry> entryList=history.getEntries();
int currentIndex=history.getCurrentIndex();
// Out("currentIndex = "+currentIndex);
// Out(entryList.toString().replace("],","]\n"));
Platform.runLater(new Runnable() { public void run() { history.go(-1); } });
return entryList.get(currentIndex>0?currentIndex-1:currentIndex).getUrl();
}
public String goForward()
{
final WebHistory history=eng.getHistory();
ObservableList<WebHistory.Entry> entryList=history.getEntries();
int currentIndex=history.getCurrentIndex();
// Out("currentIndex = "+currentIndex);
// Out(entryList.toString().replace("],","]\n"));
Platform.runLater(new Runnable() { public void run() { history.go(1); } });
return entryList.get(currentIndex<entryList.size()-1?currentIndex+1:currentIndex).getUrl();
}
public void refresh() { Platform.runLater(new Runnable() { public void run() { eng.reload(); } }); }
public void stop() { Platform.runLater(new Runnable() { public void run() { eng.getLoadWorker().cancel(); } }); }
public void Load_iFrame(final String Url,final int W,final int H)
{
Platform.runLater(new Runnable()
{
public void run()
{
if (new File(Url).exists()) setURL(new File(Url));
else eng.loadContent("<iframe width="+W+" height="+H+" src="+Url+" style=border:0; marginheight=0 marginwidth=0 allowfullscreen></iframe>");
// else eng.loadContent("<iframe width="+W+" height="+H+" src="+Url+" frameborder=0 marginheight=0 marginwidth=0 allowfullscreen></iframe>");
// else eng.loadContent("<iframe width='990' height='915' src="+Url+" frameborder='0' allowfullscreen></iframe>");
}
});
}
public void setURL(final String Url)
{
Platform.runLater(new Runnable()
{
public void run()
{
if (new File(Url).exists()) setURL(new File(Url));
else eng.load((Url.startsWith("http://") || Url.startsWith("https://"))?Url:"http://"+Url);
}
});
}
public void setURL(final URL Url)
{
Platform.runLater(new Runnable()
{
public void run()
{
try { eng.load(Url.toString()); }
catch (Exception e) { e.printStackTrace(); }
}
});
}
public void setURL(final File file)
{
Platform.runLater(new Runnable()
{
public void run()
{
try { eng.load(file.toURI().toURL().toString()); }
catch (Exception e) { e.printStackTrace(); }
}
});
}
private void createScene()
{
browser=createBrowser();
browserFxPanel.setScene(new Scene(browser));
}
private Pane createBrowser()
{
Double widthDouble=new Integer(PANEL_WIDTH_INT).doubleValue();
Double heightDouble=new Integer(PANEL_HEIGHT_INT).doubleValue();
view=new WebView();
view.setMinSize(widthDouble,heightDouble);
view.setPrefSize(widthDouble,heightDouble);
eng=view.getEngine();
GridPane grid=new GridPane();
grid.getChildren().addAll(view);
return grid;
}
public static void out(String message) { System.out.print(message); }
public static void Out(String message) { System.out.println(message); }
public static void main(String[] args)
{
final JavaFX_Browser_Panel demo=new JavaFX_Browser_Panel(Urls[0]);
int i=0;
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
// try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); }
// catch (Exception e) { e.printStackTrace(); }
JFrame frame=new JFrame("JavaFX 2.2 in Swing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(demo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
while (i<Urls.length-1)
{
try
{
demo.setURL(Urls[++i]);
Thread.sleep(2000);
}
catch (Exception e) { e.printStackTrace(); }
}
// demo.goBack();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Map_Maker_2 extends JPanel implements Runnable
{
public static final long serialVersionUID=26362862L;
int W=1600,H=1200,JavaFX_Browser_Edge_W=200,JavaFX_Browser_Edge_H=200,Upper_Left_Button_Panel_W=90;
static Dimension Screen_Size=Toolkit.getDefaultToolkit().getScreenSize();
String Google_Url="http://maps.google.com/maps?q=Address&t=m&z=Zoom",Address="760 West Genesee Street Syracuse NY 13204",Url;
Insets An_Inset=new Insets(0,0,0,0);
JTextArea Upper_Left_TextArea=new JTextArea(Address);
JavaFX_Browser_Panel Left_JavaFX_Browser_Panel,Upper_Right_JavaFX_Browser_Panel,Lower_Right_JavaFX_Browser_Panel;
// boolean Use_iFrame_B=true;
boolean Use_iFrame_B=false;
Thread Empty_JPanel_Thread;
public Map_Maker_2()
{
JavaFX_Browser_Panel.Set_Edge(JavaFX_Browser_Edge_W,JavaFX_Browser_Edge_H);
FlowLayout Fl=new FlowLayout(0,0,0);
setLayout(Fl);
JPanel Left_Panel=new JPanel(Fl);
Left_Panel.setBorder(new EtchedBorder());
Left_Panel.setPreferredSize(new Dimension(W/2,H));
add(Left_Panel);
JPanel Upper_Left_Panel=new JPanel(Fl);
Upper_Left_Panel.setBorder(new EtchedBorder());
Upper_Left_Panel.setPreferredSize(new Dimension(W/2-2,H/4-2));
Left_Panel.add(Upper_Left_Panel);
Upper_Left_TextArea.setFont(new Font("Times New Roman",0,16));
Upper_Left_TextArea.setBorder(new EtchedBorder());
Upper_Left_TextArea.setPreferredSize(new Dimension(W/2-2-Upper_Left_Button_Panel_W-4,H/4-6));
Upper_Left_Panel.add(Upper_Left_TextArea);
FlowLayout Button_Panel_Fl=new FlowLayout(0,0,66);
JPanel Upper_Left_Button_Panel=new JPanel(Button_Panel_Fl);
Upper_Left_Button_Panel.setBorder(new EtchedBorder());
Upper_Left_Button_Panel.setPreferredSize(new Dimension(Upper_Left_Button_Panel_W,H/4-6));
Upper_Left_Panel.add(Upper_Left_Button_Panel);
JButton Get_Maps_Button=new JButton("Get Maps");
Get_Maps_Button.setForeground(new Color(0,0,230));
Get_Maps_Button.setFont(new Font("Times New Roman",0,16));
Get_Maps_Button.setMargin(An_Inset);
Get_Maps_Button.setPreferredSize(new Dimension(Upper_Left_Button_Panel_W-5,26));
Get_Maps_Button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Get_Maps(); } });
Upper_Left_Button_Panel.add(Get_Maps_Button);
JButton Print_Button=new JButton("Print");
Print_Button.setForeground(new Color(0,0,230));
Print_Button.setFont(new Font("Times New Roman",0,16));
Print_Button.setMargin(An_Inset);
Print_Button.setPreferredSize(new Dimension(Upper_Left_Button_Panel_W-5,26));
Upper_Left_Button_Panel.add(Print_Button);
JPanel Lower_Left_Panel=new JPanel(Fl);
Lower_Left_Panel.setPreferredSize(new Dimension(W/2-2,H*3/4));
Left_Panel.add(Lower_Left_Panel);
Left_JavaFX_Browser_Panel=new JavaFX_Browser_Panel(W/2-4,H*3/4);
Lower_Left_Panel.add(Left_JavaFX_Browser_Panel);
JPanel Right_Panel=new JPanel(new FlowLayout(0,0,1));
Right_Panel.setBorder(new EtchedBorder());
Right_Panel.setPreferredSize(new Dimension(W/2,H-2));
add(Right_Panel);
JPanel Upper_Right_Outer_Panel=new JPanel(Fl);
Upper_Right_Outer_Panel.setBorder(new EtchedBorder());
Upper_Right_Outer_Panel.setPreferredSize(new Dimension(W/2-4,H/2-4));
Right_Panel.add(Upper_Right_Outer_Panel);
JPanel Upper_Right_Panel=new JPanel(Fl);
Upper_Right_Panel.setPreferredSize(new Dimension(W/2-8,H/2-8));
Upper_Right_Outer_Panel.add(Upper_Right_Panel);
Upper_Right_JavaFX_Browser_Panel=new JavaFX_Browser_Panel(W/2-8,H/2-8);
Upper_Right_Panel.add(Upper_Right_JavaFX_Browser_Panel);
JPanel Lower_Right_Outer_Panel=new JPanel(Fl);
Lower_Right_Outer_Panel.setBorder(new EtchedBorder());
Lower_Right_Outer_Panel.setPreferredSize(new Dimension(W/2-4,H/2-4));
Right_Panel.add(Lower_Right_Outer_Panel);
JPanel Lower_Right_Panel=new JPanel(Fl);
Lower_Right_Panel.setPreferredSize(new Dimension(W/2-8,H/2-8));
Lower_Right_Outer_Panel.add(Lower_Right_Panel);
Lower_Right_JavaFX_Browser_Panel=new JavaFX_Browser_Panel(W/2-8,H/2-8);
Lower_Right_Panel.add(Lower_Right_JavaFX_Browser_Panel);
setPreferredSize(new Dimension(W,H));
Get_Maps();
}
void Get_Maps()
{
Address=Upper_Left_TextArea.getText();
Out(Address);
Url=Google_Url.replace("Address",Address.replace(" ","+"));
Out(Url);
if (Use_iFrame_B)
{
Left_JavaFX_Browser_Panel.Load_iFrame(Url.replace("Zoom","12&output=embed"),785,890);
Upper_Right_JavaFX_Browser_Panel.Load_iFrame(Url.replace("Zoom","16&output=embed"),778,578);
Lower_Right_JavaFX_Browser_Panel.Load_iFrame(Url.replace("Zoom","19&output=embed"),775,575);
}
else
{
Left_JavaFX_Browser_Panel.setURL(Url.replace("Zoom","12")); // This works fine without output=embed in url, but it will show address bar, I want to hide that
Upper_Right_JavaFX_Browser_Panel.setURL(Url.replace("Zoom","16"));
Lower_Right_JavaFX_Browser_Panel.setURL(Url.replace("Zoom","19"));
}
}
public void run()
{
}
public void start()
{
if (Empty_JPanel_Thread==null)
{
Empty_JPanel_Thread=new Thread(this);
Empty_JPanel_Thread.setPriority(Thread.NORM_PRIORITY);
Empty_JPanel_Thread.start();
}
}
public void stop() { if (Empty_JPanel_Thread!=null) Empty_JPanel_Thread=null; }
private static void out(String message) { System.out.print(message); }
private static void Out(String message) { System.out.println(message); }
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
static void Create_And_Show_GUI()
{
final Map_Maker_2 demo=new Map_Maker_2();
JFrame frame=new JFrame("Map Maker 2");
frame.add(demo);
frame.addWindowListener( new WindowAdapter()
{
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { demo.repaint(); }
public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
public void windowIconified(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowOpening(WindowEvent e) { demo.repaint(); }
public void windowOpened(WindowEvent e) { }
public void windowResized(WindowEvent e) { demo.repaint(); }
public void windowStateChanged(WindowEvent e) { demo.repaint(); }
});
frame.pack();
frame.setLocationRelativeTo(null);
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() { Create_And_Show_GUI(); } });
}
}
Alright, I found the answer :
Replace the code in JavaFX_Browser_Panel :
if (new File(Url).exists()) setURL(new File(Url));
else eng.loadContent("<iframe width="+W+" height="+H+" src="+Url+" style=border:0; marginheight=0 marginwidth=0 allowfullscreen></iframe>");
With the following :
String Content="<Html>\n"+
"<style>\n"+
" html,body,div,iframe\n"+
" {\n"+
" height: 100%;\n"+
" overflow: hidden;\n"+
" overflow-x: hidden;\n"+
" overflow-y: hidden;\n"+
" margin: 0; padding: 0;\n"+
" }\n"+
"</style>\n"+
"<iframe width="+W+" height="+H+" src="+Url+" style=border:0></iframe>\n"+
"</Html>";
if (new File(Url).exists()) setURL(new File(Url));
else eng.loadContent(Content);
If I have 1 main class and 2 subclasses
subclass 1: public class JPanel1 extends JPanel {....properly initialized}
subclass 2: public class JTextArea1 extends JTextArea {... properly initialized}
Why can I do jframe1.add(new JPanel1()) but not jframe1.add(new JTextArea1())? for a properly initialized JFrame jframe1 = new JFrame();?
My goal is to output data into both the jpanel and the jtextarea
Here on my side, the issue you raising, is working fine. Do let me know, if you think, this is not what you mean :-)
import java.awt.*;
import javax.swing.*;
public class SwingExample
{
private CustomPanel customPanel;
private CustomTextArea customTextArea;
private void displayGUI()
{
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createLineBorder(
Color.DARK_GRAY, 5));
customPanel = new CustomPanel();
customTextArea = new CustomTextArea();
contentPane.add(customPanel, BorderLayout.CENTER);
contentPane.add(customTextArea, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new SwingExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
private static final int GAP = 5;
public CustomPanel()
{
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(
Color.BLUE, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
}
class CustomTextArea extends JTextArea
{
private static final int GAP = 5;
public CustomTextArea()
{
setBorder(BorderFactory.createLineBorder(
Color.RED, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(100, 30));
}
}
OUTPUT :
Is there a way to implement drop down button in Java, but without implementing JMenuBar?
I need to import a button with popup menu. How can I do that?
As #DavidKroukamp stated, a JPopupMenu should do the trick.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class MenuButton extends JToggleButton {
JPopupMenu popup;
public MenuButton(String name, JPopupMenu menu) {
super(name);
this.popup = menu;
addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
JToggleButton b = MenuButton.this;
if (b.isSelected()) {
popup.show(b, 0, b.getBounds().height);
} else {
popup.setVisible(false);
}
}
});
popup.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
MenuButton.this.setSelected(false);
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {}
});
}
}
The menu is displayed on game startup and works fine, but once in game you can hit escape to bring up the menu again and this will cause the program to minimize. After I unminimize the game I can hit escape again and the menu screen will appear as intended. The return button also works as intended. What is going on here?
EDIT
Here is my SSCCE:
You will just need to add the imports and unimplemented methods for BullsEyePanel. I hope this helps!
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int B_WIDTH = (int) dim.getWidth();
int B_HEIGHT = (int) dim.getHeight();
JFrame f = new JFrame("Children of The Ape");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.pack();
f.setBackground(Color.BLACK);
f.setVisible(true);
f.setResizable(false);
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
// Change to full screen
gd.setFullScreenWindow(f);
if (gd.isDisplayChangeSupported()) {
gd.setDisplayMode(new DisplayMode(B_WIDTH, B_HEIGHT, 32, DisplayMode.REFRESH_RATE_UNKNOWN));
}
MenuPanel menu = new MenuPanel(f);
f.getContentPane().add(menu);
f.validate();
}
}
class BullsEyePanel extends JPanel implements MouseInputListener, ActionListener {
JFrame frame;
public BullsEyePanel(JFrame f) {
frame = f;
addKeyListener(new TAdapter());
setFocusable(true);
setVisible(true);
repaint();
}
private void openMenu() {
frame.getContentPane().add(new MenuPanel(this));
setVisible(false);
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == 27) {
openMenu();
}
}
}
}
class MenuPanel extends JPanel {
JButton btnExit;
JButton btnNewGame;
JFrame f;
BullsEyePanel panel;
MenuPanel(JFrame frame) { //this menu constructor is only called on program startup
f = frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
MenuPanel(BullsEyePanel bullsEyePanel) { //this menu constructor is called when ESC is typed
f = bullsEyePanel.frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
public class exitListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
public class newGameListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
f.getContentPane().add(new BullsEyePanel(f), BorderLayout.CENTER);
}
}
}
Instead of variant constructors, let the menu panel undertake its removal and restoration, as suggested below. See also this related example.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Board().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JFrame f = new JFrame("Children of The Board");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
MenuPanel menu = new MenuPanel(f);
f.add(menu, BorderLayout.NORTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MenuPanel extends JPanel {
private JButton btnExit = new JButton("Exit");
private JButton btnNewGame = new JButton("New Game");
private BullsEyePanel gamePanel;
private JFrame parent;
MenuPanel(JFrame parent) {
this.gamePanel = new BullsEyePanel(this);
this.parent = parent;
this.setBackground(Color.black);
this.setFocusable(true);
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
this.add(btnNewGame);
this.add(btnExit);
this.setVisible(true);
}
public void restore() {
parent.remove(gamePanel);
parent.add(this, BorderLayout.NORTH);
parent.pack();
parent.setLocationRelativeTo(null);
}
private class exitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
private class newGameListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
parent.remove(MenuPanel.this);
parent.add(gamePanel, BorderLayout.CENTER);
parent.pack();
parent.setLocationRelativeTo(null);
gamePanel.requestFocus();
}
}
}
class BullsEyePanel extends JPanel {
private MenuPanel menuPanel;
public BullsEyePanel(MenuPanel menu) {
this.menuPanel = menu;
this.setFocusable(true);
this.addKeyListener(new TAdapter());
this.setPreferredSize(new Dimension(320, 240)); // placeholder
this.setVisible(true);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent code) {
if (code.getKeyCode() == KeyEvent.VK_ESCAPE) {
menuPanel.restore();
}
}
}
}