I have a JFrame which looks like a typical chat box. To connect and disconnect from the server I implemented a JPopupMenu and added a MouseListener to the main window.
However the popup menu does not appear.
Various JComponents in the main window:
JTextArea within a JScrollPane
JTextField to enter the message
Send button
JScrollPane and an ArrayList to display the users
The popup is supposed to appear no matter where you right click. Be it on the JTextArea or the field to enter your message.
To which all components do I add listeners and what listener do I add ?
Code
Variables:
private static A_Chat_Client chatClient;
public static String userName = "Anonymous";
//------------------------------------------------------------------------------
public static JFrame mainFrame = new JFrame();
public static JTextArea textArea = new JTextArea(30,30);
public static JScrollPane pane = new JScrollPane(textArea);
public static JTextField message = new JTextField(10);
public static JButton send = new JButton("Send");
public static JPopupMenu popup = new JPopupMenu();
public static JMenuItem connect = new JMenuItem("Connect");
public static JMenuItem disconnect = new JMenuItem("Disconnect");
public static JMenuItem help = new JMenuItem("Help");
public static JList usersOnline = new JList();
public static JScrollPane userPane = new JScrollPane(usersOnline);
Main method
public static void main(String[] args) {
buildMainWindow();
initialize();
addListeners();
popup.show(mainFrame, 0, 0); //forcefully popup
}
addListeners()
public static void addListeners(){
mainFrame.addMouseListener(new MouseHandler());
send.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
actionSend();
}
});
connect.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
actionConnect();
}
});
disconnect.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
actionDisconnect();
}
});
help.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
actionHelp();
}
});
}
class MouseHandler
private static class MouseHandler extends MouseAdapter{
#Override
public void mouseClicked(MouseEvent e){
if(e.isPopupTrigger()){
popup.show(mainFrame, e.getX(), e.getY());
}
}
}
You could attach an AWTEventListener to the main event queue using Toolkit#addAWTEventListener
You would then need to check the type of event your are receiving and check to see if it's popup event.
public class TestGlobalPopup {
public static void main(String[] args) {
new TestGlobalPopup();
}
public TestGlobalPopup() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
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 {
public TestPane() {
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
#Override
public void eventDispatched(AWTEvent event) {
if (event instanceof MouseEvent) {
MouseEvent me = (MouseEvent) event;
if (me.isPopupTrigger()) {
Component component = me.getComponent();
JPopupMenu popup = new JPopupMenu();
popup.add(new JLabel("Clicked on " + component.getClass().getName()));
popup.show(component, me.getX(), me.getY());
}
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Label: "), gbc);
gbc.gridx++;
add(new JTextField(10), gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 2;
add(new JScrollPane(new JTextArea(5, 20)), gbc);
}
}
}
Related
I am working on a tictactoe game using swing library in java; I made the UI using JLayeredpane and added panes containing buttons to represent a 3x3 matrix. the UI works alright but when I go in debug mode of IntelliJ the UI is all messed up. I am a newbie but I tried my best to find what causes the problem but could not find one. the same thing happens when I try to update points but in run time. I simply can't find what causes it.
error
what its supposed look
heres the code for the UIframe:
public class mainFrame {
JFrame frame= new JFrame("TicTackDIE");
JLayeredPane Container= new JLayeredPane();
static ImageIcon X = new ImageIcon("src/Webp.net-resizeimageX.png");
static ImageIcon O= new ImageIcon("src/Webp.net-resizeimageO.png");
static ImageIcon W= new ImageIcon("src/Webp.net-resizeimageBox.png");
static ImageIcon P=new ImageIcon();
static ImageIcon C=new ImageIcon();
static JLabel Points= new JLabel("YOU CPU");
int x=Ppoint;
int y=Cpoint;
JLabel YouPoints=new JLabel(String.valueOf(x));
JLabel CpuPoints=new JLabel(String.valueOf(y));
JButton container=new JButton();
JPanel AP1=new JPanel();
JPanel AP2=new JPanel();
JPanel AP3=new JPanel();
JPanel BP1=new JPanel();
JPanel BP2=new JPanel();
JPanel BP3=new JPanel();
JPanel CP1=new JPanel();
JPanel CP2=new JPanel();
JPanel CP3=new JPanel();
static JButton A1=new JButton();
static JButton A2=new JButton();
static JButton A3=new JButton();
static JButton B1=new JButton();
static JButton B2=new JButton();
static JButton B3=new JButton();
static JButton C1=new JButton();
static JButton C2=new JButton();
static JButton C3=new JButton();
static int Ppoint=0;
static int Cpoint=0;
static boolean A11=true;
static boolean A12=true;
static boolean A13=true;
static boolean B11=true;
static boolean B12=true;
static boolean B13=true;
static boolean C11=true;
static boolean C12=true;
static boolean C13=true;
mainFrame()
{
new BOX();
frame.setBounds(200,200,400,400);
Image icon_image=new ImageIcon("src/FAVPNG_red-skull-bone_kPu7iYJJ.png").getImage();
frame.setIconImage(icon_image);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.add(Container);
Points.setBounds(122,15,200,19);
Points.setFont(new Font("San-Serif",Font.BOLD,17));
Container.add(Points,2);
YouPoints.setBounds(129,42,30,19);
YouPoints.setFont(new Font("San-Serif",Font.BOLD,15));
Container.add(YouPoints,3);
CpuPoints.setBounds(230,42,30,18);
CpuPoints.setFont(new Font("San-Serif",Font.BOLD,15));
Container.add(CpuPoints,4);
container.setIcon(new ImageIcon("src/TicTackToe.png"));
container.setBounds(0,0,390,380);
container.setFocusPainted(false);
container.setBorderPainted(false);
container.setContentAreaFilled(false);
Container.add(container,1);
//////
AP1.setBounds(84,82,67,67);
AP1.setLayout(null);
A1.setBounds(0,0,67,67);
A1.setIcon(W);
A1.setBackground(Color.white);
A1.setFocusPainted(false);
A1.setBorderPainted(false);
A1.setContentAreaFilled(false);
A1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(1,BOX.field[0][0],true);
new CPUmove(A11);
A11=false;
}
});
AP1.add(A1);
Container.add(AP1,0);
AP2.setBounds(160,82,67,67);
AP2.setLayout(null);
A2.setBounds(0,0,67,67);
A2.setIcon(W);
A2.setFocusPainted(false);
A2.setBorderPainted(false);
A2.setContentAreaFilled(false);
A2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(2,BOX.field[0][1],true);
new CPUmove(A12);
A12=false;
}
});
AP2.add(A2);
Container.add(AP2,0);
AP3.setBounds(236,82,67,67);
AP3.setLayout(null);
A3.setBounds(0,0,67,67);
A3.setIcon(W);
A3.setFocusPainted(false);
A3.setBorderPainted(false);
A3.setContentAreaFilled(false);
A3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(3,BOX.field[0][2],true);
new CPUmove(A13);
A13=false;
}
});
AP3.add(A3);
Container.add(AP3,0);
BP1.setBounds(84,158,67,67);
BP1.setLayout(null);
B1.setBounds(0,0,67,67);
B1.setIcon(W);
B1.setFocusPainted(false);
B1.setBorderPainted(false);
B1.setContentAreaFilled(false);
B1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(4,BOX.field[1][0],true);
new CPUmove(B11);
B11=false;
}
});
BP1.add(B1);
Container.add(BP1,0);
BP2.setBounds(160,158,67,67);
BP2.setLayout(null);
B2.setBounds(0,0,67,67);
B2.setIcon(W);
B2.setFocusPainted(false);
B2.setBorderPainted(false);
B2.setContentAreaFilled(false);
B2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(5,BOX.field[1][1],true);
new CPUmove(B12);
B12=false;
}
});
BP2.add(B2);
Container.add(BP2,0);
BP3.setBounds(236,158,67,67);
BP3.setLayout(null);
B3.setBounds(0,0,67,67);
B3.setIcon(W);
B3.setFocusPainted(false);
B3.setBorderPainted(false);
B3.setContentAreaFilled(false);
B3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(6,BOX.field[1][2],true);
new CPUmove(B13);
B13=false;
}
});
BP3.add(B3);
Container.add(BP3,0);
CP1.setBounds(84,233,67,67);
CP1.setLayout(null);
C1.setBounds(0,0,67,67);
C1.setIcon(W);
C1.setFocusPainted(false);
C1.setBorderPainted(false);
C1.setContentAreaFilled(false);
C1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(7,BOX.field[2][0],true);
new CPUmove(C11);
C11=false;
}
});
CP1.add(C1);
Container.add(CP1,0);
CP2.setBounds(160,233,67,67);
CP2.setLayout(null);
C2.setBounds(0,0,67,67);
C2.setIcon(W);
C2.setFocusPainted(false);
C2.setBorderPainted(false);
C2.setContentAreaFilled(false);
C2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(8,BOX.field[2][1],true);
new CPUmove(C12);
C12=false;
}
});
CP2.add(C2);
container.add(CP2,0);
CP3.setBounds(236,233,67,67);
CP3.setLayout(null);
C3.setBounds(0,0,67,67);
C3.setIcon(W);
C3.setFocusPainted(false);
C3.setBorderPainted(false);
C3.setContentAreaFilled(false);
C3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX(9,BOX.field[2][2],true);
new CPUmove(C13);
C13=false;
}
});
CP3.add(C3);
Container.add(CP3,0);
////
JButton clear = new JButton("clear");
JPanel Clear=new JPanel();
Clear.setLayout(null);
Clear.setBounds(155,320,70,17);
clear.setBorderPainted(false);
clear.setContentAreaFilled(false);
clear.setBounds(0,0,70,17);
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new BOX();
}
});
Clear.add(clear);
Container.add(Clear,0);
}
public static void main(String[] args) {
new mainFrame();
}
}
I truly am stuck upon why this happens.
the same thing happens when i try to refresh the points on click of buttons.
I have my MainWindow class where menue buttons and everything else are. In the middle of it is an Panel called content. I want to load JPanels from other classes into this field. But when i start the code below nothing shows up.
MainWindow Class:
public class MainWindow {
private JFrame frame;
private JScrollPane Content;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel TopPanel = new JPanel();
scrollPane.setColumnHeaderView(TopPanel);
JLabel lblNewLabel = new JLabel("Made by " + Globals.Author);
TopPanel.add(lblNewLabel);
JButton btnHome = new JButton("Home");
TopPanel.add(btnHome);
btnHome.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Content.add(new Home());
}
});
Content = new JScrollPane();
scrollPane.setViewportView(Content);
}
}
JPanel Class:
public class Home extends JPanelContentTemplate {
/**
* Create the panel.
*/
protected void InitializeComponents(){
setLayout(new BorderLayout(0, 0));
JPanel OptionsMenuePanel = new JPanel();
add(OptionsMenuePanel, BorderLayout.WEST);
JPanel ConentPanel = new JPanel();
add(ConentPanel, BorderLayout.CENTER);
ConentPanel.setLayout(new GridLayout(1, 2, 0, 0));
JLabel lblConnectedWith = new JLabel("Connected With:");
ConentPanel.add(lblConnectedWith);
JTextPane textServerIP = new JTextPane();
ConentPanel.add(textServerIP);
}
#Override
protected void Refresh() {
// TODO Auto-generated method stub
}
}
The InitializeComponents method comes from an Self Created Superclass:
public abstract class JPanelContentTemplate extends JPanel {
/**
* Create the panel.
*/
public JPanelContentTemplate() {
InitializeComponents();
}
protected abstract void InitializeComponents();
protected abstract void Refresh();
}
I also tried an repaint etc.
Thanks for Help
Nothing shows up because you add nothing but empty JScrollPanes to your GUI:
Content = new JScrollPane();
scrollPane.setViewportView(Content);
Here is a simple example of adding separate panels to the MainFrame. I hope it helps you.
public class SidePanel extends JPanel {
private JLabel label;
public SidePanel() {
setBorder(BorderFactory.createEtchedBorder());
label = new JLabel("Hello");
setVisible(true);
/* More Code Goes Here */
}
}
public class CenterPanel extends JPanel {
/* Center Panel Code */
}
public class MainFrame extends JFrame {
private SidePanel sidePanel;
private CenterPanel centerPanel;
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
sidePanel = new SidePanel();
centerPanel = new CenterPanel();
add(sidePanel, BorderLayout.WEST);
add(centerPanel, BorderLayout.CENTER);
setSize(300, 300);
setVisible(true);
}
}
/* Main App */
public static void main(String [] args) {
try {
/* Lambda Expression */
SwingUtitlities.InvokeLater(() -> new MainFrame());
} catch(Exception ex) {
ex.printStackTrace();
}
}
I'm trying to undo the setText() method effect in a JEditorPane. Here is my code:
public final class UndoManagerTestForJEditorPane {
private final JEditorPane editor = new JEditorPane();
private final UndoManager undoManager = new UndoManager();
public JComponent makeUI() {
editor.setContentType("text/html");
HTMLDocument document = (HTMLDocument) editor.getDocument();
document.addUndoableEditListener(undoManager);
editor.setText("Hello");
JPanel p = new JPanel();
p.add(new JButton(new AbstractAction("undo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canUndo()) {
undoManager.undo();
}
}
}));
p.add(new JButton(new AbstractAction("redo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canRedo()) {
undoManager.redo();
}
}
}));
p.add(new JButton(new AbstractAction("setText(new Date())") {
#Override
public void actionPerformed(ActionEvent e) {
String str = new Date().toString();
editor.setText(str);
}
}));
Box box = Box.createVerticalBox();
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box.add(makePanel("Default", editor));
JPanel pp = new JPanel(new BorderLayout());
pp.add(box, BorderLayout.NORTH);
pp.add(p, BorderLayout.SOUTH);
return pp;
}
private static JPanel makePanel(String title, JComponent c) {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder(title));
p.add(c);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new UndoManagerTestForJEditorPane().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
The default behaviour is done with four steps:
1) Nothing is done, the cursor doesn't even move..
2) The cursor gets down with almost 10 lines under the inserted word..
3) The text get disappeared..
4) the old text appears finally..
So, instead of these steps, could we do it just only with one undo step like in this link for JTextField JTextArea setText() & UndoManager, but with JEditorPane ?
The problem the replace method for JEditorPane does not get executed when setText() is called on JEditorPane...
Please any help ?
Thank you
You could do it with a separate class (can be nested to directly access the necessary GUI elements, if you only have to do your edits with informations from one class) which extends AbstractUndoableEdit. You can save the exact old state that you want to load after one undo operation and the exact new state which you want to reload after a redo operation. You can then set the correct values in the redo and undo methods directly by overriding them in the State class. This could look like this:
public final class UndoManagerTestForJEditorPane {
private final JEditorPane editor = new JEditorPane();
private final UndoManager undoManager = new UndoManager();
public JComponent makeUI() {
editor.setContentType("text/html");
HTMLDocument document = (HTMLDocument) editor.getDocument();
//document.addUndoableEditListener(undoManager); -> Not used anymore
editor.setText("Hello");
JPanel p = new JPanel();
p.add(new JButton(new AbstractAction("undo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canUndo()) {
undoManager.undo();
}
}
}));
// New class to hold the state and load the correct string
class State extends AbstractUndoableEdit
{
String oldText;
String newText;
State(String oldText, String newText)
{
this.oldText = oldText;
this.newText = newText;
}
#Override
public void undo() throws CannotUndoException {
editor.setText(oldText);
}
#Override
public boolean canUndo() {
return true;
}
#Override
public void redo() throws CannotRedoException {
editor.setText(newText);
}
#Override
public boolean canRedo() {
return true;
}
}
p.add(new JButton(new AbstractAction("redo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canRedo()) {
undoManager.redo();
}
}
}));
p.add(new JButton(new AbstractAction("setText(new Date())") {
#Override
public void actionPerformed(ActionEvent e) {
String str = new Date().toString();
// Add a new edit by saving the old string (by calling getText) and the new string 'str'
undoManager.addEdit(new State(editor.getText(), str));
editor.setText(str);
}
}));
Box box = Box.createVerticalBox();
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box.add(makePanel("Default", editor));
JPanel pp = new JPanel(new BorderLayout());
pp.add(box, BorderLayout.NORTH);
pp.add(p, BorderLayout.SOUTH);
return pp;
}
private static JPanel makePanel(String title, JComponent c) {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder(title));
p.add(c);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new UndoManagerTestForJEditorPane().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
As I said in the title, I am writing a code for a small program in java. I used Internal Frames to implement it. The thing is I am trying to add a login option to the program. The login class is a jInternalFrame and I want it to Enable/Disable specific buttons in my main window. I tried google-ing a solution but didn't seem to find it. (Keep in mind that I'm really new to programing so I expect there might be other problems in my code I don't see at the moment).
Main Window code:
import javax.swing.JDesktopPane;
public class FereastraPrincipala extends JFrame {
private static final long serialVersionUID = 1L;
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public FereastraPrincipala() {
super("Fereastra Principala");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,screenSize.height - inset * 2);
// Add a Window Exit Listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic(KeyEvent.VK_F);
JMenuItem mntmLogin = new JMenuItem("Login");
mnFile.add(mntmLogin);
mntmLogin.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnFile);
mntmLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
login();
}
});
JMenuItem mntmLogout = new JMenuItem("Logout");
mnFile.add(mntmLogout);
mntmLogout.setEnabled(true);
JMenuItem mntmCreazaUser = new JMenuItem("Creaza User");
mntmCreazaUser.setMnemonic(KeyEvent.VK_C);
mnFile.add(mntmCreazaUser);
mntmCreazaUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
creazaUser();
}
});
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.setMnemonic(KeyEvent.VK_X);
mnFile.add(mntmExit);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu mnAdministrator = new JMenu("Administrator");
mnAdministrator.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnAdministrator);
mnAdministrator.setEnabled(true);
JMenu mnPresedinte = new JMenu("Presedinte");
mnPresedinte.setMnemonic(KeyEvent.VK_P);
menuBar.add(mnPresedinte);
mnPresedinte.setEnabled(true);
JMenuItem mnHelp = new JMenuItem("Help");
mnHelp.setMnemonic(KeyEvent.VK_H);
menuBar.add(mnHelp);
mnHelp.setEnabled(true);
mnHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
help();
}
});
return menuBar;
}
protected void login() {
Login frame = new Login();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void help() {
Help frame1 = new Help();
frame1.setVisible(true);
jdpDesktop.add(frame1);
try {
frame1.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void creazaUser() {
CreazaUser frame = new CreazaUser();
frame.setVisible(true);
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
FereastraPrincipala frame = new FereastraPrincipala();
frame.setVisible(true);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
}
Login class code:
import java.awt.EventQueue;
public class Login extends JInternalFrame {
private static Login instance = null;
private JTextField textField;
private JPasswordField passwordField;
public static Login getInstance(){
if(instance == null) {instance = new Login(); }
return instance;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Login() {
super("Login", false, true, false, false);
setVisible(true);
setBounds(200, 200, 290, 173);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(22, 29, 79, 14);
panel.add(lblNewLabel);
JLabel label = new JLabel("Parola:");
label.setBounds(22, 54, 79, 14);
panel.add(label);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(123, 26, 98, 20);
panel.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(123, 51, 98, 20);
panel.add(passwordField);
JButton button = new JButton("Autentificare");
button.setBounds(80, 97, 112, 23);
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String user = textField.getText();
String pass = passwordField.getText();
if(user.equals("admin") && pass.equals("admin")) {
FereastraPrincipala(mntmLogout.setEnabled(true));
FereastraPrincipala(mnAdministrator.setEnabled(true));
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else if (user.equals("prez") && pass.equals("prez")) {
/* FereastraPrincipala(mntmLogout.setEnabled(true)):
FereastraPrincipala(mnPresedinte.setEnabled(true)); */
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else { JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);}
}
});
}
}
Please take a look at the following code (I've missed the imports purposely)
public class MainFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 11, 414, 240);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
panel.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
System.out.println("lost");
// I want to do something here, if I reach here!
}
#Override
public void focusGained(FocusEvent arg0) {
System.out.println("gained");
// I want to do something here, if I reach here!
}
});
tabbedPane.addTab("New tab", null, panel, null);
JButton button = new JButton("New button");
panel.add(button);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("New tab", null, panel_1, null);
JPanel panel_2 = new JPanel();
tabbedPane.addTab("New tab", null, panel_2, null);
}
}
I've created this class to test it and then add the onFocusListener in my main code, but it's not working the way I expect. Please tell what's wrong or is this the right EvenetListener at all?
JPanels are not focusable by default. If you ever wanted to use a FocusListener on them, you'd first have to change this property via setFocusable(true).
But even if you do this, a FocusListener is not what you want.
Instead I'd look to listen to the JTabbedPane's model for changes. It uses a SingleSelectionModel, and you can add a ChangeListener to this model, listen for changes, check the component that is currently being displayed and if your component, react.
You are using setBounds and null layouts, something that you will want to avoid doing if you are planning on creating and maintaining anything more than a toy Swing program.
Edit
For example:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings("serial")
public class MainPanel extends JPanel {
private static final int PREF_W = 450;
private static final int PREF_H = 300;
private static final int GAP = 5;
private static final int TAB_COUNT = 5;
private JTabbedPane tabbedPane = new JTabbedPane();
public MainPanel() {
for (int i = 0; i < TAB_COUNT; i++) {
JPanel panel = new JPanel();
panel.add(new JButton("Button " + (i + 1)));
panel.setName("Panel " + (i + 1));
tabbedPane.add(panel.getName(), panel);
}
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(tabbedPane, BorderLayout.CENTER);
tabbedPane.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent evt) {
Component component = tabbedPane.getSelectedComponent();
System.out.println("Component Selected: " + component.getName());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
MainPanel mainPanel = new MainPanel();
JFrame frame = new JFrame("MainPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
JPanel is a lightweight container and it is not a Actionable component so it does not get focus events. It lets you add focus listener because of swing component hierarchy. In Order to get tab selected events you need to use JTabbedPane#addChangeListener.
Hope this helps.