JTextField is not editable in a JPopupMenu - java

When I add a JtextField in a JPopupMenu, I can't edit the text when the popup is displayed. Anyone know why?
Here's a code example:
public static void main(String[] args) {
JFrame frame = new JFrame();
JPopupMenu popup = new JPopupMenu();
JTextField field = new JTextField("My text");
popup.insert(field, 0);
popup.setVisible(true);
}

Seems to work alright for me:
Check out this example (right click anywhere on the content pane to make the popup visible:
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class Main {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPopupMenu popup = new JPopupMenu();
final JTextField field = new JTextField(20);
field.setText("My text");
popup.insert(field, 0);
popup.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
field.requestFocusInWindow();
field.selectAll();
}
});
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
((JComponent) frame.getContentPane()).setComponentPopupMenu(popup);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main().initUI();
}
});
}
}

to avoiding any speculations
I can't edit the text when the popup is displayed. Anyone know why?
JPopup nested JPopupMenu must has a parent, my code example (reason why is there hardcodes frame.setLocation(150, 100);)
in this form works correctly, JPopup accepting JFrames coordinates
change this code inside Swing Action
from
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
to
popupMenu.setVisible(true);
//popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
then PopupMenuListener firing and events, but JMenuItems aren't repainted too
from code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class PopupSample {
private JPopupMenu popupMenu = new JPopupMenu();
private javax.swing.Timer timer = null;
private JFrame frame = new JFrame("Popup Example");
public PopupSample() {
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Selected: "
+ actionEvent.getActionCommand());
}
};
PopupMenuListener popupMenuListener = new PopupMenuListener() {
#Override
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
System.out.println("Canceled");
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Invisible");
}
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Visible");
}
};
popupMenu.addPopupMenuListener(popupMenuListener);
JSeparator jSeparator = new JSeparator(JSeparator.VERTICAL);
jSeparator.setPreferredSize(new Dimension(2, 100));
jSeparator.setBackground(Color.red);
popupMenu.add(jSeparator);
JMenuItem cutMenuItem = new JMenuItem("Cut");
cutMenuItem.addActionListener(actionListener);
popupMenu.add(cutMenuItem);
cutMenuItem.setBorder(null);
JMenuItem copyMenuItem = new JMenuItem("Copy");
copyMenuItem.addActionListener(actionListener);
popupMenu.add(copyMenuItem);
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.addActionListener(actionListener);
pasteMenuItem.setEnabled(false);
popupMenu.add(pasteMenuItem);
popupMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find");
findMenuItem.addActionListener(actionListener);
popupMenu.add(findMenuItem);
JTextField text = new JTextField("text");
popupMenu.add(text);
MouseListener mouseListener = new JPopupMenuShower(popupMenu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(mouseListener);
frame.setLocation(150, 100);
frame.setSize(350, 250);
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(1000, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
}
});
}
};
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
PopupSample popupSample = new PopupSample();
}
});
}
static class JPopupMenuShower extends MouseAdapter {
private JPopupMenu popup;
public JPopupMenuShower(JPopupMenu popup) {
this.popup = popup;
}
private void showIfPopupTrigger(MouseEvent mouseEvent) {
if (popup.isPopupTrigger(mouseEvent)) {
popup.show(mouseEvent.getComponent(), mouseEvent.getX(),
mouseEvent.getY());
}
}
#Override
public void mousePressed(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
#Override
public void mouseReleased(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
}
}

Related

How can I display a JavaFX Browser in a Java JPanel application?

Good Community I am making an app and I am working with a java browser googlemap and I want to show it in a panel or in another element where it is displayed (JLabel, JPanel, etc).
I made a project in java-> javaAplication-> a form -> with a button. This is the method I am calling on the button.
locate ();
I want to display it in a JPanel not in an FXPanel like this now:
private void locate() {
String a = txtMapaBuscador.getText().replace(" ", "+");
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(1280, 720);
frame.setVisible(true);
final JFXPanel fxpanel = new JFXPanel();
frame.add(fxpanel);
Platform.runLater(new Runnable() {
#Override
public void run() {
WebEngine engine;
WebView wv = new WebView();
engine = wv.getEngine();
fxpanel.setScene(new Scene(wv));
engine.load("https://www.google.com/maps/place/" + a);
}
});
}
This is my friend's code but I can't understand it.
package simpleswingbrowser;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.JFXPanel;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;
import static javafx.concurrent.Worker.State.FAILED;
public class SimpleSwingBrowser extends JFrame {
private final JFXPanel jfxPanel = new JFXPanel();
private WebEngine engine;
private final JPanel panel = new JPanel(new BorderLayout());
private final JLabel lblStatus = new JLabel();
private final JButton btnGo = new JButton("Go");
private final JTextField txtURL = new JTextField();
private final JProgressBar progressBar = new JProgressBar();
public SimpleSwingBrowser() {
super();
initComponents();
}
private void initComponents() {
createScene();
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loadURL(txtURL.getText());
}
};
btnGo.addActionListener(al);
txtURL.addActionListener(al);
progressBar.setPreferredSize(new Dimension(150, 18));
progressBar.setStringPainted(true);
JPanel topBar = new JPanel(new BorderLayout(5, 0));
topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
topBar.add(txtURL, BorderLayout.CENTER);
topBar.add(btnGo, BorderLayout.EAST);
JPanel statusBar = new JPanel(new BorderLayout(5, 0));
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
statusBar.add(lblStatus, BorderLayout.CENTER);
statusBar.add(progressBar, BorderLayout.EAST);
panel.add(topBar, BorderLayout.NORTH);
panel.add(jfxPanel, BorderLayout.CENTER);
panel.add(statusBar, BorderLayout.SOUTH);
getContentPane().add(panel);
setPreferredSize(new Dimension(1024, 600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
private void createScene() {
Platform.runLater(new Runnable() {
#Override
public void run() {
WebView view = new WebView();
engine = view.getEngine();
engine.titleProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SimpleSwingBrowser.this.setTitle(newValue);
}
});
}
});
engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
#Override
public void handle(final WebEvent<String> event) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
lblStatus.setText(event.getData());
}
});
}
});
engine.locationProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> ov, String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
txtURL.setText(newValue);
}
});
}
});
engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progressBar.setValue(newValue.intValue());
}
});
}
});
engine.getLoadWorker()
.exceptionProperty()
.addListener(new ChangeListener<Throwable>() {
#Override
public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
if (engine.getLoadWorker().getState() == FAILED) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(
panel,
(value != null)
? engine.getLocation() + "\n" + value.getMessage()
: engine.getLocation() + "\nUnexpected error.",
"Loading error...",
JOptionPane.ERROR_MESSAGE);
}
});
}
}
});
jfxPanel.setScene(new Scene(view));
}
});
}
public void loadURL(final String url) {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
private static String toURL(String str) {
try {
return new URL(str).toExternalForm();
} catch (MalformedURLException exception) {
return null;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SimpleSwingBrowser browser = new SimpleSwingBrowser();
browser.setVisible(true);
browser.loadURL("http://oracle.com");
}
});
}
}
Add a JPanel pnlViewMap in my frame and put BorderLayout and the map appeared
pnlViewMapa.add(fxpanel,BorderLayout.CENTER);
Platform.runLater(new Runnable() {
#Override
public void run() {
WebEngine engine;
WebView wv = new WebView();
engine = wv.getEngine();
fxpanel.setScene(new Scene(wv));
engine.load("https://www.google.com/maps/place/" + a);
}
});

