I have a JTabbedPane with 4 tabs. I would like to load 1 tab 1 after another as the tabs uses, refers and retrieves from the same database. And this is causing an issue of "Database is locked" in my application.
Thanks in advance for the help and suggestions :)
This is how I create the JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBounds(0, 0, 450, 300);
tabbedPane.addTab("tab1", new class1UseDb());
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
tabbedPane.addTab("tab2", new class2UseDb());
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
tabbedPane.addTab("tab3", new class3UseDb());
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
tabbedPane.addTab("tab4", new class());
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
Based on this example, the sscce below simply creates a new panel for each click on the Add button and fills in the result. In a real program, you may want to use a SwingWorker to manage latency and resources.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import org.h2.jdbcx.JdbcDataSource;
/**
* #see https://stackoverflow.com/a/19860170/230513
* #see https://stackoverflow.com/a/15715096/230513
* #see https://stackoverflow.com/a/11949899/230513
*/
public class TabData {
private int n = 1;
private void display() {
JFrame f = new JFrame("TabData");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTabbedPane jtp = new JTabbedPane();
jtp.add(String.valueOf(n), createPane());
f.add(jtp, BorderLayout.CENTER);
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Add") {
#Override
public void actionPerformed(ActionEvent e) {
jtp.add(String.valueOf(++n), createPane());
jtp.setSelectedIndex(n - 1);
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JPanel createPane() {
JPanel p = new JPanel();
JLabel l = new JLabel();
p.add(new JLabel("Result: "));
p.add(l);
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:file:~/src/java/jdbc/test;IFEXISTS=TRUE");
ds.setUser("sa");
ds.setPassword("");
try {
Connection conn = ds.getConnection();
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT RAND() FROM DUAL");
rs.next();
l.setText(rs.getString(1));
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TabData().display();
}
});
}
}
Related
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 would like my original window to close when someone enters the password and a new one to pop up, or if you have a better recommendation please tell me. Here is my code,
The main class,
package notebook;
import java.awt.EventQueue;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
public class mainPage extends JDialog {
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainPage frame = new mainPage();
frame.setVisible(true);
frame.setResizable(false);
Image icon = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE);
frame.setIconImage(icon);
frame.setTitle("Notebook");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
*/
public mainPage() throws IOException {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 560, 390);
JLabel contentPane = new JLabel(
new ImageIcon(
ImageIO.read(new File(
"C:\\Users\\Gianmarco\\workspace\\notebook\\src\\notebook\\cool_cat.jpg"))));
contentPane.setBorder(new CompoundBorder());
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblEnterPassword = new JLabel(" Enter Password");
lblEnterPassword.setForeground(Color.LIGHT_GRAY);
lblEnterPassword.setBackground(Color.DARK_GRAY);
lblEnterPassword.setOpaque(true);
lblEnterPassword.setBounds(230, 60, 100, 15);
contentPane.add(lblEnterPassword);
security sInfo = new security();
textField = new JPasswordField(10);
nbTab notebook = new nbTab();
Action action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
String textFieldValue = textField.getText();
if (sInfo.checkPassword(textFieldValue)){
System.out.println("working");
notebook.setVisible(true);
//dispose();
}
}
};
JPanel panel = new JPanel();
textField.setBounds(230, 85, 100, 15);
contentPane.add(textField);
contentPane.add(panel);
textField.setColumns(10);
textField.addActionListener(action);
}
}
The password class,
package notebook;
public class security {
private String password = "kitten";
protected boolean checkPassword(String x){
if(x.length()<15 && x.equals(password)) return true;
return false;
}
}
The JTabbedPane class,
package notebook;
import javax.swing.JTabbedPane;
import javax.swing.JEditorPane;
import javax.swing.JList;
import javax.swing.JButton;
public class nbTab<E> extends JTabbedPane {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Create the panel.
*/
public nbTab() {
JEditorPane editorPane = new JEditorPane();
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(480, 345, 40, 30);
editorPane.add(btnNewButton);
editorPane.setBounds(80, 45, 400, 300);
addTab("New tab", null, editorPane, null);
JList<? extends E> list = new JList();
addTab("New tab", null, list, null);
}
}
In my main class, on lines 76 - 82 (where the action event listner is located) I would like to have my current window close and a new window of notebook to open. I used dispose() to close the password window. Then I try to open the JTabbedPane with setVisible(), setSelectedComponent, and setSelectedIndex however I am either using them incorrectly or there must be some better way to do this because it is not working. Any advice is appreciated guys thanks for all help.
As already suggested by MadProgrammer and Frakcool, the CardLayout layout manager is an interesting option in your case. A nice introduction to several Layout Managers for Swing is available here: A Visual Guide to Layout Managers.
You can use the code below to get an idea of how it could work. I have made a few modifications to your main application class:
The main class now extends from JFrame (instead of JDialog).
A few more panels and layout managers are used.
In Java class names usually start with a capital letter, so I have renamed your classes to MainPage, NotebookTab, and Security.
Here is the modified MainPage class:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class MainPage extends JFrame {
private static final String LOGIN_PANEL_ID = "Login panel";
private static final String NOTEBOOK_ID = "Notebook tabbed pane";
private JPanel mainPanel;
private CardLayout cardLayout;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setResizable(false);
Image icon = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE);
frame.setIconImage(icon);
frame.setTitle("Notebook");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
*/
public MainPage() throws IOException {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 560, 390);
cardLayout = new CardLayout();
mainPanel = new JPanel(cardLayout);
mainPanel.add(createLoginPanel(), LOGIN_PANEL_ID);
mainPanel.add(new NotebookTab(), NOTEBOOK_ID);
getContentPane().add(mainPanel);
}
private JPanel createLoginPanel() throws IOException {
JPanel loginPanel = new JPanel(new BorderLayout());
JPanel passwordPanel = new JPanel();
passwordPanel.setLayout(new BoxLayout(passwordPanel, BoxLayout.PAGE_AXIS));
JLabel lblEnterPassword = new JLabel("Enter Password");
lblEnterPassword.setForeground(Color.LIGHT_GRAY);
lblEnterPassword.setBackground(Color.DARK_GRAY);
lblEnterPassword.setOpaque(true);
lblEnterPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterPassword.setMaximumSize(new Dimension(100, 16));
lblEnterPassword.setAlignmentX(Component.CENTER_ALIGNMENT);
JTextField textField = new JPasswordField(10);
textField.setMaximumSize(new Dimension(100, 16));
textField.setAlignmentX(Component.CENTER_ALIGNMENT);
passwordPanel.add(Box.createRigidArea(new Dimension(0, 42)));
passwordPanel.add(lblEnterPassword);
passwordPanel.add(Box.createRigidArea(new Dimension(0, 10)));
passwordPanel.add(textField);
loginPanel.add(passwordPanel, BorderLayout.NORTH);
Action loginAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if (new Security().checkPassword(textField.getText())) {
System.out.println("working");
cardLayout.show(mainPanel, NOTEBOOK_ID);
}
}
};
textField.addActionListener(loginAction);
String imagePath = "C:\\Users\\Gianmarco\\workspace\\" +
"notebook\\src\\notebook\\cool_cat.jpg";
BufferedImage bufferedImage = ImageIO.read(new File(imagePath));
JLabel imageLabel = new JLabel(new ImageIcon(bufferedImage));
loginPanel.add(imageLabel, BorderLayout.CENTER);
return loginPanel;
}
}
I'm trying to display a JscrollPane using this code. but it's displaying a blank frame with just the "close" button displayed. Can't figure out why it wouldn't display. Any help would be greatly appreciated! :)
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.table.DefaultTableModel;
import edu.pitt.bank.Account;
import edu.pitt.bank.Transaction;
import edu.pitt.utilities.DbUtilities;
import edu.pitt.utilities.MySqlUtilities;
public class TransactionUI {
private JFrame frame;
private JScrollPane transactionPane;
private JTable tblTransactions;
public TransactionUI(Account userAccount) {
frame = new JFrame();
frame.setTitle("Account Transactions");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
transactionPane = new JScrollPane();
frame.getContentPane().add(transactionPane);
DbUtilities db = new MySqlUtilities();
String [] cols = {"Type", "Amount", "Date"};
String sql = "SELECT type, amount, transactionDate FROM srp63_bank1017.transaction;";
try {
System.out.println("use getDataTable()");
DefaultTableModel transactionList = db.getDataTable(sql, cols);
System.out.println("getDataTable() used");
tblTransactions = new JTable(transactionList);
tblTransactions.setFillsViewportHeight(true);
tblTransactions.setShowGrid(true);
tblTransactions.setGridColor(Color.BLACK);
transactionPane.getViewport().add(tblTransactions);
} catch (SQLException e) {
e.printStackTrace();
}
JButton btnClose = new JButton("Close");
btnClose.setBounds(323, 212, 89, 23);
btnClose.setBounds(284, 214, 73, 23);
frame.getContentPane().add(btnClose);
}
public JFrame getFrame() {
return frame;
}
}
I use this to call the above frame from another class:
public void actionPerformed(ActionEvent arg0) {
if(userAccount.getAccountID() != null){
TransactionUI tUI = new TransactionUI(userAccount);
tUI.getFrame().setVisible(true);
} else {
System.out.println("Account object must not be null");
}
}
});
Here is the getDataTable method...
public DefaultTableModel getDataTable(String sqlQuery, String[] customColumnNames) throws SQLException{
ResultSet rs = getResultSet(sqlQuery);
/* Metadata object contains additional information about a ResulSet,
* such as database column names, data types, etc...
*/
ResultSetMetaData metaData = rs.getMetaData();
// Get column names from the metadata object and store them in a Vector variable
Vector<String> columnNames = new Vector<String>();
for(int column = 0; column < customColumnNames.length; column++){
columnNames.add(customColumnNames[column]);
}
// Create a nested Vector containing an entire table from the ResultSet
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()){
Vector<Object> vector = new Vector<Object>();
for(int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++){
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
I received no errors
Problem #1
frame.getContentPane().setLayout(null);
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
See Laying Out Components Within a Container for more details
Problem #2
transactionPane.getViewport().add(tblTransactions);
Don't use ad with JScrollPane or JViewport, use
transactionPane.getViewport().setView(tblTransactions);
or
transactionPane.setViewportView(tblTransactions);
instead
See
How to Use Scroll Panes for more details
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTable table = new JTable(new DefaultTableModel(100, 100));
table.setGridColor(Color.LIGHT_GRAY);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Problem #3
The use of multiple windows, see The Use of Multiple JFrames, Good/Bad Practice? for a more in-depth discussion
I think what you really want is some kind of modal dialog. See How to Make Dialogs for more details
Your code without modifications
(Except removing the database code)
This is how your code looks on my PC, take a good hard look at the button...
Your code modified to use layout managers...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
TransactionUI ui = new TransactionUI();
JFrame frame = ui.getFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TransactionUI {
private JFrame frame;
private JScrollPane transactionPane;
private JTable tblTransactions;
public TransactionUI() {
frame = new JFrame();
frame.setTitle("Account Transactions");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
transactionPane = new JScrollPane();
frame.getContentPane().add(transactionPane);
String[] cols = {"Type", "Amount", "Date"};
String sql = "SELECT type, amount, transactionDate FROM srp63_bank1017.transaction;";
System.out.println("use getDataTable()");
DefaultTableModel transactionList = new DefaultTableModel(100, 100);
System.out.println("getDataTable() used");
tblTransactions = new JTable(transactionList);
tblTransactions.setFillsViewportHeight(true);
tblTransactions.setShowGrid(true);
tblTransactions.setGridColor(Color.BLACK);
transactionPane.setViewportView(tblTransactions);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton btnClose = new JButton("Close");
buttons.add(btnClose);
frame.getContentPane().add(buttons, BorderLayout.SOUTH);
}
public JFrame getFrame() {
return frame;
}
}
}
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();
}
}
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.