I'm try of change change the text in the option exit , I would like put a title dynamic in with a personality own for example maybe in spanish put "salir" and remove the text default "Exit" I tryed used a variable String and put how atribute in JMenuItem("Exit"); but its give me error,someone say how I can do this?
this is full code :
import java.awt.*
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class BordeExample extends JFrame {
Container frameContainer;
JPanel panel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Ile");
JMenuItem fileExit = new JMenuItem("Exit");
JMenu borderMenu = new JMenu("Border");
String[] borderTypes = {"Bevel", "Compound", "Empty", "Etched", "Line", "Matte", "SoftBevel",
"Titled"};
JRadioButtonMenuItem[] borders = new JRadioButtonMenuItem[borderTypes.length];
AbstractBorder[] border = {new BevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new LineBorder(Color.blue, 10), new LineBorder(Color.red, 5)),
new EmptyBorder(10, 10, 10, 10), new EtchedBorder(), new LineBorder(Color.blue, 10),
new MatteBorder(new ImageIcon("")), new SoftBevelBorder(BevelBorder.RAISED),
new TitledBorder("Example")};
ButtonGroup buttonGroup = new ButtonGroup();
public BordeExample() {
super("");
fileMenu.add(fileExit);
for (int i = 0; i < borderTypes.length; ++i) {
borders[i] = new JRadioButtonMenuItem(borderTypes[i]);
buttonGroup.add(borders[i]);
borderMenu.add(borders[i]);
}
menuBar.add(fileMenu);
menuBar.add(borderMenu);
setJMenuBar(menuBar);
frameContainer = getContentPane();
frameContainer.setLayout(new BorderLayout());
frameContainer.add("Center", panel);
setupEventHandlers();
setSize(700, 700);
setVisible(true);
}
void setupEventHandlers() {
addWindowListener(new WindowHandler());
fileExit.addActionListener(new MenuItemHandler());
for (int i = 0; i < borders.length; ++i) {
borders[i].addItemListener(new ItemHandler());
}
}
public static void main(String[] args) {
BordeExample app = new BordeExample();
}
public class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public class MenuItemHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Exit")) {
System.exit(0);
}
}
}
public class ItemHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
JRadioButtonMenuItem button = (JRadioButtonMenuItem) e.getItem();
String label = button.getText();
for (int i = 0; i < borderTypes.length; ++i) {
if (label.equals(borderTypes[i])) {
panel.setBorder(border[i]);
repaint();
}
}
}
}
}
I tryed did that:
String textExample = "salir";
JMenu fileMenu = new JMenu(textExample);
"Code is working :"
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.border.AbstractBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
public class BordeExample extends JFrame {
// It's woring
String exitString = "slair";
JMenuItem fileExit = new JMenuItem(exitString);
//
Container frameContainer;
JPanel panel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Ile");
JMenu borderMenu = new JMenu("Border");
String[] borderTypes = { "Bevel", "Compound", "Empty", "Etched", "Line",
"Matte", "SoftBevel", "Titled" };
JRadioButtonMenuItem[] borders = new JRadioButtonMenuItem[borderTypes.length];
AbstractBorder[] border = {
new BevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new LineBorder(Color.blue, 10), new LineBorder(
Color.red, 5)), new EmptyBorder(10, 10, 10, 10),
new EtchedBorder(), new LineBorder(Color.blue, 10),
new MatteBorder(new ImageIcon("")),
new SoftBevelBorder(BevelBorder.RAISED),
new TitledBorder("Example") };
ButtonGroup buttonGroup = new ButtonGroup();
public BordeExample() {
super("");
fileMenu.add(fileExit);
for (int i = 0; i < borderTypes.length; ++i) {
borders[i] = new JRadioButtonMenuItem(borderTypes[i]);
buttonGroup.add(borders[i]);
borderMenu.add(borders[i]);
}
menuBar.add(fileMenu);
menuBar.add(borderMenu);
setJMenuBar(menuBar);
frameContainer = getContentPane();
frameContainer.setLayout(new BorderLayout());
frameContainer.add("Center", panel);
setupEventHandlers();
setSize(700, 700);
setVisible(true);
}
void setupEventHandlers() {
addWindowListener(new WindowHandler());
fileExit.addActionListener(new MenuItemHandler());
for (int i = 0; i < borders.length; ++i) {
borders[i].addItemListener(new ItemHandler());
}
}
public class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public class MenuItemHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Exit")) {
System.exit(0);
}
}
}
public class ItemHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
JRadioButtonMenuItem button = (JRadioButtonMenuItem) e.getItem();
String label = button.getText();
for (int i = 0; i < borderTypes.length; ++i) {
if (label.equals(borderTypes[i])) {
panel.setBorder(border[i]);
repaint();
}
}
}
}
public static void main(String[] args) {
new BordeExample();
}
}
Check Output screenshot :
Related
Try to use some "dark side" features of Swing and got problem when I try to populate the popup of a combo-box with some components. Here is my SSCCE:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormatSymbols;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.ComboPopup;
public class ComboBoxTryout extends JComboBox {
private JPanel panel;
public ComboBoxTryout() {
initPanel();
}
private void initPanel() {
panel = new JPanel(new GridLayout(7, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
DateFormatSymbols symbols = new DateFormatSymbols();
for (String s : symbols.getWeekdays()) {
if (s != null && !s.trim().isEmpty()) {
panel.add(createCheckBox(s));
}
}
setPopupComponent(this, panel);
}
private JCheckBox createCheckBox(String text) {
final JCheckBox cb = new JCheckBox(text);
cb.setHorizontalAlignment(SwingConstants.LEADING);
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
StringBuilder b = new StringBuilder();
for (Component c : panel.getComponents()) {
if (c instanceof JCheckBox && ((JCheckBox) c).isSelected()) {
if (b.length() > 0) {
b.append(", ");
}
b.append(((JCheckBox) c).getText().substring(0, 3));
}
}
getModel().setSelectedItem(b.toString());
}
});
return cb;
}
/**
* Sets the custom component as popup component for the combo-box.
*
* #param combo combo-box to get new popup component.
* #param comp new popup component.
*/
public static void setPopupComponent(JComboBox<?> combo, Component comp) {
final ComboPopup popup = (ComboPopup) combo.getUI().getAccessibleChild(combo, 0);
if (popup instanceof Container) {
Container c = (Container) popup;
c.removeAll();
c.setLayout(new GridLayout(1, 1));
c.add(comp);
c.setPreferredSize(comp.getPreferredSize());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frm = new JFrame("Test");
frm.add(new ComboBoxTryout(), BorderLayout.NORTH);
frm.setSize(250, 600);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
});
}
}
I can open the combo-box but when I click a check-box in the popup the combo-box goes closed and check-box is still not selected. But, when I change the line
frm.add(new ComboBoxTryout(), BorderLayout.NORTH);
to
frm.add(new ComboBoxTryout(), BorderLayout.SOUTH);
all works fine: I can change state of check-boxes and popup is still visible! Any suggestions, how to get it working for BorderLayout.NORTH?
The following doesn't use a regular JComboBox, but rather mimics one to give you more control.
This example is inspired from Creating Pop-Up Components and from your code.
It uses a Popup component and listeners on the button and on the textfield (textfield + button to look like a combobox, this part is not visually optimized in this example) to manage the popup hiding/showing.
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormatSymbols;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingConstants;
public class ButtonPopupSample {
private final JTextField tField;
private final JButton start;
private final JPanel panel;
private boolean popping = false;
private Popup popup;
ButtonPopupSample() {
panel = new JPanel(new GridLayout(7, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
DateFormatSymbols symbols = new DateFormatSymbols();
for (String s : symbols.getWeekdays()) {
if (s != null && !s.trim().isEmpty()) {
panel.add(createCheckBox(s));
}
}
JFrame frame = new JFrame("Button Popup Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tField = new JTextField(20);
tField.setEditable(false);
start = new JButton("Pop");
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
popOrNot();
}
};
start.addActionListener(actionListener);
tField.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(final MouseEvent me) {
popOrNot();
}
});
JPanel contPan = new JPanel();
contPan.add(tField);
contPan.add(start);
frame.setContentPane(contPan);
frame.setSize(350, 250);
frame.setVisible(true);
}
private JCheckBox createCheckBox(final String text) {
final JCheckBox cb = new JCheckBox(text);
cb.setHorizontalAlignment(SwingConstants.LEADING);
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
StringBuilder b = new StringBuilder();
for (Component c : panel.getComponents()) {
if (c instanceof JCheckBox && ((JCheckBox) c).isSelected()) {
if (b.length() > 0) {
b.append(", ");
}
b.append(((JCheckBox) c).getText().substring(0, 3));
}
}
tField.setText(b.toString());
}
});
return cb;
}
private void popOrNot() {
if (popping) {
popup.hide();
} else {
PopupFactory factory = PopupFactory.getSharedInstance();
Point location = tField.getLocationOnScreen();
popup = factory.getPopup(tField, panel, location.x, location.y + tField.getHeight());
popup.show();
}
popping = !popping;
}
public static void main(final String args[]) {
new ButtonPopupSample();
}
}
Solution found. A strange focus change event provides the above described problem. So processing of this event must be prevented.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormatSymbols;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.ComboPopup;
#SuppressWarnings("serial")
public class ComboBoxTryout extends JComboBox {
private JPanel panel;
private boolean avoidFocusChange;
/**
*
*/
public ComboBoxTryout() {
initPanel();
}
private void initPanel() {
panel = new JPanel(new GridLayout(7, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
DateFormatSymbols symbols = new DateFormatSymbols();
for (String s : symbols.getWeekdays()) {
if (s != null && !s.trim().isEmpty()) {
panel.add(createCheckBox(s));
}
}
setPopupComponent(this, panel);
}
#Override
protected void processFocusEvent(FocusEvent e) {
if (avoidFocusChange && FocusEvent.FOCUS_LOST == e.getID() && panel.isAncestorOf(e.getOppositeComponent())) {
System.out.println(e); // skip it
} else {
super.processFocusEvent(e);
}
avoidFocusChange = false;
}
private JCheckBox createCheckBox(String text) {
final JCheckBox cb = new JCheckBox(text);
cb.setHorizontalAlignment(SwingConstants.LEADING);
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
StringBuilder b = new StringBuilder();
for (Component c : panel.getComponents()) {
if (c instanceof JCheckBox && ((JCheckBox) c).isSelected()) {
if (b.length() > 0) {
b.append(", ");
}
b.append(((JCheckBox) c).getText().substring(0, 3));
}
}
getModel().setSelectedItem(b.toString());
}
});
cb.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
avoidFocusChange = SwingUtilities.isLeftMouseButton(e);
}
});
return cb;
}
/**
* Sets the custom component as popup component for the combo-box.
*
* #param combo combo-box to get new popup component.
* #param comp new popup component.
*/
public static void setPopupComponent(JComboBox<?> combo, Component comp) {
final ComboPopup popup = (ComboPopup) combo.getUI().getAccessibleChild(combo, 0);
if (popup instanceof Container) {
Container c = (Container) popup;
c.removeAll();
c.setLayout(new GridLayout(1, 1));
c.add(comp);
Dimension dim = comp.getPreferredSize();
dim.width += 10; // need 10 px more width
c.setPreferredSize(dim);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frm = new JFrame("Test");
frm.add(new ComboBoxTryout(), BorderLayout.NORTH);
frm.setSize(250, 600);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
});
}
}
If somebody finds a better solution, please post it!!!
I am trying to develop a voting GUI and I have a main class and a ballot class. The Ballot class extends JPanel and creates buttons inside the class. I am trying to add Ballot objects to the main JFrame but when I run the program, the buttons do not display. Any help would be appreciated. Here is the code.
Assig5.java:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.BoxLayout;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Assig5 extends JFrame
{
public Assig5()
{
super("E-Vote Version 1.0");
JPanel castVotePanel = new JPanel();
BoxLayout layout = new BoxLayout(castVotePanel, BoxLayout.Y_AXIS);
castVotePanel.setLayout(layout);
ArrayList<String> ballots = new ArrayList<String>();
try{
ballots = readBallotFile("ballots.txt");
}
catch(FileNotFoundException e){
System.exit(0);
}
ArrayList<Ballot> ballotList = addBallots(ballots);
for(Ballot b : ballotList)
{
add(b);
}
castVotePanel.add(createLoginButton());
castVotePanel.add(createCastButton());
add(castVotePanel);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[])
{
Assig5 assig5 = new Assig5();
}
public JButton createLoginButton()
{
JButton loginButton = new JButton("Login to Vote");
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// display/center the jdialog when the button is pressed
String input = JOptionPane.showInputDialog("Please enter your voter ID: ");
}
});
return loginButton;
}
public JButton createCastButton()
{
JButton castButton = new JButton("Cast Vote");
castButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
return castButton;
}
public ArrayList<Ballot> addBallots(ArrayList<String> ballotContents)
{
ArrayList<Ballot> ballotList = new ArrayList<Ballot>();
for(int i = 0; i < ballotContents.size(); i++)
{
String[] splitBallotContent = ballotContents.get(i).split("[:,]");
String[] options = new String[splitBallotContent.length - 2];
for(int j = 2; j < splitBallotContent.length; j++)
{
options[j - 2] = splitBallotContent[j];
}
Ballot ballot = new Ballot(splitBallotContent[0], splitBallotContent[1], options);
ballotList.add(ballot);
}
return ballotList;
}
public static ArrayList<String> readBallotFile(String filename) throws FileNotFoundException
{
ArrayList<String> list = new ArrayList<String>();
Scanner s = new Scanner(new File(filename));
int numBallots = Integer.parseInt(s.nextLine()); //we need to get to next line
for(int i = 0; i < numBallots; i++)
{
if(s.hasNextLine())
{
list.add(s.nextLine());
}
}
s.close();
return list;
}
Ballot.java:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.BoxLayout;
import java.awt.*;
import java.awt.event.*;
public class Ballot extends JPanel
{
public Ballot(String ballotID, String title, String[] options)
{
super();
BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(layout);
add(new JLabel(title, JLabel.CENTER));
for(String s : options)
{
add(new JButton(s));
//add actionlistener here
}
}
}
JFrame uses a BorderLayout, you are adding both the castVotePanel and all the Ballot panels to the same position on the frame (CENTER). You might want to consider using a different layout manager
See How to Use BorderLayout and Laying Out Components Within a Container for more details.
For example...
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Assig5 extends JFrame {
public Assig5() {
super("E-Vote Version 1.0");
JPanel castVotePanel = new JPanel();
BoxLayout layout = new BoxLayout(castVotePanel, BoxLayout.Y_AXIS);
castVotePanel.setLayout(layout);
ArrayList<String> ballots = new ArrayList<String>();
try {
ballots = readBallotFile("ballots.txt");
} catch (FileNotFoundException e) {
System.exit(0);
}
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
ArrayList<Ballot> ballotList = addBallots(ballots);
for (Ballot b : ballotList) {
add(b, gbc);
}
castVotePanel.add(createLoginButton());
castVotePanel.add(createCastButton());
add(castVotePanel, gbc);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[]) {
Assig5 assig5 = new Assig5();
}
public JButton createLoginButton() {
JButton loginButton = new JButton("Login to Vote");
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// display/center the jdialog when the button is pressed
String input = JOptionPane.showInputDialog("Please enter your voter ID: ");
}
});
return loginButton;
}
public JButton createCastButton() {
JButton castButton = new JButton("Cast Vote");
castButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
return castButton;
}
public ArrayList<Ballot> addBallots(ArrayList<String> ballotContents) {
ArrayList<Ballot> ballotList = new ArrayList<Ballot>();
int id = 0;
for (int i = 0; i < 10; i++) {
String[] options = new String[]{"A", "B", "C", "D"};
Ballot ballot = new Ballot(Integer.toString(++id), "Help " + id, options);
ballotList.add(ballot);
}
return ballotList;
}
public static ArrayList<String> readBallotFile(String filename) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
// Scanner s = new Scanner(new File(filename));
// int numBallots = Integer.parseInt(s.nextLine()); //we need to get to next line
// for (int i = 0; i < numBallots; i++) {
// if (s.hasNextLine()) {
// list.add(s.nextLine());
// }
//
// }
// s.close();
return list;
}
public class Ballot extends JPanel {
public Ballot(String ballotID, String title, String[] options) {
super();
BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(layout);
add(new JLabel(title, JLabel.CENTER));
for (String s : options) {
add(new JButton(s));
//add actionlistener here
}
}
}
}
JFrame uses BorderLayout by default and your all panels are on center of border that is why its not showing up
Use different positions or different layouts
for more on layouts : https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
https://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
My program will allow the user to log in first and if he is logged in,
he will click on labelone first and labeltwo next.
the program will print ("last two cards detected. starting new game..") and allow the user to click on the two labels again.
the problem I am facing is after my panel has been repainted. I cannot click on the labels
anymore.
I know that my codes provided it too lengthy but I have already attempted to tried to cut down my codes from my actual program.
I think the main focus is this block of codes in my controller class.
labelPanel.removeAll();
Dealer dealer = new Dealer();
labelPanel.add(new LabelPanel(dealer));
labelPanel.revalidate();
labelPanel.repaint();
new Controller(labelPanel,dealer);
I am not sure what happened to my mouselistener. please help
This is are the class. feel free to run it if you guys couldn't understand.
login as username-> john password -> abc
click on label one first, after that click on label two. the console will display
"last 2 cards detected, starting new game.."
after that try clicking the labels again(by right it should be clickable but it's not)
LoginPanel.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class LoginPanel extends JPanel {
private JPanel northPanel = new JPanel(new BorderLayout());
private JPanel southPanel = new JPanel(new BorderLayout());
private JPanel subSouthPanel = new JPanel(new GridBagLayout());
private JPanel subSouthPanelTwo = new JPanel(new FlowLayout());
private GridBagConstraints gbc2 = new GridBagConstraints();
private JTextField playerUsernameTF = new JTextField(15);
private JPasswordField playerPasswordTF = new JPasswordField(15);
private JButton playerLoginBtn = new JButton("Login");
public LoginPanel() {
setLayout(new BorderLayout());
gbc2.gridx = 0;
gbc2.gridy = 0;
subSouthPanel.add(new JLabel("Username"),gbc2);
gbc2.gridx = 1;
gbc2.gridy = 0;
subSouthPanel.add(playerUsernameTF,gbc2);
gbc2.gridx = 0;
gbc2.gridy = 1;
subSouthPanel.add(new JLabel("Password"),gbc2);
gbc2.gridx = 1;
gbc2.gridy = 1;
subSouthPanel.add(playerPasswordTF,gbc2);
southPanel.add(subSouthPanel,BorderLayout.CENTER);
subSouthPanelTwo.add(playerLoginBtn);
southPanel.add(subSouthPanelTwo,BorderLayout.SOUTH);
add(northPanel,BorderLayout.NORTH);
add(southPanel,BorderLayout.SOUTH);
}
public JTextField getPlayerUsernameTF() {
return playerUsernameTF;
}
public JPasswordField getPlayerPasswordTF() {
return playerPasswordTF;
}
void addListenerForPlayerLoginBtn(ActionListener actionListener) {
playerLoginBtn.addActionListener(actionListener);
}
}
LabelPanel.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class LabelPanel extends JPanel {
private JPanel panel = new JPanel(new FlowLayout());
private JLabel labelOne;
private JLabel labelTwo;
public LabelPanel(Dealer dealer) {
setLayout(new BorderLayout());
labelOne = new JLabel(new ImageIcon(dealer.hideCard()));
labelTwo = new JLabel(new ImageIcon(dealer.hideCard()));
panel.add(labelOne);
panel.add(labelTwo);
add(panel);
}
public JLabel getJLabelOne() {
return labelOne;
}
public JLabel getJLabelTwo() {
return labelTwo;
}
void listenerForJLabelOne(MouseListener listenForMouseClick) {
labelOne.addMouseListener(listenForMouseClick);
}
void listenerForJLabelTwo(MouseListener listenForMouseClick) {
labelTwo.addMouseListener(listenForMouseClick);
}
}
Dealer.java
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Dealer {
public Dealer() {
}
public Image hideCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/blank.png"));
} catch (Exception e) {
}
return img;
}
public Image displayFirsCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/ClubsAce.png"));
} catch (Exception e) {
}
return img;
}
public Image displaySecondCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/ClubsAce.png"));
} catch (Exception e) {
}
return img;
}
}
Controller.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.Timer;
public class Controller {
private LabelPanel labelPanel;
private Dealer dealer;
private int countdown = 1;
private Timer timer = new Timer(1000,null);
private MouseHandler mouseHandler = new MouseHandler();
private int clicked = 0;
public Controller(LabelPanel labelPanel,Dealer dealer) {
clicked = 0;
this.labelPanel = labelPanel;
this.dealer = dealer;
this.labelPanel.listenerForJLabelOne(mouseHandler);
this.labelPanel.listenerForJLabelTwo(mouseHandler);
this.labelPanel.getJLabelOne().setText("Ace");
this.labelPanel.getJLabelTwo().setText("Ace");
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
clicked++;
if(clicked == 1) {
labelPanel.getJLabelOne().setIcon((new ImageIcon(dealer.displayFirsCard())));
}
if(clicked == 2) {
labelPanel.getJLabelTwo().setIcon((new ImageIcon(dealer.displaySecondCard())));;
if(label.getText().equals(label.getText())) {
System.out.println("last 2 cards detected, starting new game..");
timer = new Timer(1000,new newGameTimer());
timer.start();
}
}
}
}
private class newGameTimer implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(countdown == 0) {
timer.stop();
clicked = 0;
labelPanel.removeAll();
Dealer dealer = new Dealer();
labelPanel.add(new LabelPanel(dealer));
labelPanel.revalidate();
labelPanel.repaint();
new Controller(labelPanel,dealer);
}
else {
countdown--;
}
}
}
}
MainFrame.java
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame {
private CardLayout cardLayout = new CardLayout();
private Dealer dealer = new Dealer();
private JPanel cardLayoutPanel = new JPanel();
private LoginPanel loginPanel = new LoginPanel();
private JFrame frame = new JFrame("Mouse CLick Test");
private JPanel dialogPanel = new JPanel();
private LabelPanel labelPanel = new LabelPanel(dealer);
public MainFrame() {
cardLayoutPanel.setLayout(cardLayout);
cardLayoutPanel.add(loginPanel,"1");
cardLayout.show(cardLayoutPanel,"1");
cardLayoutPanel.add(labelPanel,"2");
frame.add(cardLayoutPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(1024,768);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
loginPanel.addListenerForPlayerLoginBtn(new PlayerLoginBtnActionPerformed());
}
public class PlayerLoginBtnActionPerformed implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String playerUsername = loginPanel.getPlayerUsernameTF().getText();
String playerPassword = new String(loginPanel.getPlayerPasswordTF().getPassword());
if(playerUsername.equals("john") && playerPassword.equals("abc")) {
JOptionPane.showMessageDialog(dialogPanel,
"Login Successfully!"
,"Player Login",JOptionPane.PLAIN_MESSAGE);
cardLayout.show(cardLayoutPanel,"2");
new Controller(labelPanel,dealer);
}
else {
JOptionPane.showMessageDialog(dialogPanel,
"Wrong Password or Username!"
,"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[]args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
The problem is, you are adding a LabelPanel to a LabelPanel
labelPanel.add(new LabelPanel(dealer));
But you are passing the outer panel to the controller
new Controller(labelPanel, dealer);
The outer panel no longer actually contains any labels, but only contains the new LabelPanel...
A better solution would be to provide the LabelPanel with a "reset" option of some kind instead...
I have a grid of JTextFields for my sudoku gui but im confused as to how to place for example a 3 in the top left box, in the top left corner of that box so it looks something like this
http://tinypic.com/r/t7io28/8
and that number becomes un editable to the user?
Here's my class for setting the cells:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class Squares extends JPanel {
public final int CELL_COUNT = 9;
public Cell [] cells = new Cell[CELL_COUNT];
public Squares(){
this.setLayout(new GridLayout(3,3));
this.setBorder(new LineBorder(Color.BLACK,2));
for(int i = 0; i<CELL_COUNT; i++){
cells[i] = new Cell();
cells[i].setDocument(new NumericalDocument());
this.add(cells[i]);
}
}
public class Cell extends JTextField{
private int number;
public Cell(){
}
public void setNumber(int number){
this.number = number;
this.setText("5");
}
public int getNumber(){
return number;
}
}
public static class NumericalDocument extends PlainDocument{
String numbers = "0123456789";
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (getLength() == 0 && str.length() == 1 && numbers.contains(str)) {
super.insertString(offs, str, a);
}
else {
Toolkit.getDefaultToolkit().beep();
}
}
}
}
and here's the class that sets the 3x3 cells into a 3x3 grid
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class SudokuPanel extends JFrame {
public final int SQUARE_COUNT = 9;
public Squares [] squares = new Squares[SQUARE_COUNT];
public SudokuPanel(){
super("Sudoku");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3,3));
for(int i=0; i<SQUARE_COUNT; i++){
squares[i] = new Squares();
panel.add(squares[i]);
}
JPanel panel2 = new JPanel();
JButton startTime = new JButton();
JButton stop = new JButton();
JButton submit = new JButton();
MyTimer timer = new MyTimer();
startTime = new JButton("Start Timer");
stop = new JButton("Stop Timer");
final JLabel timerLabel = new JLabel(" ...Waiting... ");
submit = new JButton("Done");
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem newDifficulty = new JMenuItem("Select New Difficulty");
menu.add(newDifficulty);
JMenuItem reset = new JMenuItem("Reset Puzzle");
menu.add(reset);
JMenuItem exit = new JMenuItem("Exit");
menu.add(exit);
exitaction e = new exitaction();
newDifficultyaction d = new newDifficultyaction();
resetaction f = new resetaction();
reset.addActionListener(f);
exit.addActionListener(e);
newDifficulty.addActionListener(d);
panel2.add(timer);
add(panel, BorderLayout.CENTER);
add(panel2, BorderLayout.PAGE_END);
setVisible(true);
setLocationRelativeTo(null);
}
public class exitaction implements ActionListener{
public void actionPerformed (ActionEvent e){
System.exit(0);
}
}
public class newDifficultyaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
Level select = new Level();
}
}
public class resetaction implements ActionListener{
public void actionPerformed (ActionEvent e){
dispose();
SudokuPanel Squares = new SudokuPanel();
}
}
}
A JTextField can be set uneditable using setEditable(false). You could also use JLabels.
In the last question I was asking the community why my JPopupMenu did not appear on the screen.
I was unable to come up with a simple , runnable, compilable example.
So, here is what I did for you guys:
Is the area too small to draw a popup?
I want my popup to be like this:
The code of what I did is visible in the first photo.
Code:
/* The old code entered here has been removed */
Complete code can be found here
edit 2
I copied the various JRadioButtonMenuItem and the setupJPopup() into a new file and ran. It works. Why doesn't it work in ScreenRecorder class?
Code
package demo;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class PopupTrial {
public PopupTrial(){
setupJPopup();
JFrame frame = new JFrame();
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
}
frame.getContentPane().add(label);
label.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
frame.setVisible(true);
frame.setSize(300, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new PopupTrial();
}
});
}
public void setupJPopup(){
encodingGroup.add(avi);
encodingGroup.add(quicktime);
popup.add(avi);
popup.add(quicktime);
popup.addSeparator();
recordingAreaGroup.add(entireScreen);
recordingAreaGroup.add(custom);
popup.add(entireScreen);
popup.add(custom);
popup.addSeparator();
cursorGroup.add(selectBlackCursor);
cursorGroup.add(selectWhiteCursor);
cursorGroup.add(selectNoCursor);
selectCursor.add(selectBlackCursor);
selectCursor.add(selectWhiteCursor);
selectCursor.add(selectNoCursor);
popup.add(selectCursor);
popup.pack();
}
JLabel label = new JLabel("Click Me");
ButtonGroup recordingAreaGroup = new ButtonGroup();
ButtonGroup cursorGroup = new ButtonGroup();
ButtonGroup encodingGroup = new ButtonGroup();
JPopupMenu popup = new JPopupMenu();
JRadioButtonMenuItem avi = new JRadioButtonMenuItem("AVI",true);
JRadioButtonMenuItem quicktime = new JRadioButtonMenuItem("QuickTime",false);
JRadioButtonMenuItem entireScreen = new JRadioButtonMenuItem("Entire Screen",true);
JRadioButtonMenuItem custom = new JRadioButtonMenuItem("Custom...",false);
JMenuItem selectCursor = new JMenu("Select a cursor");
JRadioButtonMenuItem selectWhiteCursor = new JRadioButtonMenuItem("White Cursor",true);
JRadioButtonMenuItem selectBlackCursor = new JRadioButtonMenuItem("Black Cursor",false);
JRadioButtonMenuItem selectNoCursor = new JRadioButtonMenuItem("No Cursor",false);
}
No, the size of the JFrame isn't related to why the PopupMenu isn't showing. Here's an example showing something similar to what you want (and using similar methods) working:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupMenu extends Box{
Dimension preferredSize = new Dimension(400,30);
public PopupMenu(){
super(BoxLayout.Y_AXIS);
final JPopupMenu menu = new JPopupMenu("Options");
for(int i = 1; i < 20; i++)
menu.add(new JMenuItem("Option" + i));
JLabel clickMe = new JLabel("ClickMe");
clickMe.setAlignmentX(RIGHT_ALIGNMENT);
clickMe.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
menu.show(e.getComponent(), e.getX(), e.getY());
}});
add(clickMe);
}
public Dimension getPreferredSize(){
return preferredSize;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PopupMenu());
frame.validate();
frame.pack();
frame.setVisible(true);
}
}