No up state JButton

I'm trying to change to appearance of my JButton so that the button have no up state.
Currently i have something like this:
And i would like something like this:(comming from NetBeans)
In other words, I only want the image of the button to be visible when the button does not have any kind of focus. But when the user click or roll over it, it should act exactly the same as a regular button.
more examples:
no focus
roll over
click
I use a inner class for my button. It look like this:
private class CustumJButton extends JButton
{
public CustumJButton(Icon icon)
{
super(icon);
int size = 30;
setPreferredSize(new Dimension(size, size));
setFocusable(false);
}
}
Thanks ayoye.
You can achieve this using setBorderPainted() and setContentAreaFilled() methods. Here is the short Demo of what you are looking for. I hope it would give you rough figure to how to achieve your task.:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CustomJButton extends JButton
{
public CustomJButton(String icon)
{
super(icon);
/*int size = 30;
setPreferredSize(new Dimension(size, size));*/
addFocusListener(new ButtonFocusAdapter());
addMouseListener(new ButtonMouseAdapter());
setContentAreaFilled(false);
setBorderPainted(false);
//setFocusable(false);//Don't use this method. This would avoid the focus event on JButton
}
private void decorateButton()
{
setContentAreaFilled(true);
setBorderPainted(true);
}
private void unDecorateButton()
{
setContentAreaFilled(false);
setBorderPainted(false);
}
private class ButtonFocusAdapter extends FocusAdapter
{
#Override
public void focusGained(FocusEvent evt)
{
decorateButton();
}
#Override
public void focusLost(FocusEvent evt)
{
unDecorateButton();
}
}
private class ButtonMouseAdapter extends MouseAdapter
{
#Override
public void mouseEntered(MouseEvent evt)
{
decorateButton();
}
#Override
public void mouseExited(MouseEvent evt)
{
unDecorateButton();
}
}
}
public class ButtonFrame extends JFrame
{
public void createAndShowGUI()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
for (int i = 0; i < 4 ; i++ )
{
CustomJButton cb = new CustomJButton("Button "+i);
c.add(cb);
}
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String st[])
{
SwingUtilities.invokeLater( new Runnable()
{
#Override
public void run()
{
ButtonFrame bf = new ButtonFrame();
bf.createAndShowGUI();
bf.setLocationRelativeTo(null);
}
});
}
}
I guess you need to use these two things to make it work, setBorderPainted(boolean) and setContentAreaFilled(boolean)
buttonObject.setBorderPainted(false);
buttonObject.setContentAreaFilled(false);
as cited in this example for changing appearance of JButton by #mKorbel
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ButtonDemo
{
private JButton demoButton;
private ImageIcon buttonImage;
private void displayGUI()
{
JFrame frame = new JFrame("Button Demo Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
try
{
//buttonImage = new ImageIcon(ImageIO.read(
// getClass().getResource("/image/bulb.gif")));
buttonImage = new ImageIcon(ImageIO.read(
new URL("http://gagandeepbali.uk.to/"
+ "gaganisonline/swing/downloads/"
+ "images/bulb.gif")));
}
catch(Exception e)
{
e.printStackTrace();
}
demoButton = new JButton(buttonImage);
setExceptionalState(demoButton);
demoButton.addMouseListener(new MouseAdapter()
{
#Override
public void mouseEntered(MouseEvent me)
{
setNormalState(demoButton);
}
#Override
public void mouseExited(MouseEvent me)
{
setExceptionalState(demoButton);
}
});
contentPane.add(demoButton);
frame.setContentPane(contentPane);
frame.setSize(300, 100);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void setExceptionalState(JButton button)
{
button.setBorderPainted(false);
button.setContentAreaFilled(false);
}
private void setNormalState(JButton button)
{
button.setBorderPainted(true);
button.setContentAreaFilled(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new ButtonDemo().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
You would set the default state for the button as:
button.setBorderPainted(false);
Then you would need to use a MouseListener:
on mouseEntered you would use
button.setBorderPainted(true);
and on mouse exited you would use
button.setBorderPainted(false);
You should check out the skinnable "Synth Look and Feel", but also be aware that Swing will be deprecated and replaced by JavaFX in the long run. If you are building a new application, you might want to consider using JavaFX which can be skinned with CSS to achieve the effect you are looking for.

getting right click location from popmenu action event

I have a java program that opens a popup menu when right clicked in a JPanel. When any of the popup menu items are clicked, I want to print the location of the right click that triggered the popupmenu in the terminal. How do I do this? How do I get the location of where the right click happened from within popup action events?
How does the code change if the popup menu is in a JComponent?
Here is the program.
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle("MenuTest");
setSize(300, 200);
Action cutAction = new TestAction("Cut");
Action copyAction = new TestAction("Copy");
Action pasteAction = new TestAction("Paste");
JPopupMenu popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
panel.addMouseListener(new MouseAdapter() {});
}
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
System.out.println("Right click happened at ?"); // How do I get right click location?
}
}
}
Add a mouse listener to pressed events, (clicked events get captured by popup):
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
clickLocation.setSize(e.getX(), e.getY());
}
});
Action cutAction = new TestAction("Cut", clickLocation);
Action copyAction = new TestAction("Copy", clickLocation);
Action pasteAction = new TestAction("Paste", clickLocation);
Print out the dimension:
private Dimension clickLocation;
public TestAction(String name, Dimension clickLocation) {
super(name);
this.clickLocation = clickLocation;
}
public void actionPerformed(ActionEvent event) {
System.out.println("Right click happened at " + clickLocation);
}
you were on the right track. i personally prefer to show it manually in the MouseAdapter so i can add methods on other mouseevents. for this you probably need to remove the panel.setComponentPopupMenu(popup);
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if (arg0.getButton() == MouseEvent.BUTTON3) { //Button3 is rightclick
popup.show(panel, arg0.getX(), arg0.getY());
}
}
});
Here is the code that I was looking for. Thank you Schippi and Garret for your help.
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle("MenuTest");
setSize(300, 200);
Action cutAction = new TestAction("Cut");
Action copyAction = new TestAction("Copy");
Action pasteAction = new TestAction("Paste");
JPopupMenu popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
clickLocation= e.getPoint();
}
});
}
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
System.out.println("Right click happened at (" + clickLocation.getX()+"," + clickLocation.getY()+ ")");
}
}
private Point2D clickLocation;
}
Or if you don't want to get it from the event.
Point mousepospoint=null;
if((mousepospoint=componentname.getMousePosition()) != null){
//mouseposArray[0]=mousepospoint.x;
//mouseposArray[1]=mousepospoint.y;
mousepoints(mousepospoint.x,mousepospoint.y);
}//enif
int[] mouseposArray={0,0};
// requires a function to return it if mouseposArray[] is global
protected int[] mousepoints(int xpo,int ypo){
mouseposArray=new int[2];
mouseposArray[0]=xpo;
mouseposArray[1]=ypo;
return mouseposArray;
}//enmeth

