When having multiple JPanels laid out with BorderLayout, what decides which panel should keep its size on the cost of other panels when the containing dialog is re-sized?
In the sample code below, I would like the south panel, containing a JComboBox and JCheckBoxes, to keep its size when the dialog is re-sized.
Original Size
Re-Sized, south panel messed up
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JCheckBox;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JList;
import javax.swing.border.TitledBorder;
import javax.swing.BoxLayout;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class GrantPrivilegesDialog extends JDialog {
private JTable queueTable;
private JComboBox groupComboBox;
private JCheckBox receiveCheckBox;
private JCheckBox sendCheckBox;
private JCheckBox browseCheckBox;
private JCheckBox viewCheckBox;
private JCheckBox createCheckBox;
private JCheckBox deleteCheckBox;
private JCheckBox modifyCheckBox;
private JCheckBox purgeCheckBox;
private TableRowSorter<DefaultTableModel> queueSorter;
private DefaultTableModel queueModel;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
GrantPrivilegesDialog dialog = new GrantPrivilegesDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public GrantPrivilegesDialog() {
setTitle("Grant Privileges To Group(s)");
setBounds(100, 100, 866, 461);
getContentPane().setLayout(new BorderLayout());
{
JPanel northPanel = new JPanel();
northPanel.setLayout(new BorderLayout());
getContentPane().add(northPanel, BorderLayout.NORTH);
{
queueTable = new JTable();
//Object[][] rows = null;
Object[][] rows ={ {"*", "localhost1", "someQueue1"},
{"", "localhost2", "someQueue2"},
{"", "localhost3", "someQueue3"},
{"", "localhost4", "someQueue4"},
{"", "localhost5", "someQueue5"},
{"", "localhost6", "someQueue6.sdfsdfssdf.sfsdfsdfpweerpowerpoiwer.werjsdgf.sdföw.slksdfsdf"}
};
String[] queueColumnNames = {"","Server","QueueName"};
queueModel = new DefaultTableModel(rows, queueColumnNames){
#Override
public Class getColumnClass(int colNum) {
switch (colNum) {
case 0:
return String.class; //Asterisk (*) for dynamic
case 1:
return String.class; //Server
case 2:
return String.class; //Queue Name
default:
return String.class;
}
}
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
queueTable.setModel(queueModel);
queueSorter = new TableRowSorter<DefaultTableModel>(queueModel);
queueTable.setRowSorter(queueSorter);
queueTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
queueTable.getColumnModel().getColumn(0).setPreferredWidth(2);
queueTable.getColumnModel().getColumn(0).setMaxWidth(2);
queueTable.getColumnModel().getColumn(1).setPreferredWidth(225);
queueTable.getColumnModel().getColumn(2).setPreferredWidth(600);
queueTable.setCellSelectionEnabled(true);
JScrollPane queueScrollPane = new JScrollPane(queueTable);
northPanel.add(queueScrollPane, BorderLayout.CENTER);
queueScrollPane.setViewportBorder(new TitledBorder(null, "Queues", TitledBorder.LEADING, TitledBorder.TOP, null, null));
{
queueScrollPane.setViewportView(queueTable);
}
}
}
{
JPanel southPanel = new JPanel();
getContentPane().add(southPanel, BorderLayout.SOUTH);
southPanel.setLayout(new BorderLayout());
{
{
//JList<? extends E> list = new JList();
//panel_1.add(list, BorderLayout.NORTH);
}
}
{
JPanel privilegesPanel = new JPanel();
privilegesPanel.setBorder(BorderFactory.createTitledBorder("Grant"));
southPanel.add(privilegesPanel, BorderLayout.CENTER);
privilegesPanel.setLayout(new BorderLayout());
{
JPanel groupListPanel = new JPanel();
groupListPanel.setBorder(BorderFactory.createTitledBorder("Select Group"));
privilegesPanel.add(groupListPanel, BorderLayout.WEST);
groupListPanel.setLayout(new BorderLayout());
{
String[] choices = {"GroupA", "GroupB", "GroupC", "GroupD", "GroupE", "GroupE", "GroupE", "GroupE", "GroupE", "GroupE", "GroupE", "GroupE"};
groupComboBox = new JComboBox(choices);
groupComboBox.setEditable(true);
groupComboBox.setPreferredSize(new Dimension(300,10));
groupComboBox.setSelectedIndex(4);
groupListPanel.add(groupComboBox, BorderLayout.EAST);
}
}
{
JPanel privilegesCheckBoxPanel = new JPanel();
privilegesCheckBoxPanel.setBorder(BorderFactory.createTitledBorder("Privileges"));
privilegesPanel.add(privilegesCheckBoxPanel, BorderLayout.EAST);
privilegesCheckBoxPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
{
receiveCheckBox = new JCheckBox("receive");
receiveCheckBox.setSelected(true);
privilegesCheckBoxPanel.add(receiveCheckBox);
}
{
sendCheckBox = new JCheckBox("send");
sendCheckBox.setSelected(true);
privilegesCheckBoxPanel.add(sendCheckBox);
}
{
browseCheckBox = new JCheckBox("browse");
browseCheckBox.setSelected(true);
privilegesCheckBoxPanel.add(browseCheckBox);
}
{
viewCheckBox = new JCheckBox("view");
privilegesCheckBoxPanel.add(viewCheckBox);
}
{
createCheckBox = new JCheckBox("create");
privilegesCheckBoxPanel.add(createCheckBox);
}
{
deleteCheckBox = new JCheckBox("delete");
privilegesCheckBoxPanel.add(deleteCheckBox);
}
{
modifyCheckBox = new JCheckBox("modify");
privilegesCheckBoxPanel.add(modifyCheckBox);
}
{
purgeCheckBox = new JCheckBox("purge");
privilegesCheckBoxPanel.add(purgeCheckBox);
}
}
}
{
JPanel confirmPane = new JPanel();
southPanel.add(confirmPane, BorderLayout.SOUTH);
confirmPane.setLayout(new BorderLayout(0, 0));
{
JPanel panel = new JPanel();
confirmPane.add(panel, BorderLayout.EAST);
{
JButton grantButton = new JButton("GRANT");
panel.add(grantButton);
grantButton.setActionCommand("GRANT");
getRootPane().setDefaultButton(grantButton);
grantButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(receiveCheckBox.isSelected());
System.out.println(sendCheckBox.isSelected());
System.out.println(browseCheckBox.isSelected());
System.out.println(viewCheckBox.isSelected());
System.out.println(createCheckBox.isSelected());
System.out.println(deleteCheckBox.isSelected());
System.out.println(modifyCheckBox.isSelected());
System.out.println(purgeCheckBox.isSelected());
}
} );
}
{
JButton cancelButton = new JButton("CLOSE");
panel.add(cancelButton);
cancelButton.setActionCommand("CLOSE");
}
}
{
JLabel errorMessageLabel = new JLabel("");
confirmPane.add(errorMessageLabel, BorderLayout.WEST);
}
}
}
setMinimumSize(new Dimension(870, 300));
pack();
}
}
Change getContentPane().add(northPanel, BorderLayout.NORTH); to getContentPane().add(northPanel, BorderLayout.CENTER); and panel with table will be resizable and second panel will be with fixed size:
Also read about BorderLayout. I recommend you to use another layout manager, for example GridBagLayout, because it is more suitable for complex form.
Related
package SOS;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class BoardPanel {
private JFrame frame;
private void createAndDisplayGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createBoard(ActionEvent event) {
Object source = event.getSource();
if (source instanceof JTextField) {
JTextField textField = (JTextField) source;
String text = textField.getText();
int dimension = Integer.parseInt(text);
JPanel board = new JPanel(new GridLayout(dimension, dimension));
for (int row = 0; row < dimension; row++) {
for (int col = 0; col < dimension; col++) {
JLabel square = new JLabel(" ");
square.setBackground(Color.white);
square.setOpaque(true);
square.setBorder(BorderFactory.createLineBorder(Color.black));
board.add(square);
}
}
frame.add(board, BorderLayout.CENTER);
frame.pack();
}
}
private JPanel createTopPanel() {
JRadioButton optionS = new JRadioButton("S");
JRadioButton optionO = new JRadioButton("O");
ButtonGroup group = new ButtonGroup();
group.add(optionS);
group.add(optionO);
JPanel topPanel = new JPanel();
JLabel label = new JLabel("Board size:");
topPanel.add(label);
JTextField boardSize = new JTextField(6);
boardSize.addActionListener(this::createBoard);
topPanel.add(boardSize);
topPanel.add(optionS, BorderLayout.NORTH);
topPanel.add(optionO, BorderLayout.CENTER);
return topPanel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new BoardPanel().createAndDisplayGui());
}
}
I know I am supposed to make an action listener for each radio button and that seems pretty straightforward, but I am confused on how I would do that and then translate that to placing an S or O on the game boards given cell depending on what is selected. I think the more confusing part is being able to draw in the given cell either the S or the O depending on what is selected. This is for an SOS game, sort of like tic tac toe. I tried following a simple tic tac toe example but got lost as there is no radio buttons like this and I am using a different createboard method.
You can declare your radioButton globally so you can check the selected status. Then in a listener in your cells check that and place the appropriate letter:
package SOS;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class BoardPanel {
private JFrame frame;
private JRadioButton optionS;
private JRadioButton optionO;
private void createAndDisplayGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createTopPanel(), BorderLayout.PAGE_START);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createBoard(ActionEvent event) {
Object source = event.getSource();
if (source instanceof JTextField) {
JTextField textField = (JTextField) source;
String text = textField.getText();
int dimension = Integer.parseInt(text);
JPanel board = new JPanel(new GridLayout(dimension, dimension));
for (int row = 0; row < dimension; row++) {
for (int col = 0; col < dimension; col++) {
JLabel square = new JLabel(" ");
square.setBackground(Color.white);
square.setOpaque(true);
square.setBorder(BorderFactory.createLineBorder(Color.black));
board.add(square);
square.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
square.setText(optionS.isSelected() ? " S " : " O ");
}
});
}
}
frame.getContentPane().add(board, BorderLayout.CENTER);
frame.pack();
}
}
private JPanel createTopPanel() {
optionS = new JRadioButton("S");
optionO = new JRadioButton("O");
ButtonGroup group = new ButtonGroup();
group.add(optionS);
group.add(optionO);
JPanel topPanel = new JPanel();
JLabel label = new JLabel("Board size:");
topPanel.add(label);
JTextField boardSize = new JTextField(6);
boardSize.addActionListener(this::createBoard);
topPanel.add(boardSize);
topPanel.add(optionS, BorderLayout.NORTH);
topPanel.add(optionO, BorderLayout.CENTER);
return topPanel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new BoardPanel().createAndDisplayGui());
}
}
There are few ways you might be able to do this, personally, I like to decouple the workflows and remove dependencies where I can.
For example, your createBoard method is making an assumption about how the dimension value is captured by the user. What happens if you want to change that workflow to use a JSpinner or JCombobox? You'd then have to modify this method as well.
Better to pass the method the information it needs to do its job. In fact, I'd make it return an instance of JPanel, so as to remove all the dependencies, after all createBoard should do just that, nothing else.
I've changed the workflow so there is now a dedicated "create" button, this will collect the information it needs in order to be able to create the board itself. Not as dynamic as the other approach, but it gives the user time to consider their inputs
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class BoardPanel {
private JFrame frame;
enum State {
S, O;
}
private JPanel board;
private void createAndDisplayGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createBoard(int dimension, State state) {
JPanel board = new JPanel(new GridLayout(dimension, dimension));
for (int row = 0; row < dimension; row++) {
for (int col = 0; col < dimension; col++) {
JLabel square = new JLabel(" " + state.name() + " ");
square.setBackground(Color.white);
square.setOpaque(true);
square.setBorder(BorderFactory.createLineBorder(Color.black));
board.add(square);
}
}
return board;
}
private JPanel createTopPanel() {
JRadioButton optionS = new JRadioButton("S");
JRadioButton optionO = new JRadioButton("O");
JTextField boardSize = new JTextField(6);
JPanel topPanel = new JPanel();
ButtonGroup group = new ButtonGroup();
group.add(optionS);
group.add(optionO);
// Default state
optionS.setSelected(true);
JButton createButton = new JButton("Make it so");
createButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
State state = State.O;
if (optionS.isSelected()) {
state = State.S;
}
try {
int dimension = Integer.parseInt(boardSize.getText());
if (board != null) {
frame.remove(board);
}
board = createBoard(dimension, state);
frame.add(board, BorderLayout.CENTER);
frame.pack();
} catch (NumberFormatException exp) {
JOptionPane.showMessageDialog(topPanel, "Invalid board size", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
JLabel label = new JLabel("Board size:");
topPanel.add(label);
topPanel.add(boardSize);
topPanel.add(optionS);
topPanel.add(optionO);
topPanel.add(createButton);
return topPanel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new BoardPanel().createAndDisplayGui());
}
}
If you'd prefer something a little more dynamic, then you could add shared ActionListener to the buttons and text field, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class BoardPanel {
private JFrame frame;
enum State {
S, O;
}
private JPanel board;
private void createAndDisplayGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createBoard(int dimension, State state) {
JPanel board = new JPanel(new GridLayout(dimension, dimension));
for (int row = 0; row < dimension; row++) {
for (int col = 0; col < dimension; col++) {
JLabel square = new JLabel(" " + state.name() + " ");
square.setBackground(Color.white);
square.setOpaque(true);
square.setBorder(BorderFactory.createLineBorder(Color.black));
board.add(square);
}
}
return board;
}
private JPanel createTopPanel() {
JRadioButton optionS = new JRadioButton("S");
JRadioButton optionO = new JRadioButton("O");
JTextField boardSize = new JTextField(6);
JPanel topPanel = new JPanel();
ButtonGroup group = new ButtonGroup();
group.add(optionS);
group.add(optionO);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
State state = State.O;
if (optionS.isSelected()) {
state = State.S;
}
try {
int dimension = Integer.parseInt(boardSize.getText());
if (board != null) {
frame.remove(board);
}
board = createBoard(dimension, state);
frame.add(board, BorderLayout.CENTER);
frame.pack();
} catch (NumberFormatException exp) {
// Not yet ready
}
}
};
optionS.addActionListener(actionListener);
optionO.addActionListener(actionListener);
boardSize.addActionListener(actionListener);
// Default state
optionS.setSelected(true);
JLabel label = new JLabel("Board size:");
topPanel.add(label);
topPanel.add(boardSize);
topPanel.add(optionS);
topPanel.add(optionO);
return topPanel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new BoardPanel().createAndDisplayGui());
}
}
I am trying to get values from a database via Jlist; but when I select a value of Jlist, no values return and the "Jtable" becomes empty instead of titles. That's my code for UI.
Thanks for your help...
package ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import model.Category;
import model.Person;
import service.AddressBookService;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JSplitPane;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.AbstractListModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class UserInterfaceMain extends JFrame {
private JPanel contentPane;
private JPanel panel;
private JButton btnNew;
private JSplitPane splitPane;
private JList list;
private JTable table;
private JScrollPane scrollPane;
private List<Category> categories = new ArrayList<>();
private List<Person> personList = new ArrayList<>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserInterfaceMain frame = new UserInterfaceMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UserInterfaceMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 624, 395);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
btnNew = new JButton("NEW");
panel.add(btnNew);
splitPane = new JSplitPane();
contentPane.add(splitPane, BorderLayout.CENTER);
list = new JList();
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
do_list_valueChanged(arg0);
}
});
splitPane.setLeftComponent(list);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.EAST);
table = new JTable();
splitPane.setRightComponent(table);
scrollPane.setViewportView(table);
loadCategories();
}
public void loadCategories() {
categories = new AddressBookService().getAllCategories();
DefaultListModel<Category> listModel = new DefaultListModel<>();
for (int i = 0; i < categories.size(); i++) {
listModel.addElement(categories.get(i));
//listModel.addElement(categories.get(i).getName());
}
list.setModel(listModel);
}
public void loadPersonList() {
String[] columns = new String[] { "NAME", "LAST NAME", "E-MAIL", "CITY" };
Object[][] personData = new Object[personList.size()][];
for (int i = 0; i < personData.length; i++) {
personData[i] = new Object[] { personList.get(i).getName(), personList.get(i).getLastName(),
personList.get(i).getEmail(), personList.get(i).getCity() };
}
TableModel tableModel = new DefaultTableModel(personData, columns);
table.setModel(tableModel);
}
protected void do_list_valueChanged(ListSelectionEvent arg0) {
personList = new AddressBookService().getPersonsForTable(((Category)list.getSelectedValue()).getId());
loadPersonList();
System.out.println(personList.size());
}
}
I don't understand exactly what you want, but I modified your code to run it in this way:
Obviously I have all hardcoded in order to run your program. If your problem is that in the left side instead of the names of the categories appears the hash code of the object "com.mypackage.Category#12AAAF", you must modify your Category class and override the toString method.
#Override
public String toString() {
return getName();
}
If it isn't your problem, please add a comment describing it.
I am trying to create a JList with a small arrow next to it. When clicked, I want some content associated with the list item shown in the same List/Panel. The picture, I hope, gives a clear idea of what I am trying to achieve.
How do I do this ? Also, what is the small triangle feature to the left known as (for future search tags) ?
I hope this is what you meant. The arrowButton is a JToggleButton which, when activated, displays a JWindow containing information about the selected value of the JList. This JWindow will remain visible until the JToggleButtons state is set back to unselected again. The ListPanel class should be reusable in your code.
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Example {
public Example() {
JFrame frame = new JFrame();
ArrayList<Object> elements = new ArrayList<Object>();
ArrayList<String> texts = new ArrayList<String>();
ListPanel listPanel = new ListPanel(elements, texts);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JTextField elementField = new JTextField(5);
JTextArea textArea = new JTextArea(5, 10);
JPanel panel = new JPanel();
panel.add(new JLabel("Element:"));
panel.add(elementField);
panel.add(Box.createHorizontalStrut(15));
panel.add(new JLabel("Text:"));
panel.add(new JScrollPane(textArea));
int result = JOptionPane.showConfirmDialog(frame, panel, "Element & Text",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
listPanel.addElementToList(elementField.getText(), textArea.getText());
}
}
});
JButton deleteButton = new JButton("Remove");
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (listPanel.getList().getSelectedValue() != null) {
listPanel.removeElementFromList(listPanel.getList().getSelectedValue());
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
frame.add(listPanel);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
}
class ListPanel extends JPanel {
private JList<Object> list;
private JToggleButton arrowButton;
private ArrayList<String> texts;
private JWindow popup;
public ListPanel(ArrayList<Object> elements, ArrayList<String> texts) {
this.texts = texts;
popup = new JWindow();
arrowButton = new JToggleButton("\u25B6");
arrowButton.setMargin(new Insets(0, 0, 0, 0));
arrowButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arrowButton.isSelected()) {
Object value = list.getSelectedValue();
if (value != null) {
JLabel titleLabel = new JLabel(value.toString());
titleLabel.setBackground(Color.WHITE);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
titleLabel.setHorizontalAlignment(JLabel.LEFT);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
titlePanel.setBackground(Color.WHITE);
titlePanel.add(titleLabel);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setText(texts.get(list.getSelectedIndex()));
JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
contentPanel.add(titlePanel, BorderLayout.NORTH);
contentPanel.add(textPane);
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
popup.setContentPane(contentPanel);
popup.revalidate();
popup.pack();
popup.setVisible(true);
}
} else {
if (popup.isVisible()) {
popup.setVisible(false);
}
}
}
});
Timer timer = new Timer(100, null);
timer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (((JFrame) SwingUtilities.getWindowAncestor(ListPanel.this)) != null) {
activateComponentListener();
timer.stop();
}
}
});
timer.start();
list = new JList<Object>(new DefaultListModel<Object>());
for (Object element : elements) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
}
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(Color.WHITE);
buttonPanel.add(arrowButton, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBorder(null);
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(scrollPane);
add(buttonPanel, BorderLayout.WEST);
}
private void activateComponentListener() {
((JFrame) SwingUtilities.getWindowAncestor(this)).addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent arg0) {
if (popup.isVisible()) {
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
}
}
});
}
public void removeElementFromList(Object element) {
int index = getElementIndex(element);
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(getElementIndex(element)) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
public void removeElementFromList(int index) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(index) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
private Integer getElementIndex(Object element) {
for (int i = 0; i < ((DefaultListModel<Object>) getList().getModel()).getSize(); i++) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(i).equals(element)) {
return i;
}
}
return null;
}
public void addElementToList(Object element, String text) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
getTexts().add(text);
}
public JList<Object> getList() {
return list;
}
public JToggleButton getArrowButton() {
return arrowButton;
}
public ArrayList<String> getTexts() {
return texts;
}
}
I'm trying to make a window with an internal window, using a JSpinner to set integer values, a button to generate the JInternalFrame, passing JSpinner value as parameter.
This JInternalFrame will contain 3 JPannels, where they must have colmuns and rows equals to the value of JSpinner.
So, I thought of using an ArrayList of JFormatedTextFields, and a for to add TextFields to the ArrayList, with a class I've create previously to create JFormatedTextFields with one line, but I don't know how to use the for to add values.
There's the code:
JDialog:
package br.edu.faculdadedosguararapes;
import java.awt.EventQueue;
import javax.swing.JDialog;
import javax.swing.JSpinner;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.beans.PropertyVetoException;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.JScrollPane;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Soma extends JDialog {
private JSpinner spinner;
private JPanel panelLinhasEColunas;
private JPanel panelTop;
private JScrollPane scrollPanePrincipal;
private JButton btnGerarMatrizes;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Soma dialog = new Soma();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the dialog.
* #throws PropertyVetoException
*/
public Soma() throws PropertyVetoException {
setTitle("Soma de Matrizes");
setModalityType(ModalityType.APPLICATION_MODAL);
setBounds(100, 100, 573, 447);
panelTop = new JPanel();
getContentPane().add(panelTop, BorderLayout.NORTH);
panelTop.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
panelLinhasEColunas = new JPanel();
panelLinhasEColunas.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Numero de Colunas e Linhas", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(51, 51, 51)));
panelTop.add(panelLinhasEColunas);
spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(2, 2, 10, 1));
panelLinhasEColunas.add(spinner);
btnGerarMatrizes = new JButton("Gerar Matrizes");
btnGerarMatrizes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int valor = (Integer) spinner.getValue();
GerarMatrizes soma = new GerarMatrizes();
soma.GerarSoma(valor, scrollPanePrincipal, btnGerarMatrizes);
btnGerarMatrizes.setEnabled(false);
}
});
panelLinhasEColunas.add(btnGerarMatrizes);
scrollPanePrincipal = new JScrollPane();
getContentPane().add(scrollPanePrincipal, BorderLayout.CENTER);
}
}
Class to create JInternalFrame:
package br.edu.faculdadedosguararapes;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
public class GerarMatrizes {
public void GerarSoma(int valor, JScrollPane pane, final JButton botao){
ArrayList<JFormattedTextField> campos = new ArrayList<JFormattedTextField>();
JInternalFrame internalFrame = new JInternalFrame("");
internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosed(InternalFrameEvent arg0) {
botao.setEnabled(true);
}
});
internalFrame.setClosable(true);
internalFrame.setBorder(null);
internalFrame.setVisible(true);
pane.setViewportView(internalFrame);
Component rigidArea = Box.createRigidArea(new Dimension(20, 20));
internalFrame.getContentPane().add(rigidArea, BorderLayout.NORTH);
Component rigidArea_1 = Box.createRigidArea(new Dimension(20, 20));
internalFrame.getContentPane().add(rigidArea_1, BorderLayout.SOUTH);
JPanel panel = new JPanel();
internalFrame.getContentPane().add(panel, BorderLayout.CENTER);
JPanel panelMatrizA = new JPanel();
panelMatrizA.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Matriz A", TitledBorder.CENTER, TitledBorder.TOP, null, null));
panel.add(panelMatrizA);
panelMatrizA.setLayout(new GridLayout(valor, valor, 5, 5));
Component horizontalStrut = Box.createHorizontalStrut(20);
panel.add(horizontalStrut);
JPanel panelMatrizB = new JPanel();
panelMatrizB.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Matriz B", TitledBorder.CENTER, TitledBorder.TOP, null, null));
panel.add(panelMatrizB);
panelMatrizB.setLayout(new GridLayout(valor, valor, 5, 5));
Component horizontalStrut_1 = Box.createHorizontalStrut(20);
panel.add(horizontalStrut_1);
JButton btnSomar = new JButton("Somar");
panel.add(btnSomar);
JPanel panelMatrizRes = new JPanel();
panelMatrizRes.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Matriz Resultante", TitledBorder.CENTER, TitledBorder.TOP, null, null));
panel.add(panelMatrizRes);
panelMatrizRes.setLayout(new GridLayout(valor, valor, 5, 5));
/*for (int i=1; i < valor; i++){
campos.add(i);
}*/
}
}
And class to create JFormattedTextFields:
package br.edu.faculdadedosguararapes;
import javax.swing.JFormattedTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.DocumentFilter;
public class GeraObjeto {
public JFormattedTextField novoFtf(JFormattedTextField nome, JPanel panel){
nome = new JFormattedTextField();
nome.setHorizontalAlignment(SwingConstants.CENTER);
nome.setColumns(2);
DocumentFilter filtro = new FiltroNumero();
((AbstractDocument) nome.getDocument()).setDocumentFilter(filtro);
panel.add(nome);
return nome;
}
}
Well, I've changed
ArrayList<JFormattedTextField> campos = new ArrayList<JFormattedTextField>();
to
JFormattedTextField[] camposA = new JFormattedTextField[valor*valor];
GeraObjeto textField = new GeraObjeto();
so with a simple for using the class to create JFormattedTextFields (GeraObjeto) like
for (int i=0; i < valor*valor; i++){
camposA[i] = textField.novoFtf(camposA[i], panelMatrizA);
}
it's working well.
package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class login extends javax.swing.JFrame implements ActionListener, javax.swing.RootPaneContainer {
private static final long serialVersionUID = 1L;
private JTextField TUserID=new JTextField(20);
private JPasswordField TPassword=new JPasswordField(20);
protected int role;
public JButton bLogin = new JButton("continue");
private JButton bCancel = new JButton("cancel");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new login().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel();
JLabel l2 = new JLabel("(2011)");
l2.setFont(new Font("Courier New", Font.BOLD, 10));
l.setIcon(icon);
JLabel LUserID=new JLabel("Your User ID: ");
JLabel LPassword=new JLabel("Your Password: ");
TUserID.addActionListener(this);
TPassword.addActionListener(this);
TUserID.setText("correct");
TPassword.setEchoChar('*');
TPassword.setText("correct");
bLogin.setOpaque(true);
bLogin.addActionListener(this);
bCancel.setOpaque(true);
bCancel.addActionListener(this);
JFrame f = new JFrame("continue");
f.setUndecorated(true);
f.setSize(460,300);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 80) / 100.0f);
Container pane = f.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS) );
pane.setBackground(Color.BLACK);
Box box0 = Box.createHorizontalBox();
box0.add(Box.createHorizontalGlue());
box0.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
box0.add(l);
box0.add(Box.createRigidArea(new Dimension(100, 0)));
pane.add(box0);
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box.add(Box.createRigidArea(new Dimension(100, 0)));
box.add(LUserID);
box.add(Box.createRigidArea(new Dimension(32, 0)));
box.add(TUserID);
LUserID.setMaximumSize( LUserID.getPreferredSize() );
TUserID.setMaximumSize( TUserID.getPreferredSize() );
pane.add(box);
Box box2 = Box.createHorizontalBox();
box2.add(Box.createHorizontalGlue());
box2.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box2.add(Box.createRigidArea(new Dimension(100, 0)));
box2.add(LPassword,LEFT_ALIGNMENT);
box2.add(Box.createRigidArea(new Dimension(15, 0)));
box2.add(TPassword,LEFT_ALIGNMENT);
LPassword.setMaximumSize( LPassword.getPreferredSize() );
TPassword.setMaximumSize( TPassword.getPreferredSize() );
pane.add(box2);
Box box3 = Box.createHorizontalBox();
box3.add(Box.createHorizontalGlue());
box3.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 100));
box3.add(bLogin);
box3.add(Box.createRigidArea(new Dimension(10, 0)));
box3.add(bCancel);
pane.add(box3);
f.setLocation(450,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
String TBUsername = TUserID.getText();
Object src = evt.getSource();
char[] CHPassword1 = TPassword.getPassword();
String TBPassword = String.valueOf(CHPassword1);
login mLogin = this;
if (src==bLogin) {
if (authenticate(TBUsername,TBPassword)) {
System.out.println(this);
exitApp(this);
} else {
exitApp(this);
}
} else if (src==bCancel) {
exitApp(mLogin);
}
}
public void exitApp(JFrame mlogin) {
mlogin.setVisible(false);
}
private boolean authenticate(String uname, String pword) {
if ((uname.matches("correct")) && (pword.matches("correct"))) {
new MyJFrame().createAndShowGUI();
return true;
}
return false;
}
}
and MyJFrame.java
package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MyJFrame extends javax.swing.JFrame implements ActionListener {
private static final long serialVersionUID = 2871032446905829035L;
private JButton bExit = new JButton("Exit (For test purposes)");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyJFrame().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JPanel p = new JPanel();
p.setBackground(Color.black);
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel("(2011)"); //up to here
l.setIcon(icon);
p.add(l);
p.add(bExit);
bExit.setOpaque(true);
bExit.addActionListener(this);
JFrame f = new JFrame("frame");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setUndecorated(true);
p.setOpaque(true);
f.getContentPane().add(p);
f.pack();
f.setSize(1000,600);
Container pane=f.getContentPane();
pane.setLayout(new GridLayout(0,1) );
//p.setPreferredSize(200,200);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 90) / 100.0f);
f.setLocation(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src==bExit) {
System.exit(0);
}
}
}
I cannot get the exitApp() method to work, although it worked before I expanded on my code, I've been trying for hours to get it to work but no avail! The login button suceeds in opening the new frame but will not close the preious(login) frame. It did earlier till I added the validation method etc ....
Create only one JFrame as parent and for another Top-level Containers create only once JDialog (put there JPanel as base), and re-use that for another Action, then you only to remove all JComponents from Base JPanel and add there another JPanel
don't forget for as last lines after switch betweens JPanels inside Base JPanel
revalidate();
repaint();
you can pretty to forgot about that by implements CardLayout