Create JInternalFrame with 3 JPanels with variable size and TextFields - java

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.

Related

About getting values from JList

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.

How set size of specified String to JTextField?

JTextField in JPanel which in turn in JDialog doesn't take specified size. I tried to use BoxLayout and FlowLayout, but still have not achieved the desired size. I.E. I measure the size of String example and set this size to width of JTextField inputCat, but inputCat doesn't take this size, then I call it. How correctly set size of specified String to JTextField? Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.util.Calendar;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DemoJDialog {
static private JInternalFrame internal;
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
internal = new JInternalFrame("Example", true, true, false, true);
internal.setLayout(new BorderLayout());
internal.setVisible(true);
JDesktopPane dp = new JDesktopPane();
dp.add(internal);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(dp);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JTextField inputCat = new JTextField();
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very long string (really long )");
int heightInputCat = inputCat.getSize().height;
FontMetrics FN = internal.getFontMetrics(internal.getFont());
int widthInputCat = SwingUtilities.computeStringWidth(FN, example);
inputCat.setSize(widthInputCat, heightInputCat);
String[] comboString = { "Telecast", "Radiocast" };
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel ("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(internal, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}
This works just fine here:
import java.awt.EventQueue;
import java.util.Calendar;
import javax.swing.*;
public class DemoJDialog {
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({"rawtypes", "unchecked"})
#Override
public void run() {
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very "
+ "long string (really long)");
// create a textfield the size of the string!
JTextField inputCat = new JTextField(example);
inputCat.setCaretPosition(0);
String[] comboString = {"Telecast", "Radiocast"};
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(listPane, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}
But JTextField is filled by the example String. And I need empty JTextField with this width
Just use constructor which specifies desired colums Count:
JTextField inputCat = new JTextField(example.length());

How to open one JInternalFrame over another in JDesktopPane?

In my application, I am trying to open one JInternalFrame over another JInternalFrame in single JDesktopPane that implements MigLayout but it is displaying second internal frame beside first internal frame. Where am I going wrong?
Code
//MainClass.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import javax.swing.JDesktopPane;
import java.awt.Color;
#SuppressWarnings("serial")
public class MainClass extends JFrame {
private JPanel contentPane;
JDesktopPane desktopMain = new JDesktopPane();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainClass frame = new MainClass();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainClass() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, 1368, 766);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnJinternalframe = new JMenu("Click Here");
menuBar.add(mnJinternalframe);
JMenuItem mntmOpenInternalFrame = new JMenuItem("Open Internal Frame");
mntmOpenInternalFrame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JInternalFrame1 frame = new JInternalFrame1(desktopMain
.getPreferredSize());
frame.setVisible(true);
desktopMain.add(frame);
}
});
mnJinternalframe.add(mntmOpenInternalFrame);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
desktopMain.setBackground(Color.WHITE);
contentPane.add(desktopMain, BorderLayout.CENTER);
desktopMain.setLayout(new MigLayout("", "[0px:1366px:1366px,grow,shrink 50,fill]", "[0px:766px:766px,grow,shrink 50,fill]"));
}
}
//JInternalFrame1.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
#SuppressWarnings("serial")
public class JInternalFrame1 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame1(Dimension d) {
setTitle("JInternalFrame1");
setBounds(0, 0, 1368, 766);
setVisible(true);
setSize(d);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
JButton btnClickMe = new JButton("Click Me");
btnClickMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)e.getSource());
if (container != null)
{
JDesktopPane desktop = (JDesktopPane)container;
JInternalFrame2 frame = new JInternalFrame2();
frame.setVisible(true);
desktop.add( frame );
}
}
});
panel.add(btnClickMe, "cell 7 5");
}
}
//JInternalFrame2.java
import javax.swing.JInternalFrame;
#SuppressWarnings("serial")
public class JInternalFrame2 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame2() {
setTitle("JInternalFrame2");
setBounds(100, 100, 450, 450);
setSize(500,500);
}
}
I found the solution,here is the code..
//MainClass.java
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicInternalFrameUI;
#SuppressWarnings("serial")
public class MainClass extends JFrame {
private JPanel contentPane;
static JDesktopPane desktopMain = new JDesktopPane();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainClass frame = new MainClass();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainClass() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, 1368, 766);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnJinternalframe = new JMenu("Click Here");
menuBar.add(mnJinternalframe);
JMenuItem mntmOpenInternalFrame = new JMenuItem("Open Internal Frame");
mntmOpenInternalFrame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JInternalFrame1 frame = new JInternalFrame1(desktopMain
.getPreferredSize());
frame.setVisible(true);
Dimension desktopSize = desktopMain.getSize();
frame.setSize(desktopSize);
frame.setPreferredSize(desktopSize);
desktopMain.add(frame);
dontmoveframe();
}
});
mnJinternalframe.add(mntmOpenInternalFrame);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
desktopMain.setBackground(Color.WHITE);
contentPane.add(desktopMain, BorderLayout.CENTER);
desktopMain.setLayout(new CardLayout(0, 0));
}
public static void dontmoveframe() {
try {
JInternalFrame[] frames = desktopMain.getAllFrames();
frames[0].setSelected(true);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace();
}
// Make first internal frame unmovable
JInternalFrame[] frames = desktopMain.getAllFrames();
JInternalFrame f = frames[0];
BasicInternalFrameUI ui = (BasicInternalFrameUI) f.getUI();
Component north = ui.getNorthPane();
MouseMotionListener[] actions = (MouseMotionListener[]) north
.getListeners(MouseMotionListener.class);
for (int i = 0; i < actions.length; i++) {
north.removeMouseMotionListener(actions[i]);
}
}
}
//JInternalFrame1.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
#SuppressWarnings("serial")
public class JInternalFrame1 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame1(Dimension d) {
setTitle("JInternalFrame1");
setBounds(0, 0, 1368, 766);
setVisible(true);
setSize(d);
setClosable(true);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
JButton btnClickMe = new JButton("Click Me");
btnClickMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)e.getSource());
if (container != null)
{
JDesktopPane desktopPane = getDesktopPane();
JInternalFrame2 f1 = new JInternalFrame2();
desktopPane.add(f1);//add f1 to desktop pane
f1.setVisible(true);
Dimension desktopSize = getDesktopPane().getSize();
f1.setSize(desktopSize);
f1.setPreferredSize(desktopSize);
MainClass.dontmoveframe();
}
}
});
panel.add(btnClickMe, "cell 7 5");
}
}
//JInternalFrame2.java
import javax.swing.JInternalFrame;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
#SuppressWarnings("serial")
public class JInternalFrame2 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame2() {
setTitle("JInternalFrame2");
setBounds(0, 0, 1366, 768);
setClosable(true);
getContentPane().setLayout(
new MigLayout("", "[][][][][][]", "[][][][][][]"));
JButton btnBack = new JButton("Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JInternalFrame2.this.dispose();
}
});
getContentPane().add(btnBack, "cell 5 5");
MainClass.dontmoveframe();
}
}

Multiple JPanels inside JDialog, how to control panel re-sizing order?

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.

Cannot close frame using button after opening a new one in swing

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

Categories

Resources