Pressing Enter to Continue

I have a JDialog which has two fields, username and password. I want to make the form like normal ones in which pressing enter will be like pressing continue.
I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.
I have already tried getRootPane().setDefaultButton(myButton);, but only that does not seem to work.
than you have to invoke code for this button with method
JButton#doClick();
but better would be use KeyBindings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Test {
private static final long serialVersionUID = 1L;
private JDialog dialog = new JDialog();
private final JPanel contentPanel = new JPanel();
private Timer timer1;
private JButton killkButton = new JButton("Kill JDialog");
private JButton okButton = new JButton("OK");
public Test() {
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel buttonPane = new JPanel();
okButton.setActionCommand("OK");
buttonPane.add(okButton);
killkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
killkButton.setActionCommand("Kill JDialog");
buttonPane.add(killkButton);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
startTimer();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
dialog.setLayout(new BorderLayout());
dialog.getRootPane().setDefaultButton(okButton);
dialog.add(buttonPane, BorderLayout.SOUTH);
dialog.add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setLocation(100, 100);
dialog.setVisible(true);
setKeyBindings();
}
private void setKeyBindings() {
okButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
okButton.getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
startTimer();
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
}
JButton button = ...
JTextField password = ...
ActionListener buttonListener = ...
button.addActionListner(buttonListener);
password.addActionListener(buttonListener);
When enter is pressed in a JTextField, an action event is fired.
You can achieve this by adding an action listener to your textfield, like so.
JTextField field1 = new JTextField();
field1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//here is your method to continue
continue();
}
});

