I have a question regarding how to align my components on my GUI.
Referring to the screen capture above, I want the checkboxes to be aligned with each other, but here I'm getting that one checkbox (LC Proxy) which is out of line, due to there being an additional combo box on the same line.
Can anyone suggest the necessary changes I should make to achieve what I want? (Other suggestions on how to improve the code/display are also welcome!)
(P/S Sorry if the title is misleading; not sure how else I can name it)
Here's the code for my GUI:
/**
* Builds the elements for the GUI
*/
private void build() {
// define properties
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(100, 100);
this.setSize(360, 250);
this.setResizable(false);
// build elements
movFileField = new JTextField(30);
movFileField.setEditable(false);
JLabel textFieldLabel = new JLabel("MOV file: ");
textFieldLabel.setLabelFor(movFileField);
JPanel filenamePane = new JPanel();
filenamePane.setLayout(new FlowLayout());
filenamePane.add(textFieldLabel);
filenamePane.add(movFileField);
JCheckBox checkIPV = new JCheckBox("IPV Proxy");
checkIPV.setSelected(configMap.get(EpoxyConfigField.IPV_PROXY.name()).isEnabled());
toggleMap.put(EpoxyConfigField.IPV_PROXY, checkIPV);
flickComps.add(checkIPV);
JCheckBox checkITX = new JCheckBox("ITX Proxy");
checkITX.setSelected(configMap.get(EpoxyConfigField.ITX_PROXY.name()).isEnabled());
toggleMap.put(EpoxyConfigField.ITX_PROXY, checkITX);
flickComps.add(checkITX);
JCheckBox checkLC = new JCheckBox("LC Proxy");
checkLC.setSelected(configMap.get(EpoxyConfigField.LC_PROXY.name()).isEnabled());
toggleMap.put(EpoxyConfigField.LC_PROXY, checkLC);
flickComps.add(checkLC);
JComboBox<String> comboLCProfile = new JComboBox<String>("A;C;D;Dxd;E".split(";"));
JCheckBox checkArchive = new JCheckBox("Archive Asset");
checkArchive.setSelected(configMap.get(EpoxyConfigField.ARCHIVE.name()).isEnabled());
toggleMap.put(EpoxyConfigField.ARCHIVE, checkArchive);
flickComps.add(checkArchive);
JPanel checkboxPane = new JPanel();
checkboxPane.setLayout(new BoxLayout(checkboxPane, BoxLayout.PAGE_AXIS));
checkboxPane.add(checkIPV);
checkboxPane.add(checkITX);
// This is the part I'm having problems with
JPanel lcproxyPane = new JPanel();
lcproxyPane.add(checkLC);
lcproxyPane.add(comboLCProfile);
checkboxPane.add(lcproxyPane);
checkboxPane.add(checkArchive);
checkboxPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JButton processButton = new JButton("Process");
processButton.setActionCommand(COMMAND_PROCESS);
processButton.addActionListener(this);
flickComps.add(processButton);
JButton selectButton = new JButton("Select");
selectButton.setActionCommand(COMMAND_SELECT);
selectButton.addActionListener(this);
flickComps.add(selectButton);
statusField = new JTextArea(10,20);
statusField.setEditable(false);
statusField.setLineWrap(true);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(Box.createRigidArea(new Dimension(50, 0)));
buttonPane.add(processButton);
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(selectButton);
buttonPane.add(Box.createRigidArea(new Dimension(50, 0)));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
JPanel bottomPane = new JPanel();
bottomPane.setLayout(new BoxLayout(bottomPane, BoxLayout.PAGE_AXIS));
bottomPane.add(buttonPane);
bottomPane.add(new JScrollPane(statusField));
Container contentPane = this.getContentPane();
contentPane.add(filenamePane, BorderLayout.PAGE_START);
contentPane.add(checkboxPane, BorderLayout.CENTER);
contentPane.add(bottomPane, BorderLayout.PAGE_END);
this.pack();
}
The reason why you cannot align your components is because you used a layout which makes very difficult to align those components.
I suggest you to use GridBagLayout rather than FlowLayout.
Example:
JPanel checkboxPane = new JPanel();
GridBagLayout gbl_checkboxPane = new GridBagLayout();
gbl_checkboxPane.columnWidths = new int[]{430, 0, 0};
gbl_checkboxPane.rowHeights = new int[]{27, 27, 27, 27};
gbl_checkboxPane.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
gbl_checkboxPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
checkboxPane.setLayout(gbl_checkboxPane);
JCheckBox checkIPV = new JCheckBox("IPV Proxy");
GridBagConstraints gbc_checkIPV = new GridBagConstraints();
gbc_checkIPV.anchor = GridBagConstraints.WEST;
gbc_checkIPV.fill = GridBagConstraints.VERTICAL;
gbc_checkIPV.insets = new Insets(0, 0, 5, 5);
gbc_checkIPV.gridx = 0;
gbc_checkIPV.gridy = 0;
checkboxPane.add(checkIPV, gbc_checkIPV);
Related
I am trying to create a register form for my application(school project), I wanted to set the layout to BoxLayout but the Jtextfields and combo box is having issue as you can see below, does this issue relates to setSize() or is it something I am doing incorrect,I just want the Jtextfields sorts vertically , I appreciate the support
private JPanel SetUpRegister() {
JLabel registerLabel = new JLabel("Registera");
registerLabel.setFont(new Font("Arial", Font.BOLD, 30));
loginRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
passwordRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
fnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
lnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
ageRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
String[] genderlist = new String[] { "Male", "Female", "Other" };
JComboBox<String> registerList = new JComboBox<>(genderlist);
JPanel registerPanel = new JPanel();
registerPanel.setBackground(new Color(255, 140, 0));
registerPanel.add(registerLabel);
registerPanel.add(loginRegisterInput);
registerPanel.add(passwordRegisterInput);
registerPanel.add(fnRegisterInput);
registerPanel.add(lnRegisterInput);
registerPanel.add(ageRegisterInput);
registerPanel.add(registerList);
registerPanel.setLayout(new BoxLayout(registerPanel,BoxLayout.Y_AXIS));
return registerPanel;
}
The input fields are huge
The BoxLayout will attempt to resize components when extra space is available on the panel. It will resize a component up to its maximum size.
For some reason the maximum height of a JTextField is Integer.MAX_VALUE which makes no sense to me, since the height of the text never changes as you enter more text.
In any case you have a couple of choices:
Use a different layout manager, like the GridBagLayout. The GridBagLayout, will respect the preferred size of the text fields.
Create a custom JTestField and override the getMaximumSize() method to return the preferred height of the component
Use a wrapper panel.
For the wrapper panel you could do:
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(registerPanel, BorderLayout.PAGE_START);
return wrapper;
//return registerPanel;
The BorderLayout will respect the preferred height of any component added to the PAGE_START, so there is no need for the BoxLayout to resize any component.
private JPanel SetUpRegister() {
JLabel registerLabel = new JLabel("Registera");
JLabel registerLabel1 = new JLabel("Login :");
JLabel registerLabel2 = new JLabel("Password :");
JLabel registerLabel3 = new JLabel("First Name :");
JLabel registerLabel4 = new JLabel("Last Name :");
JLabel registerLabel5 = new JLabel("Age :");
JLabel registerLabel6 = new JLabel("Gender :");
JLabel registerLabel7 = new JLabel("Bio :");
registerLabel.setFont(new Font("Arial", Font.BOLD, 30));
JButton createAccButton = new JButton("Create");
createAccButton.addActionListener(new CreateAccountListener());
loginRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
passwordRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
fnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
lnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
ageRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
bioRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
String[] genderlist = new String[] { "Male", "Female", "Other" };
registerList = new JComboBox(genderlist);
JPanel registerPanel = new JPanel();
registerPanel.setLayout(new BoxLayout(registerPanel, BoxLayout.Y_AXIS));
registerPanel.add(registerLabel);
JPanel registerLabPanel = new JPanel();
registerLabPanel.setLayout(new FlowLayout());
registerLabPanel.add(registerLabel);
JPanel usernamePanel = new JPanel();
usernamePanel.setLayout(new FlowLayout());
usernamePanel.add(registerLabel1);
usernamePanel.add(loginRegisterInput);
JPanel passwordPanel = new JPanel();
passwordPanel.setLayout(new FlowLayout());
passwordPanel.add(registerLabel2);
passwordPanel.add(passwordRegisterInput);
JPanel fnPanel = new JPanel();
fnPanel.setLayout(new FlowLayout());
fnPanel.add(registerLabel3);
fnPanel.add(fnRegisterInput);
JPanel lnPanel = new JPanel();
lnPanel.setLayout(new FlowLayout());
lnPanel.add(registerLabel4);
lnPanel.add(lnRegisterInput);
JPanel agePanel = new JPanel();
agePanel.setLayout(new FlowLayout());
agePanel.add(registerLabel5);
agePanel.add(ageRegisterInput);
JPanel genderPanel = new JPanel();
genderPanel.setLayout(new FlowLayout());
genderPanel.add(registerLabel6);
genderPanel.add(registerList);
JPanel bioPanel = new JPanel();
bioPanel.setLayout(new FlowLayout());
bioPanel.add(registerLabel7);
bioPanel.add(bioRegisterInput);
JPanel buttonLoginPanel = new JPanel();
buttonLoginPanel.setLayout(new FlowLayout());
buttonLoginPanel.add(createAccButton);
registerPanel.add(registerLabel);
registerPanel.add(usernamePanel);
registerPanel.add(passwordPanel);
registerPanel.add(fnPanel);
registerPanel.add(lnPanel);
registerPanel.add(agePanel);
registerPanel.add(genderPanel);
registerPanel.add(bioPanel);
registerPanel.add(buttonLoginPanel);
return registerPanel;
}
I fixed the issue by making a Panel for each input and label
I was trying to build UI in IntelliJ but it was hard so I tried to build it in Eclipse. Now UI looks little better but still poor. One of chart (the cener one) should be biger and second one on south should be smaller but flat and long. I tried to use preffered size or validate or repaint but still nothing. How to anchor them to side borders, and avoid to cover them self?
public class MainWindow extends JFrame{
private JPanel contentPane;
private XYSeries daneXYSciezki;
private XYSeries daneXYWys;
private final XYSeriesCollection wykCenter;
private final XYSeriesCollection wykSouth;
public MainWindow(){
setTitle("ParserGPS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 880, 640);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panelNorth = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelNorth.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panelNorth, BorderLayout.NORTH);
JButton btnWczytajPlik = new JButton("Wczytaj plik");
panelNorth.add(btnWczytajPlik);
JLabel lblOdlego = new JLabel("Odległość:");
panelNorth.add(lblOdlego);
JLabel lblm = new JLabel("0m");
panelNorth.add(lblm);
JLabel lblCzas = new JLabel("Czas:");
panelNorth.add(lblCzas);
JLabel label = new JLabel("00:00:00");
panelNorth.add(label);
JLabel lblPrdko = new JLabel("Prędkość:");
panelNorth.add(lblPrdko);
JLabel lblkmh = new JLabel("0km/h");
panelNorth.add(lblkmh);
JLabel lblNrSat = new JLabel("Nr sat:");
panelNorth.add(lblNrSat);
JLabel label_1 = new JLabel("0");
panelNorth.add(label_1);
JLabel lblGga = new JLabel("GGA:");
lblGga.setHorizontalAlignment(SwingConstants.CENTER);
panelNorth.add(lblGga);
JLabel label_2 = new JLabel("0/0");
panelNorth.add(label_2);
JLabel lblGsa = new JLabel("GSA:");
panelNorth.add(lblGsa);
JLabel label_3 = new JLabel("0/0");
panelNorth.add(label_3);
JLabel lblNewLabel = new JLabel("RMC:");
panelNorth.add(lblNewLabel);
JLabel label_4 = new JLabel("0/0");
panelNorth.add(label_4);
JLabel lblGll = new JLabel("GLL:");
panelNorth.add(lblGll);
JLabel label_5 = new JLabel("0/0");
panelNorth.add(label_5);
JLabel lblVtg = new JLabel("VTG:");
panelNorth.add(lblVtg);
JLabel label_6 = new JLabel("0/0");
panelNorth.add(label_6);
JPanel jpCenter = new JPanel();
contentPane.add(jpCenter, BorderLayout.CENTER);
jpCenter.setPreferredSize(new Dimension(785, 440));
JPanel jpSouth = new JPanel();
FlowLayout flowLayout_1 = (FlowLayout) jpSouth.getLayout();
flowLayout_1.setAlignment(FlowLayout.TRAILING);
contentPane.add(jpSouth, BorderLayout.SOUTH);
this.daneXYSciezki = new XYSeries("Trasa", false);
wykCenter = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykCenter = createChart(wykCenter);
final ChartPanel jfcPanelCenter = new ChartPanel(jfcWykCenter);
jpCenter.add(jfcPanelCenter,BorderLayout.CENTER);
this.daneXYSciezki = new XYSeries("Wysokość", false);
wykSouth = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykSouth = createChart(wykSouth);
final ChartPanel jfcPanelSouth = new ChartPanel(jfcWykSouth);
jpSouth.add(jfcPanelSouth,BorderLayout.CENTER);
repaint();
revalidate();
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createXYLineChart(
"",
"Szerokość",
"Długość",
dataset);
final XYPlot plot = result.getXYPlot();
NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
yAxis.setAutoRangeIncludesZero(false);
yAxis.setAutoRange(true);
customizeChart(result);
return result;
}
private void customizeChart(JFreeChart chart) {
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer;
renderer = new XYLineAndShapeRenderer(true, true);
renderer.setSeriesShapesVisible(0, true);
renderer.setSeriesShapesVisible(1, false);
renderer.setSeriesPaint(0, Color.RED);
renderer.setSeriesStroke(0, new BasicStroke(1.0f));
plot.setRenderer(renderer);
plot.setBackgroundPaint(Color.WHITE);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.BLACK);
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.BLACK);
}
}
After #m.cekiera advices
public class MainWindow extends JFrame{
private JPanel contentPane;
private XYSeries daneXYSciezki;
private XYSeries daneXYWys;
private final XYSeriesCollection wykCenter;
private final XYSeriesCollection wykSouth;
public MainWindow(){
setTitle("ParserGPS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 880, 640);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panelNorth = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelNorth.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panelNorth,BorderLayout.NORTH);
JButton btnWczytajPlik = new JButton("Wczytaj plik");
panelNorth.add(btnWczytajPlik);
JLabel lblOdlego = new JLabel("Odległość:");
panelNorth.add(lblOdlego);
JLabel lblm = new JLabel("0m");
panelNorth.add(lblm);
JLabel lblCzas = new JLabel("Czas:");
panelNorth.add(lblCzas);
JLabel label = new JLabel("00:00:00");
panelNorth.add(label);
JLabel lblPrdko = new JLabel("Prędkość:");
panelNorth.add(lblPrdko);
JLabel lblkmh = new JLabel("0km/h");
panelNorth.add(lblkmh);
JLabel lblNrSat = new JLabel("Nr sat:");
panelNorth.add(lblNrSat);
JLabel label_1 = new JLabel("0");
panelNorth.add(label_1);
JLabel lblGga = new JLabel("GGA:");
//lblGga.setHorizontalAlignment(SwingConstants.CENTER);
panelNorth.add(lblGga);
JLabel label_2 = new JLabel("0/0");
panelNorth.add(label_2);
JLabel lblGsa = new JLabel("GSA:");
panelNorth.add(lblGsa);
JLabel label_3 = new JLabel("0/0");
panelNorth.add(label_3);
JLabel lblNewLabel = new JLabel("RMC:");
panelNorth.add(lblNewLabel);
JLabel label_4 = new JLabel("0/0");
panelNorth.add(label_4);
JLabel lblGll = new JLabel("GLL:");
panelNorth.add(lblGll);
JLabel label_5 = new JLabel("0/0");
panelNorth.add(label_5);
JLabel lblVtg = new JLabel("VTG:");
panelNorth.add(lblVtg);
JLabel label_6 = new JLabel("0/0");
panelNorth.add(label_6);
JPanel jpCenter = new JPanel(new BorderLayout());
contentPane.add(jpCenter, BorderLayout.CENTER);
//jpCenter.setPreferredSize(new Dimension(785, 440));
JPanel jpSouth = new JPanel(new BorderLayout());
//FlowLayout flowLayout_1 = (FlowLayout) jpSouth.getLayout();
// flowLayout_1.setAlignment(FlowLayout.TRAILING);
contentPane.add(jpSouth, BorderLayout.SOUTH);
this.daneXYSciezki = new XYSeries("Trasa", false);
wykCenter = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykCenter = createChart(wykCenter);
final ChartPanel jfcPanelCenter = new ChartPanel(jfcWykCenter);
jpCenter.add(jfcPanelCenter,BorderLayout.NORTH);
this.daneXYSciezki = new XYSeries("Wysokość", false);
wykSouth = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykSouth = createChart(wykSouth);
final ChartPanel jfcPanelSouth = new ChartPanel(jfcWykSouth);
jpCenter.add(jfcPanelSouth,BorderLayout.SOUTH);
}
...
}
As your code is not MCVE I could not run it with changes, but I think your problem is bad layout settings. For example, you create a new JPanel:
JPanel jpSouth = new JPanel();
FlowLayout flowLayout_1 = (FlowLayout) jpSouth.getLayout();
flowLayout_1.setAlignment(FlowLayout.TRAILING);
You are aware that it is using FlowLayout by defaul, by later you use:
jpSouth.add(jfcPanelSouth,BorderLayout.CENTER);
but you never change layout to BorderLayout. You cannot mix layout of one particular container. But this is not what couse you problem directly.
Your BorderLayout.SOUTH area stretch horizontally, to fit components inside, and BorderLayout.CENTER takes all spece left(or not). This is how those parts of BorderLayout works. So you can change where you put particular components, or change layout at all.
I suggest to try with:
JPanel jpCenter = new JPanel(new BorderLayout());
...
jpCenter.add(jfcPanelCenter,BorderLayout.NORTH);
...
jpCenter.add(jfcPanelSouth,BorderLayout.SOUTH); //not to contentPane!
this will change an arrangement. However I am not sure, is it what you want. If not, try with different layout, for example BoxLayout.
Also I would rather use pack() and set size of components, than setBounds on a countainer.
You can also use GUI builders, like Netbeans IDE GUI Builder if you want to create GUI but don't care how.
The below code creates the following GUI.
But I would like to have TextFields "A" and "C" completely fill their respective rows (so that their right corners are aligned with the right edge of the JComboBox. Help would be much appreciated!
Here's the code:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
Dimension size = new Dimension( 310, 210 );
frame.setSize(size);
frame.setPreferredSize(size);
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JTextField tf3 = new JTextField();
JLabel label1 = new JLabel( "A");
JLabel label2 = new JLabel( "B");
JLabel label3 = new JLabel( "C");
String[] opts = {"1","2","3"};
JComboBox dropdown = new JComboBox(opts);
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup().
addComponent(label1).addComponent(label2).
addComponent(label3));
hGroup.addGroup(layout.createParallelGroup().
addComponent(tf1).addComponent(tf2).
addComponent(tf3));
hGroup.addGroup(layout.createParallelGroup().addComponent(dropdown));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label1).addComponent(tf1));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label2).addComponent(tf2).addComponent(dropdown));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label3).addComponent(tf3));
layout.setVerticalGroup(vGroup);
frame.add( panel, BorderLayout.NORTH );
frame.setVisible(true);
I think the best for this would be to use GridBagLayout, it is al little bit hard to use, but if you read some tutorials you'll find that it is the perfect solution for you.
GridBagLayout have weight in x and y, fill in x and y, and it is like a table.
You need to specify table with 2 columns, and three rows.
then each element need to be positioned in this table row and column, but the A and C should have gridtWidth set to 2 columns. And in the middle row you put jtextdield in one column, and jcombobox in the second.
Here you have sample program that do this:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JComboBox;
public class Example {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Example window = new Example();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Example() {
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[] {500, 500};
gridBagLayout.rowHeights = new int[] {50, 50, 50};
gridBagLayout.columnWeights = new double[]{1.0, 1.0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0};
frame.getContentPane().setLayout(gridBagLayout);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.weightx = 1.0;
gbc_textField.gridwidth = 2;
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 0;
frame.getContentPane().add(textField, gbc_textField);
textField.setColumns(10);
textField_1 = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.weightx = 1.0;
gbc_textField_1.insets = new Insets(0, 0, 5, 5);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 0;
gbc_textField_1.gridy = 1;
frame.getContentPane().add(textField_1, gbc_textField_1);
textField_1.setColumns(10);
JComboBox comboBox = new JComboBox();
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.weightx = 1.0;
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 1;
gbc_comboBox.gridy = 1;
frame.getContentPane().add(comboBox, gbc_comboBox);
textField_2 = new JTextField();
GridBagConstraints gbc_textField_2 = new GridBagConstraints();
gbc_textField_2.weightx = 1.0;
gbc_textField_2.gridwidth = 2;
gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_2.gridx = 0;
gbc_textField_2.gridy = 2;
frame.getContentPane().add(textField_2, gbc_textField_2);
textField_2.setColumns(10);
}
}
It is hard to write UI by hand if you are not very familiar. Better idea is to use some UI Design tools. For example WindowBuilder in Eclipse. It can read and show your Frames and allow you to add button by just dragging it to the right place in the frame, it is a lot easier and faster. If you click in the added element you will automatically get created an action listener and you are ready to write the code for the action. I recommend this way of building UIs:)
I am new to java swing, I wrote a startup program to formart text, but i am confused with the layout,
the result is below:
I want the combobox and the button are placed middle of the ctrlPanel, and the combobox should not be stretched
public class MainFrame extends JFrame {
private static final long serialVersionUID = 7553142908344084288L;
private static String[] formats = new String[] {
"JSON",
"XML",
"YAML"
};
public MainFrame() {
super("jValidator");
Panel mainPanel = new Panel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
setContentPane(mainPanel);
JTextArea fromTextArea = new JTextArea(20, 40);
JScrollPane fromTextAreaScrollPanel = new JScrollPane(fromTextArea);
fromTextAreaScrollPanel.setPreferredSize(new Dimension(300, 300));
fromTextAreaScrollPanel.setBorder(BorderFactory.createEmptyBorder(15, 5, 15, 5));
mainPanel.add(fromTextAreaScrollPanel);
JButton fmtButton = new JButton("Format >>");
JComboBox jComboBox = new JComboBox(formats);
jComboBox.setBorder(BorderFactory.createTitledBorder("Text Format"));
JPanel ctrPanel = new JPanel();
ctrPanel.setLayout(new BoxLayout(ctrPanel, BoxLayout.Y_AXIS));
ctrPanel.setAlignmentY(Component.CENTER_ALIGNMENT);
ctrPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
ctrPanel.add(jComboBox);
ctrPanel.add(Box.createRigidArea(new Dimension(50, 15)));
ctrPanel.add(fmtButton);
mainPanel.add(ctrPanel);
JTextArea toTextArea = new JTextArea(20, 40);
JScrollPane toTextAreaScrollPanel = new JScrollPane(toTextArea);
toTextAreaScrollPanel.setPreferredSize(new Dimension(300, 300));
toTextAreaScrollPanel.setBorder(BorderFactory.createEmptyBorder(15, 5, 15, 5));
mainPanel.add(toTextAreaScrollPanel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
You could use a GridBagLayout instead of a BoxLayout...
JPanel ctrPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
ctrPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
gbc.fill = GridBagConstraints.HORIZONTAL;
ctrPanel.add(jComboBox, gbc);
ctrPanel.add(Box.createRigidArea(new Dimension(50, 15)), gbc);
gbc.fill = GridBagConstraints.NONE;
ctrPanel.add(fmtButton, gbc);
Take a look at Laying Out Components Within a Container for more details
For that purposes I recommend you to use another LayoutManager, for example GridBagLayout change creation of ctrPanel like next :
JButton fmtButton = new JButton("Format >>");
JComboBox jComboBox = new JComboBox(formats);
jComboBox.setBorder(BorderFactory.createTitledBorder("Text Format"));
JPanel ctrPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx=0;
c.gridy=1;
ctrPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
ctrPanel.add(fmtButton,c);
c.gridy=0;
c.fill = GridBagConstraints.HORIZONTAL;
ctrPanel.add(jComboBox,c);
mainPanel.add(ctrPanel);
And it looks like:
I have designed a frame containing a few controls using the design view in Netbeans 6.9.1. Further, I have added an empty panel in which I am trying to toggle display of a couple of swing components on button click. The problem is that on button click, the panel displays nothing. The code is as follows:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JPanel txtPanel = new JPanel();
JPanel listPanel = new JPanel();
JTextField txtfield = new JTextField("ABCDEFGHIJ", 20);
txtPanel.add(txtfield);
JList<String> list = new JList<String>();
DefaultListModel<String> model = new DefaultListModel<String>();
for (int i = 0; i < userCommands.size(); i++){
model.addElement(userCommands.get(i));
}
list.setModel(model);
listPanel.add(list);
jPanel2.add(listPanel, "list");
jPanel2.add(txtPanel, "text");
//MainUI.getFrames()[0].add(jPanel2, BorderLayout.CENTER);
itemStateChanged("text");
}
Code for itemStateChanged is as follows:
public void itemStateChanged(String disp) {
CardLayout cl = (CardLayout)(jPanel2.getLayout());
cl.show(jPanel2, disp);
}
In the first piece of code, jPanel2 is dragged and dropped onto the frame containing other components, what i am trying to achieve here is that on button click, the jPanel2 should toggle between text field and list. But currently, the panel is not displaying anything on button click.
Before even considering if jPanel2 can switch between the different panels (the different cards), is jPanel2 on display at all anywhere? The only code I can see that displayes the jPanel2 is adding it to the MainUI but it is commented out?! So how do you know that the display inside jPanel2 isn't switching?
I did a quick example code for you .Have a look.You need to define the Card layout as global and try.
import javax.swing.AbstractAction;
public class TestPanel extends JPanel {
/**
* Create the panel.
*/
JPanel panel;
CardLayout cl = new CardLayout();
public TestPanel() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 155, 0, 0};
gridBagLayout.rowHeights = new int[]{94, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, 1.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JButton btnNewButton = new JButton("New button");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 0;
add(btnNewButton, gbc_btnNewButton);
btnNewButton.setAction(new AbstractAction("New button") {
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel txtPanel = new JPanel();
JPanel listPanel = new JPanel();
JTextField txtfield = new JTextField("ABCDEFGHIJ", 20);
txtPanel.add(txtfield);
JList<String> list = new JList<String>();
DefaultListModel<String> model = new DefaultListModel<String>();
for (int i = 0; i < 3; i++){
model.addElement("Sanjaya");
}
list.setModel(model);
listPanel.add(list);
panel.add(listPanel, "list");
panel.add(txtPanel, "text");
//MainUI.getFrames()[0].add(jPanel2, BorderLayout.CENTER);
itemStateChanged("list");
}
});
JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.insets = new Insets(0, 0, 5, 5);
gbc_textArea.fill = GridBagConstraints.BOTH;
gbc_textArea.gridx = 1;
gbc_textArea.gridy = 0;
add(textArea, gbc_textArea);
panel = new JPanel(cl);
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.insets = new Insets(0, 0, 5, 0);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 2;
gbc_panel.gridy = 0;
add(panel, gbc_panel);
}
public void itemStateChanged(String disp) {
cl.show(panel, disp);
}
}