I have a JTextPane sandwiched between 2 JLabels - is there a known reason why the cursor shows through if i have it on the left most part of the textpane but not on the right?
Here is the code to better demonstrate what i mean:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class Testing {
/**
* #param args
*/
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel cp = new JPanel(new BorderLayout());
f.setContentPane(cp);
final SubPanel subPanel = new SubPanel();
cp.add(subPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(new JLabel("Align"));
final JComboBox alignCB = new JComboBox(new String[] {"left", "centre", "right"});
alignCB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
subPanel.align((String) alignCB.getSelectedItem());
}
});
buttonPanel.add(alignCB);
buttonPanel.add(new JLabel("Justify"));
final JComboBox justifyCB = new JComboBox(new String[] {"left", "centre", "right"});
justifyCB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
subPanel.justify((String) justifyCB.getSelectedItem());
}
});
buttonPanel.add(justifyCB);
JTextField tf = new JTextField("TF");
tf.setBorder(null);
buttonPanel.add(tf);
cp.add(buttonPanel, BorderLayout.NORTH);
f.pack();
f.setSize(new Dimension(300,300));
f.setLocation(300, 300);
f.setVisible(true);
}
public static class SubPanel extends JPanel {
JPanel innerPanel = new JPanel(new GridBagLayout());
TextPaneWidget[] tps = new TextPaneWidget[3];
public SubPanel() {
// setBorder(BorderFactory.createLineBorder(Color.RED));
setBorder(null);
// innerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
innerPanel.setBorder(null);
for (int i = 0; i < tps.length; i++) {
tps[i] = new TextPaneWidget();
}
int gridy = 0;
for (TextPaneWidget tp : tps) {
innerPanel.add(tp, new GridBagConstraints(0,gridy, 1,1, 0.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
gridy++;
}
setLayout(new GridBagLayout());
add(innerPanel, new GridBagConstraints(0,0, 1,1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
}
public void align(String alignment) {
System.out.println("Align: " + alignment);
int anchor = GridBagConstraints.CENTER;
if ("right".equals(alignment)) {
anchor = GridBagConstraints.EAST;
} else if ("left".equals(alignment)) {
anchor = GridBagConstraints.WEST;
}
GridBagLayout gbl = (GridBagLayout) getLayout();
gbl.setConstraints(innerPanel, new GridBagConstraints(0,0, 1,1, 1.0, 0.0, anchor, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
revalidate();
repaint();
}
public void justify(String justification) {
System.out.println("Justify: " + justification);
for (TextPaneWidget tp : tps) {
tp.justify(justification);
}
}
}
public static class MyDocument extends DefaultStyledDocument {
#Override
public void insertString(int offset, String text, AttributeSet attributeSet) throws BadLocationException {
SimpleAttributeSet attrs = new SimpleAttributeSet(attributeSet);
StyleConstants.setForeground(attrs, Color.WHITE);
StyleConstants.setBackground(attrs, Color.RED);
super.insertString(offset, text, attrs);
}
}
public static class TextPaneWidget extends JPanel {
JTextPane tp = new JTextPane();
JLabel lSpace = new JLabel(" ");
JLabel rSpace = new JLabel(" ");
public TextPaneWidget() {
// setBorder(BorderFactory.createLineBorder(Color.GREEN));
setBorder(null);
Font font = new Font("monospaced", Font.BOLD, 13);
tp.setBorder(null);
tp.setDocument(new MyDocument());
tp.setFont(font);
tp.setText("Text");
tp.setOpaque(true);
setLayout(new GridBagLayout());
lSpace.setBackground(Color.MAGENTA);
lSpace.setOpaque(true);
lSpace.setBorder(null);
add(lSpace, new GridBagConstraints(0,0, 1,1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
add(tp, new GridBagConstraints(1,0, 1,1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
rSpace.setBackground(Color.MAGENTA);
rSpace.setOpaque(true);
rSpace.setBorder(null);
add(rSpace, new GridBagConstraints(2,0, 1,1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tp.setCaretPosition((e.getX() < tp.getX()) ? 0 : tp.getText().length());
tp.requestFocusInWindow();
}
});
lSpace.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tp.setCaretPosition(0);
tp.requestFocusInWindow();
}
});
rSpace.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tp.setCaretPosition(tp.getText().length());
tp.requestFocusInWindow();
}
});
}
public void justify(String justification) {
double leftWeight = 0.5;
double rightWeight = 0.5;
if ("right".equals(justification)) {
leftWeight = 1.0;
rightWeight = 0.0;
} else if ("left".equals(justification)) {
leftWeight = 0.0;
rightWeight = 1.0;
}
GridBagLayout gbl = (GridBagLayout) getLayout();
gbl.setConstraints(lSpace, new GridBagConstraints(0,0, 1,1, leftWeight, 0.0, GridBagConstraints.EAST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
gbl.setConstraints(rSpace, new GridBagConstraints(2,0, 1,1, rightWeight, 0.0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
revalidate();
repaint();
}
}
}
I think I understand what's happening. Thanks for providing the code.
When you define a JTextPane, the default border is a 3 pixel empty border. This empty border provides a place for the text pane cursor to show when the cursor is at the rightmost position. The cursor is at the rightmost position to allow characters to be typed at the end of a line of characters.
When you define a null border, which is the same as a 0 pixel empty border, there's no place for the text pane cursor to be drawn when it's in the rightmost position.
In order to see the cursor in the rightmost position, you have to define an empty border with at least 1 right pixel. If you want it to be more visually appealing, include 1 left pixel.
tp.setBorder(BorderFactory.createEmptyBorder(0,1,0,1));
You have to define an empty border, because an empty border is the only Border that does not paint. A Border that paints will paint over the text pane cursor in the rightmost position.
So, you are required to use an empty border with at least one right pixel for a JTextPane to display the rightmost cursor.
Edited to add:
When you're using the GridBagLayout, a method like this one reduces the number of parameters that you have to deal with when you add a component.
protected void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight,
Insets insets, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
Setting the background to the following fixes this...
tp.setBackground(Color.RED);
tp.setOpaque(true);
Related
I'm trying to make a simple program where there is a text input field and a label, and when you input something to the field it stores the input as "testInput" and changes the label to that text. I'm using Eclipse's Window Builder plugin for this, and it has worked fine before. What happens now is it will take the text in, but wont send it back out to the jLabel. Here is my code:
package interest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestWin {
String testInput;
private JFrame frame;
private JTextField txtTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestWin window = new TestWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestWin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
txtTest = new JTextField();
//Change label when enter is pressed
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
txtTest.setText("test");
GridBagConstraints gbc_txtTest = new GridBagConstraints();
gbc_txtTest.insets = new Insets(0, 0, 5, 0);
gbc_txtTest.fill = GridBagConstraints.HORIZONTAL;
gbc_txtTest.gridx = 5;
gbc_txtTest.gridy = 1;
frame.getContentPane().add(txtTest, gbc_txtTest);
txtTest.setColumns(10);
JLabel lblTest = new JLabel("test");
GridBagConstraints gbc_lblTest = new GridBagConstraints();
gbc_lblTest.gridx = 5;
gbc_lblTest.gridy = 4;
frame.getContentPane().add(lblTest, gbc_lblTest);
}
}
I'm sure I'm making a really simple mistake, so any help is appreciated!
Put
JLabel lblTest = new JLabel("test");
at the begining of initialize() (or anywhere above txtTest.addActionListener...), and then replace
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
for
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
lblTest.setText(testInput); //This line was changed.
}
});
This is my SSCE (though in three seperate classes).
StartUp.java
public class Startup {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame gui = new MainFrame();
}
});
}
}
MainFrame.java
package gui;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class MainFrame {
private JFrame mainFrame;
private JMenuBar menuBar;
private JMenu menuRoboControl;
private JMenuItem menuItemStart;
private JMenuItem menuItemShutdown;
private JPanel cardPanel;
private final JPanel comListCard = new ComListCard();
public MainFrame() {
initComponents();
}
private void menuItemStartActionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) cardPanel.getLayout();
cardLayout.show(cardPanel, "selectPort");
}
private void menuItemShutdownActionPerformed(ActionEvent e) {
mainFrame.dispose();
System.exit(0);
}
private void initComponents() {
mainFrame = new JFrame();
menuBar = new JMenuBar();
menuRoboControl = new JMenu();
menuItemStart = new JMenuItem();
menuItemShutdown = new JMenuItem();
cardPanel = new JPanel();
//======== mainFrame ========
{
Container mainFrameContentPane = mainFrame.getContentPane();
mainFrameContentPane.setLayout(new BoxLayout(mainFrameContentPane, BoxLayout.X_AXIS));
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//======== menuBar ========
{
//======== menuRoboControl ========
{
menuRoboControl.setText("RoboControl");
//---- menuItemStart ----
menuItemStart.setText("Start Robot");
menuItemStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemStartActionPerformed(e);
}
});
menuRoboControl.add(menuItemStart);
//---- menuItemShutdown ----
menuItemShutdown.setText("Shutdown Robot");
menuItemShutdown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemShutdownActionPerformed(e);
}
});
menuRoboControl.add(menuItemShutdown);
}
menuBar.add(menuRoboControl);
}
mainFrame.setJMenuBar(menuBar);
//======== cardPanel ========
{
cardPanel.setLayout(new CardLayout());
cardPanel.add(comListCard, "selectPort");
}
mainFrameContentPane.add(cardPanel);
mainFrame.setSize(835, 635);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
}
}
ComListCard.java
package gui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComListCard extends JPanel {
private JTextArea portInfo;
private JScrollPane scrollPane1;
private JList<String> portList;
private JButton selectPort;
public ComListCard() {
initComponents();
}
public void initComponents() {
portInfo = new JTextArea();
scrollPane1 = new JScrollPane();
portList = new JList<>();
selectPort = new JButton();
//======== comListCard ========
{
this.setLayout(new GridBagLayout());
((GridBagLayout) this.getLayout()).columnWidths = new int[]{298, 214, 0, 0};
((GridBagLayout) this.getLayout()).rowHeights = new int[]{0, 0, 0, 0, 86, 220, 0, 0, 0};
((GridBagLayout) this.getLayout()).columnWeights = new double[]{0.0, 0.0, 1.0, 1.0E-4};
((GridBagLayout) this.getLayout()).rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0E-4};
//---- portInfo ----
portInfo.setText("Select the port connected to your XBee. If you do not know what port it is connected to, check your Device Manager.");
portInfo.setLineWrap(true);
portInfo.setWrapStyleWord(true);
portInfo.setOpaque(false);
portInfo.setEnabled(false);
portInfo.setEditable(false);
portInfo.setBorder(null);
this.add(portInfo, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== scrollPane1 ========
{
//---- portList ----
portList.setModel(new AbstractListModel<String>() {
String[] values = {
"1",
"2",
"3",
"4"
};
#Override
public int getSize() {
return values.length;
}
#Override
public String getElementAt(int i) {
return values[i];
}
});
scrollPane1.setViewportView(portList);
}
this.add(scrollPane1, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- selectPort ----
selectPort.setText("Select");
this.add(selectPort, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
}
}
}
Now some information on the problem. GUI works fine, purely about the CardLayout. As you can see I created a main window with a JPanel inside acting as the holder of the card. I created a card and have added it too to CardLayout. But it already appears from the start of the program while it should only appear after pressing the button (referring to the actionlistener where I put .show(..).
Any help appreciated. Not in a hurry either.
A CardLayout is designed to "hold" multiple cards (panels), but only one card will ever be displayed at a time. The key is that "one" of the panels is always displayed. So the CardLayout is functioning properly.
If you has an application that needs to dynamically display an panel on a frame then you must add the panel at run time. In this case the basic logic would be:
panel.add(...);
panel.revalidate();
panel.repaint();
With the above approach, space is not reserved on the frame for the panel when the frame is initially displayed (so you may also need to pack() the frame to make sure the panel is visible).
If you really want to see an empty space for your card panel when the frame is displayed, then you could simply create a panel with no components added to it and then add this panel to your CardLayout. Then when you invoke the show() method, you will swap in your panel with the components.
Im new to GUI's in Java and having a hell of a time understanding this:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
public class Main extends JFrame {
private JPanel contentPane;
static JPanel panel;
static JScrollPane scrollPane;
static JButton btnStart;
private static String compTestArray[];
static Integer indexer = 0;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 739, 456);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnStart = new JButton("Start");
btnStart.setBounds(10, 379, 89, 23);
btnStart.addActionListener(new ButtonListener());
contentPane.add(btnStart);
panel = new JPanel();
panel.setBounds(10, 11, 513, 359);
contentPane.add(panel);
scrollPane = new JScrollPane(panel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel.setLayout(gbl_panel);
scrollPane.setBounds(10, 11, 633, 359);
contentPane.add(scrollPane);
compTestArray = new String[2];
compTestArray[0] = "172.16.98.3";
compTestArray[1] = "172.16.98.6";
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
//String labelText = "Computer Name\tTest Name\tIteration\tPass\tFail\tCrashes\tStart\tStop";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel("Computer"));
for(int ix = 0; ix < compTestArray.length; ix++){
// Clear panel
panel.removeAll();
//labelText = compTestArray[indexer] + "\tKPI_1_1_1_1\t" + ix + "/20\t1\t\t0\t\t0\t\t12:00\t12:30";
//labelText = labelText.replaceAll("\t", " ");
listOfLabels.add(new JLabel(compTestArray[indexer]));
System.out.println("indexer is " + indexer);
// Create constraints
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer+2; i++) {
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.weightx = 0;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
// Repaint the GUI
scrollPane.validate();
} // Close for loop
// Disable Start button
btnStart.setEnabled(false);
} // Close public void actionPerformed(ActionEvent arg0)
} // Close static class ButtonListener implements ActionListener
}
Output:
I had been practicing GridBagLayout from some time, but still I feel confused when I want desired output. I want this kind of output
but i mess up creating one on which table is on one side and the two buttons are on other sides. The table gets squeezed.
Can anybody give me code to align the components (buttons and a table) like this. References for components are
activateServer, addFiles and table
Thanks in advance !
EDIT : this is the code which i am using (Short code for illustrating only prob)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ServerCode extends JFrame
{
ServerCode()
{
JTable table = new JTable(10,3);
JButton addFiles= new JButton("Add files"),activateServer = new JButton("Activate Button");
setLayout(new GridBagLayout());
add(table,new GridBagConstraints(0,0,6,6, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(addFiles,new GridBagConstraints(1,6,2,1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(activateServer,new GridBagConstraints(6,6,2,1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
setSize(700,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String...args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ServerCode();
}
});
}
}
And its output is :
Heck, I'd just use a BorderLayout for this. Forget GridBagLayout if it is not needed. For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class LayoutFoo extends JPanel {
private static final int PREF_W = 800;
public LayoutFoo() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton("Foo"));
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(new JButton("Bar"));
String[] columnNames = {"Mon", "Tues", "Wed"};
DefaultTableModel model = new DefaultTableModel(columnNames, 25);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getViewport().setPreferredSize(table.getPreferredSize());
// scrollPane.getViewport().setPreferredSize(table.getPreferredScrollableViewportSize());
JLabel southLabel = new JLabel("Foobars!");
southLabel.setForeground(Color.white);
JPanel southPanel = new JPanel();
southPanel.setBackground(Color.black);
southPanel.add(southLabel);
setLayout(new BorderLayout(5, 5));
add(buttonPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER );
add(southPanel, BorderLayout.SOUTH);
}
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
int width = PREF_W > superSize.width ? PREF_W : superSize.width;
return new Dimension(width, superSize.height);
}
private static void createAndShowGUI() {
LayoutFoo paintEg = new LayoutFoo();
JFrame frame = new JFrame("Smart File Transfer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If you want to keep the GridBagLayout i believe you need something like this:
add(activateServer,new GridBagConstraints(0,0,1,1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(addFiles,new GridBagConstraints(1,0,1,1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(table,new GridBagConstraints(0,1,2,1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
if you are having problems using the creator of GridBagConstraints you should try using the easier way like in this example
for more info try the oracle documentation
I am trying to create a layout where I have two panels with borders around them. I would like the rectangular borders to be of equal size. I would also like the JTextField in the bottom panel to be of that smaller width.
The problem is that, whenever I fill the bottom panel horizontally (using GridBagConstraints.HORIZONTAL), the checkbox and label inside that panel become misaligned with the checkbox and label in the panel above it.
I was hoping an experienced developer could offer insight into how I could make the two JPanels and their rectangular borders equal in size with one another, while also having their checkboxes and labels aligned.
Here is what it looks like now:
Here is code to reproduce the problem:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class Example
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
MyFrame frame = new MyFrame();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
class MyFrame
{
private JFrame frame;
private MyDialog dialog;
public MyFrame()
{
frame = new JFrame();
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
dialog = new MyDialog(frame);
}
}
class MyDialog
{
private JDialog dialog;
private JPanel mainPanel,
panel1,
inputPanel1,
panel2,
inputPanel2;
private JLabel titleLabel,
label1,
label2;
private JCheckBox checkBox1,
checkBox2;
private JTextField textField1,
textField2;
public MyDialog(JFrame frame)
{
dialog = new JDialog(frame, true);
buildPanel();
dialog.add(mainPanel);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
private void buildPanel()
{
mainPanel = new JPanel(new GridBagLayout());
titleLabel = new JLabel("Title");
checkBox1 = new JCheckBox("checkBox1");
label1 = new JLabel("label1:");
textField1 = new JTextField(15);
inputPanel1 = new JPanel(new GridBagLayout());
inputPanel1.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel1.add(label1, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
inputPanel1.add(textField1, getConstraints(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel1 = new JPanel(new GridBagLayout());
Border border1 = BorderFactory.createEtchedBorder();
panel1.setBorder(border1);
panel1.add(checkBox1, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel1.add(inputPanel1, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
checkBox2 = new JCheckBox("checkBox2");
label2 = new JLabel("label2:");
textField2 = new JTextField(8);
inputPanel2 = new JPanel(new GridBagLayout());
inputPanel2.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel2.add(label2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
inputPanel2.add(textField2, getConstraints(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2 = new JPanel(new GridBagLayout());
Border border2 = BorderFactory.createEtchedBorder();
panel2.setBorder(border2);
panel2.add(checkBox2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2.add(inputPanel2, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(titleLabel, getConstraints(0, 0, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE));
mainPanel.add(panel1, getConstraints(0, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
// When I fill panel2 horizontally, the checkbox becomes misaligned with the above checkbox:
//mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
}
private GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight, int anchor, int fill)
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.anchor = anchor;
gbc.fill = fill;
return gbc;
}
}
What I did was
Make your inputPanelX have FlowLayout with FlowLayout.LEADING instead of using GirdBagLayout for them.
inputPanel1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
And the scond one I just made the same Dimension as the first one
inputPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING)){
Dimension dim = new Dimension(inputPanel1.getPreferredSize());
public Dimension getPreferredSize(){
return new Dimension(dim);
}
};
That's all I changed. See full code below
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class Example
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
MyFrame frame = new MyFrame();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
class MyFrame
{
private JFrame frame;
private MyDialog dialog;
public MyFrame()
{
frame = new JFrame();
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
dialog = new MyDialog(frame);
}
}
class MyDialog
{
private JDialog dialog;
private JPanel mainPanel,
panel1,
inputPanel1,
panel2,
inputPanel2;
private JLabel titleLabel,
label1,
label2;
private JCheckBox checkBox1,
checkBox2;
private JTextField textField1,
textField2;
public MyDialog(JFrame frame)
{
dialog = new JDialog(frame, true);
buildPanel();
dialog.add(mainPanel);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
private void buildPanel()
{
mainPanel = new JPanel(new GridBagLayout());
titleLabel = new JLabel("Title");
checkBox1 = new JCheckBox("checkBox1");
label1 = new JLabel("label1:");
textField1 = new JTextField(15);
inputPanel1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
inputPanel1.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel1.add(label1);
inputPanel1.add(textField1);
panel1 = new JPanel(new GridBagLayout());
Border border1 = BorderFactory.createEtchedBorder();
panel1.setBorder(border1);
panel1.add(checkBox1, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel1.add(inputPanel1, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
checkBox2 = new JCheckBox("checkBox2");
label2 = new JLabel("label2:");
textField2 = new JTextField(8);
inputPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING)){
Dimension dim = new Dimension(inputPanel1.getPreferredSize());
public Dimension getPreferredSize(){
return new Dimension(dim);
}
};
inputPanel2.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel2.add(label2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
inputPanel2.add(textField2, getConstraints(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2 = new JPanel(new GridBagLayout());
Border border2 = BorderFactory.createEtchedBorder();
panel2.setBorder(border2);
panel2.add(checkBox2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2.add(inputPanel2, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(titleLabel, getConstraints(0, 0, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE));
mainPanel.add(panel1, getConstraints(0, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
// When I fill panel2 horizontally, the checkbox becomes misaligned with the above checkbox:
//mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
}
private GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight, int anchor, int fill)
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.anchor = anchor;
gbc.fill = fill;
return gbc;
}
}