How can I make dual-lines in a JTabbedPane

I'm not sure how much of sense my title does but since you are suppose to have somewhat of a good title this was the best I came up with, so what I actually mean is...
Let's say in theory I've got 10 tabs, and instead of having them all compressed together in 1 line I'd like to split them in 2, so I'd have 5 tabs on the upper side and 5 on the lower.
Example pic:
not clear your question, but there are basic methods for Tabs in the JTabbedPane
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class TabComponentsDemo extends JFrame {
private static final long serialVersionUID = 1L;
private final int tabNumber = 15;
private final JTabbedPane pane = new JTabbedPane();
private JMenuItem tabComponentsItem;
private JMenuItem scrollLayoutItem;
public TabComponentsDemo(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initMenu();
add(pane);
}
public void runTest() {
pane.removeAll();
for (int i = 0; i < tabNumber; i++) {
String title = "Tab " + i;
pane.add(title, new JLabel(title));
//initTabComponent(i);
}
tabComponentsItem.setSelected(true);
pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
scrollLayoutItem.setSelected(false);
setSize(new Dimension(400, 200));
setLocationRelativeTo(null);
setVisible(true);
}
/*private void initTabComponent(int i) {
pane.setTabComponentAt(i, new ButtonTabComponent(pane));
}*/
private void initMenu() {//Setting menu
JMenuBar menuBar = new JMenuBar();//create Options menu
tabComponentsItem = new JCheckBoxMenuItem("Use TabComponents", true);
tabComponentsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
tabComponentsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < pane.getTabCount(); i++) {
if (tabComponentsItem.isSelected()) {
//initTabComponent(i);
} else {
pane.setTabComponentAt(i, null);
}
}
}
});
scrollLayoutItem = new JCheckBoxMenuItem("Set ScrollLayout");
scrollLayoutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_MASK));
scrollLayoutItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane.getTabLayoutPolicy() == JTabbedPane.WRAP_TAB_LAYOUT) {
pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
} else {
pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
}
}
});
JMenuItem resetItem = new JMenuItem("Reset JTabbedPane");
resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.ALT_MASK));
resetItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
runTest();
}
});
JMenu optionsMenu = new JMenu("Options");
optionsMenu.add(tabComponentsItem);
optionsMenu.add(scrollLayoutItem);
optionsMenu.add(resetItem);
menuBar.add(optionsMenu);
setJMenuBar(menuBar);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
new TabComponentsDemo("TabComponentsDemo").runTest();
}
});
}
}
If you want them all displayed in a single row (which I think is what the latter part of your description indicates...), you'll want to set the tab layout policy to JTabbedPane.SCROLL_TAB_LAYOUT.
Here's an example with an image.

Categories