I'm currently building GUI with Java Swing.
My current code produces this.
The JTextArea of Product List makes the GUI looks awkward, how can I make the JTextArea looks like this, where it seems to have an extra row:
The GroupLayout code I'm using is:
gr.setVerticalGroup(gr.createSequentialGroup()
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(productName).addComponent(productText).addComponent(productList))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(amount).addComponent(amountText).addComponent(prodScroll))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(description).addComponent(desScroll))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(addButton).addComponent(remButton)));
gr.setHorizontalGroup(gr.createSequentialGroup()
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(productName).addComponent(amount).addComponent(description).addComponent(addButton))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(productText).addComponent(amountText).addComponent(desScroll).addComponent(remButton))
.addGroup(gr.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(productList).addComponent(prodScroll)));
I think the minority of people would choose to use GridBagLayout. However, I dislike it (among with GroupLayout) since it is "hard to use". I use nested panels instead with various Layout Managers. Using only BorderLayout and GridLayout you can achieve something like the following example, which is totally resizable, giving emphasis to "interaction" components (I mean, there is no reason to resize a constant-texted JLabel, right?)
I did not add any comments in purpose, so you can experiment with constants (and layout constraints) and see their reason of existence while having the documentations opened.
Code:
public class NestedLayoutManagersExample extends JFrame {
private static final long serialVersionUID = -7042997375941726246L;
private static final int labelsWidth = 80;
private static final int textFieldColumns = 15;
private static final int spaceBetweenAllComponents = 10;
public NestedLayoutManagersExample() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = new JPanel(new GridLayout(1, 2, 50, 50));
contentPane.setBorder(BorderFactory.createEmptyBorder(spaceBetweenAllComponents, spaceBetweenAllComponents,
spaceBetweenAllComponents, spaceBetweenAllComponents));
setContentPane(contentPane);
add(createLeftPanel());
add(createRightPanel());
setLocationByPlatform(true);
pack();
}
private Component createRightPanel() {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel productListLabel = new JLabel("Product list");
mainPanel.add(productListLabel, BorderLayout.PAGE_START);
JList<String> productList = new JList<>();
DefaultListModel<String> listModel = new DefaultListModel<>();
Arrays.asList("Small Chair", "Big Chair", "Flying Chair").forEach(listModel::addElement);
productList.setModel(listModel);
JScrollPane listScrollPane = new JScrollPane(productList);
mainPanel.add(listScrollPane, BorderLayout.CENTER);
return mainPanel;
}
private Component createLeftPanel() {
JPanel mainPanel = new JPanel(new BorderLayout(spaceBetweenAllComponents, spaceBetweenAllComponents));
JPanel topPanel = new JPanel(new GridLayout(2, 1, spaceBetweenAllComponents, spaceBetweenAllComponents));
topPanel.add(createStraightPanel("Product Name"));
topPanel.add(createStraightPanel("Amount"));
mainPanel.add(topPanel, BorderLayout.PAGE_START);
JPanel centerPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><p style='width:" + labelsWidth + "px';> Description");
label.setVerticalAlignment(JLabel.TOP);
centerPanel.add(label, BorderLayout.LINE_START);
centerPanel.add(createTextAreaPanel());
mainPanel.add(centerPanel, BorderLayout.CENTER);
return mainPanel;
}
private JPanel createTextAreaPanel() {
JPanel mainPanel = new JPanel(new BorderLayout(spaceBetweenAllComponents, spaceBetweenAllComponents));
JTextArea textArea = new JTextArea(1, textFieldColumns);
JScrollPane textAreaScrollPane = new JScrollPane(textArea);
mainPanel.add(textAreaScrollPane, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel(new BorderLayout());
JButton addButton = new JButton("Add");
buttonsPanel.add(addButton, BorderLayout.LINE_START);
JButton removeButton = new JButton("Remove");
buttonsPanel.add(removeButton, BorderLayout.LINE_END);
mainPanel.add(buttonsPanel, BorderLayout.PAGE_END);
return mainPanel;
}
private Component createStraightPanel(String labelText) {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><p style='width:" + labelsWidth + "px';>" + labelText);
mainPanel.add(label, BorderLayout.LINE_START);
JTextField textField = new JTextField(textFieldColumns);
mainPanel.add(textField, BorderLayout.CENTER);
return mainPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new NestedLayoutManagersExample().setVisible(true));
}
}
Preview:
Related
In want to add a JScrollpane to my stopwatch program, so if the laptime become more and more the scrollpane should show up and allow the user to scroll.
I tried to add the textArea which I want to have in the scrollpane, but it doesn't show a scrollpane.
public class GUI_VA6 implements ActionListener {
private JPanel pan;
private JFrame frame;
private JScrollPane vertical;
private JButton Laptime;
private JButton Start;
private JButton Stop;
private JLabel label;
private JTextArea textArea;
SimpleStopwatch simple = new SimpleStopwatch();
SimpleStopwatch.StopwatchUpdateListener sss;
double ghz;
String lapTimeString;
int countLap=1;
public GUI_VA6() {
frame = new JFrame();
frame.setTitle("Stopwatch");
label = new JLabel("Current time:");
textArea = new JTextArea();
pan = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Laptime = new JButton("Laptime");
Laptime.setEnabled(false);
Start = new JButton("Start");
Stop = new JButton("Stop");
Stop.setVisible(false);
Start.setVisible(true);
Laptime.addActionListener(this);
Start.addActionListener(this);
Stop.addActionListener(this);
pan.add(Laptime);
pan.add(Stop);
pan.add(Start);
frame.add(pan);
vertical=new JScrollPane(textArea);
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
frame.add(vertical);
Container c;
c = frame.getContentPane();
c.setLayout(new java.awt.BorderLayout()); // immer so
c.add(pan, BorderLayout.SOUTH);
c.add(textArea, BorderLayout.CENTER);
c.add(label, BorderLayout.NORTH);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setSize(500, 500);
You are adding your scrollpane to the container (frame.add is equivalent to frame.getContentPane().add), THEN changing the layout manager of the container, which isn't a good idea.
Remove
frame.add(vertical);
And replace
c.add(textArea, BorderLayout.CENTER);
with
c.add(vertical, BorderLayout.CENTER);
I have the GUI displaying properly for the most part, except for one thing. The TitledBorder("Numeric Type") does not display the entire title for the right JPanel. I believe it has something to do with the BorderLayout Manager. Instead of displaying "Numeric Type" within the border, just "Numeric..." displays. Any help will be greatly appreciated.
public class P3GUI extends JFrame {
private JLabel originalList;
private JTextField originalSort;
private JLabel sortedList;
private JTextField newSort;
private JPanel panel;
private JButton performSort;
private JRadioButton ascending;
private JRadioButton descending;
private ButtonGroup sort;
private JRadioButton integer;
private JRadioButton fraction;
private ButtonGroup numType;
private JPanel inputPanel, outputPanel, calculatePanel, radioPanel;
private JPanel left, right;
public P3GUI () {
super("Binary Search Tree Sort");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
originalList = new JLabel("Original List");
originalSort = new JTextField(20);
inputPanel = new JPanel();
inputPanel.add(originalList);
inputPanel.add(originalSort);
sortedList = new JLabel("Sorted List");
newSort = new JTextField(20);
newSort.setEditable(false);
outputPanel = new JPanel();
outputPanel.add(sortedList);
outputPanel.add(newSort);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(inputPanel);
panel.add(outputPanel);
add(panel, BorderLayout.NORTH);
performSort = new JButton("Perform Sort");
calculatePanel = new JPanel();
calculatePanel.add(performSort);
add(calculatePanel, BorderLayout.CENTER);
ascending = new JRadioButton("Ascending");
descending = new JRadioButton("Descending");
sort = new ButtonGroup();
sort.add(ascending);
sort.add(descending);
integer = new JRadioButton("Integer");
fraction = new JRadioButton("Fraction");
numType = new ButtonGroup();
numType.add(integer);
numType.add(fraction);
radioPanel = new JPanel();
radioPanel.setLayout(new FlowLayout());
left = new JPanel();
left.setLayout(new GridLayout(2,1));
left.setBorder(BorderFactory.createTitledBorder("Sort Order"));
left.add(ascending);
left.add(descending);
right = new JPanel();
right.setLayout(new GridLayout(2,1));
right.setBorder(BorderFactory.createTitledBorder("Numeric Type"));
right.add(integer);
right.add(fraction);
radioPanel.add(left);
radioPanel.add(right);
add(radioPanel, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new P3GUI().setVisible(true);
}
});
}
}
The problem is that the right JPanel is too small to display the entire title, and so it gets truncated. I'd suggest placing the bottom two JPanels into another that uses GridLayout, and then place them in such a way that they expand to fit the bottom of your GUI. When spread out, the title has a much greater chance of being fully displayed (but not a guarantee, mind you!).
For example, if you make the main GUI use a BorderLayout, and add this GridLayout using JPanel into the BorderLayout.CENTER position, it will fill it completely. Then the top components, the TextFields and JButton can be added to another JPanel, say one that uses a GridBagLayout, and add that to the main JPanel's BorderLayout.PAGE_START position.
For example, the following code produces this GUI:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class P3GUI2 extends JPanel {
private static final int COLS = 20;
private JTextField originalSort = new JTextField(COLS);
private JTextField newSort = new JTextField(COLS);
private JButton performSort = new JButton("Perform Sort");
private JRadioButton ascending = new JRadioButton("Ascending");
private JRadioButton descending = new JRadioButton("Descending");
private ButtonGroup sort = new ButtonGroup();
private JRadioButton integer = new JRadioButton("Integer");
private JRadioButton fraction = new JRadioButton("Fraction");
private ButtonGroup numType = new ButtonGroup();
public P3GUI2() {
JPanel topPanel = new JPanel(new GridBagLayout());
topPanel.add(new JLabel("Original List:"), createGbc(0, 0));
topPanel.add(originalSort, createGbc(1, 0));
topPanel.add(new JLabel("Sorted List:"), createGbc(0, 1));
topPanel.add(newSort, createGbc(1, 1));
performSort.setMnemonic(KeyEvent.VK_P);
JPanel btnPanel = new JPanel();
btnPanel.add(performSort);
JPanel sortOrderPanel = createTitlePanel("Sort Order");
JPanel numericPanel = createTitlePanel("Numeric Type");
sortOrderPanel.add(ascending);
sortOrderPanel.add(descending);
sort.add(ascending);
sort.add(descending);
numericPanel.add(integer);
numericPanel.add(fraction);
numType.add(integer);
numType.add(fraction);
JPanel radioPanels = new JPanel(new GridLayout(1, 0, 3, 3));
radioPanels.add(sortOrderPanel);
radioPanels.add(numericPanel);
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(topPanel, BorderLayout.PAGE_START);
add(btnPanel, BorderLayout.CENTER);
add(radioPanels, BorderLayout.PAGE_END);
}
private JPanel createTitlePanel(String title) {
JPanel panel = new JPanel(new GridLayout(0, 1, 3, 3));
panel.setBorder(BorderFactory.createTitledBorder(title));
return panel;
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
return gbc;
}
private static void createAndShowGui() {
P3GUI2 mainPanel = new P3GUI2();
JFrame frame = new JFrame("Binary Search Tree Sort");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Or you could place the above btnPanel into the main one BorderLayout.CENTER and then place the radioPanels into the main one BorderLayout.PAGE_END. This will display a GUI of the same appearance but it will expand differently if re-sized.
The preferred size of the panel (as determined by the layout manager) does not consider the size of the text in the TitledBorder so the title can get truncated.
Here is a custom JPanel that can be used with a TitleBorder. The getPreferredSize() method has been customized to use the maximum width of:
the default getPreferredSize() calculation
the width of the text in the TitledBorder
Here is a simple example:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderPanel extends JPanel
{
/**
** The preferred width on the panel must consider the width of the text
** used on the TitledBorder
*/
#Override
public Dimension getPreferredSize()
{
Dimension preferredSize = super.getPreferredSize();
Border border = getBorder();
int borderWidth = 0;
if (border instanceof TitledBorder)
{
Insets insets = getInsets();
TitledBorder titledBorder = (TitledBorder)border;
borderWidth = titledBorder.getMinimumSize(this).width + insets.left + insets.right;
}
int preferredWidth = Math.max(preferredSize.width, borderWidth);
return new Dimension(preferredWidth, preferredSize.height);
}
private static void createAndShowGUI()
{
JPanel panel = new TitledBorderPanel();
panel.setBorder( BorderFactory.createTitledBorder("File Options Command List:") );
panel.setLayout( new BoxLayout(panel, BoxLayout.Y_AXIS) );
panel.add( new JLabel("Open") );
panel.add( new JLabel("Close") );
// panel.add( new JLabel("A really wierd file option longer than border title") );
JFrame frame = new JFrame("TitledBorderPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
I'm trying to get the config panel to take up the top of the screen, and then have the input and output panels side-by-side. I'm also trying to get the text areas to be 70 characters wide each and 30 rows tall. However, right now, the config panel isn't showing up at all, and the text areas are only 35 characters wide and 2 rows tall. I've followed all the examples and tutorials I've found. What am I doing wrong?
public class BorderWrapper {
public static void main(String[] args) {
//Create frame
JFrame frame = new JFrame("Border Wrapper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create main panel
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
//Display frame
Dimension minSize = new Dimension(650, 375);
frame.setPreferredSize(minSize);
frame.setMinimumSize(minSize);
frame.pack();
frame.setVisible(true);
}
}
public class MainPanel extends JPanel {
private static final Font INPUT_FONT = new Font("Monospaced", Font.PLAIN, 12);
private JTextArea inputArea, outputArea;
private JTextField titleField, topBorderField, sideBorderField;
public MainPanel() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Set up config panel
JPanel configPanel = new JPanel();
configPanel.setLayout(new BoxLayout(configPanel, BoxLayout.X_AXIS));
configPanel.setMaximumSize(new Dimension(400, 200));
titleField = new JTextField(25);
titleField.setFont(INPUT_FONT);
topBorderField = new JTextField(1);
topBorderField.setFont(INPUT_FONT);
sideBorderField = new JTextField(4);
sideBorderField.setFont(INPUT_FONT);
configPanel.add(new JLabel("Title:"));
configPanel.add(titleField);
configPanel.add(new JLabel("Top border:"));
configPanel.add(topBorderField);
configPanel.add(new JLabel("Side border:"));
configPanel.add(sideBorderField);
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 0;
add(configPanel, c);
//Set up Input panel
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
inputArea = new JTextArea("Type or paste your stuff here . . .");
inputArea.setFont(INPUT_FONT);
inputArea.setLineWrap(true);
inputArea.setWrapStyleWord(true);
inputArea.setColumns(75);
JScrollPane inputPane = new JScrollPane(inputArea);
inputPane.setMinimumSize(new Dimension(250, 400));
JLabel inputLabel = new JLabel("Text Box");
inputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPanel.add(inputLabel);
inputPanel.add(inputPane);
inputPanel.setMinimumSize(new Dimension(250, 400));
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
add(inputPanel, c);
//Set up Output panel
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
outputArea = new JTextArea();
outputArea.setFont(INPUT_FONT);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setColumns(75);
JScrollPane outputPane = new JScrollPane(outputArea);
outputPane.setMinimumSize(new Dimension(250, 400));
JLabel outputLabel = new JLabel("Wrapped Output");
outputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
outputPanel.add(outputLabel);
outputPanel.add(outputPane);
outputPanel.setMinimumSize(new Dimension(250, 400));
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 1;
add(outputPanel, c);
}
}
Originally, I was going to try to use a BorderLayout, since it seemed that made the most sense for the layout I was trying to make, but that did an even worse job when I set them to BorderLayout.WEST and BorderLayout.EAST.
Have modified your program to use BorderLayout in the MainPanel and few other minor changes to get the desired look and feel.Check if this helps.
public class BorderWrapper {
public static void main(String[] args) {
// Create frame
JFrame frame = new JFrame("Border Wrapper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create main panel
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel);
// Display frame
Dimension minSize = new Dimension(650, 375);
frame.setPreferredSize(minSize);
frame.setMinimumSize(minSize);
frame.pack();
frame.setVisible(true);
}
}
class MainPanel extends JPanel {
private static final Font INPUT_FONT = new Font("Monospaced", Font.PLAIN, 12);
private JTextArea inputArea, outputArea;
private JTextField titleField, topBorderField, sideBorderField;
public MainPanel() {
setLayout(new BorderLayout());
// Set up config panel
JPanel configPanel = new JPanel();
configPanel.setLayout(new BoxLayout(configPanel, BoxLayout.X_AXIS));
configPanel.setMaximumSize(new Dimension(400, 200));
titleField = new JTextField(25);
titleField.setFont(INPUT_FONT);
topBorderField = new JTextField(1);
topBorderField.setFont(INPUT_FONT);
sideBorderField = new JTextField(4);
sideBorderField.setFont(INPUT_FONT);
configPanel.add(new JLabel("Title:"));
configPanel.add(titleField);
configPanel.add(new JLabel("Top border:"));
configPanel.add(topBorderField);
configPanel.add(new JLabel("Side border:"));
configPanel.add(sideBorderField);
add(configPanel, BorderLayout.NORTH);
// Set up Input panel
JPanel lowerPanel = new JPanel(new GridLayout(1, 1));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
inputArea = new JTextArea("Type or paste your stuff here . . .");
inputArea.setFont(INPUT_FONT);
inputArea.setLineWrap(true);
inputArea.setWrapStyleWord(true);
inputArea.setColumns(75);
JScrollPane inputPane = new JScrollPane(inputArea);
JLabel inputLabel = new JLabel("Text Box");
inputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPanel.add(inputLabel);
inputPanel.add(inputPane);
lowerPanel.add(inputPanel);
// Set up Output panel
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
outputArea = new JTextArea();
outputArea.setFont(INPUT_FONT);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setColumns(75);
JScrollPane outputPane = new JScrollPane(outputArea);
JLabel outputLabel = new JLabel("Wrapped Output");
outputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
outputPanel.add(outputLabel);
outputPanel.add(outputPane);
lowerPanel.add(outputPanel);
add(lowerPanel, BorderLayout.CENTER);
}
}
I felt it convenient to use BorderLayout for this format.Anyways, you can still make few changes to the code you posted using GridBagConstraints to get the desired look.Make the below changes one by one and you will observe the differences.
1.You were aligning the MainPanel to the NORTH by using BorderLayout.But in your case the entire set of components is placed in MainPanel,so better place it in center.So instead of NORTH use below :(after this change,you will see the complete input and output panels)
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
2.You have set the dimension of the Parent frame to Dimension(height=375)
minSize = new Dimension(650, 375);
You components(configPanel=200,outputPanel=400) combined height is more than 375.Increase the height of the Parent, to about 600.
3.Instead of BoxLayout try using GridLayout for configPanel.
configPanel.setLayout(new GridLayout(1,6,5,0));
Making the above 3 changes to your existing code will get the expected output.Hope this clarifies.
This is my first post so please forgive me if I am not following the rules correctly.
I am trying to do something relatively simple in Java. I want to make a JTextArea scrollable. I am aware this has been asked before (Java :Add scroll into text area). However, when I follow this example by adding JTextArea to JScrollPane my JTextArea does not become scrollable. What is it that I am missing?
Here is my code:
import ...;
public class MyControlPanel extends JPanel {
//Declare variables
private JComboBox accountsBox;
private String[] accType = {"Current Account", "Savings Account"};
private JLabel selAccType, initDeposit, logLabel, simLabel;
private JTextField depositText;
private JTextArea log;
private JScrollPane scroll;
private JButton createAccount, start, stop;
private JPanel panel1, panel2, panel3, panel4, panel5, panel6;
private Timer timer;
private MyAccount theAccount;
private Random randNum1, randNum2;
private DecimalFormat df;
//Constructor
public MyControlPanel() {
//Create instances:
selAccType = new JLabel("Please select account type: "); //JLabel
initDeposit = new JLabel("Input initial deposit: ");
logLabel = new JLabel("Log:");
simLabel = new JLabel();
accountsBox = new JComboBox(accType); //JComboBox
depositText = new JTextField("0"); // JTextField
log = new JTextArea(); //JTextArea
scroll = new JScrollPane(log); //JScrollPane
createAccount = new JButton("Create Account"); //JButton
start = new JButton("Start");
stop = new JButton("Stop");
panel1 = new JPanel(); //JPanel
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
panel5 = new JPanel();
panel6 = new JPanel();
timer = new Timer(); //Timer
df = new DecimalFormat("#.00");
//Add ActionListeners
createAccount.addActionListener(new ActionListener() {...});
start.addActionListener(new ActionListener() {...});
stop.addActionListener(new ActionListener() {...});
//Set JTextField size
depositText.setColumns(5);
//Set JTextArea size
log.setPreferredSize(new Dimension(780, 150));
//Set panel size
panel1.setPreferredSize(new Dimension(500, 500));
panel2.setPreferredSize(new Dimension(800, 50));
panel3.setPreferredSize(new Dimension(500, 50));
panel4.setPreferredSize(new Dimension(500, 50));
panel5.setPreferredSize(new Dimension(800, 25));
panel6.setPreferredSize(new Dimension(800, 200));
//Set layout in panel5 to align left
panel6.setLayout(new FlowLayout(FlowLayout.LEFT));
//Add components to each panel
addPanels();
//Place objects in the framed window
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.add(panel4);
this.add(panel5);
this.add(panel6);
}
public void addPanels() {...}
public void removePanels() {...}
}
You need to change:
log.setPreferredSize(new Dimension(780, 150));
to:
scroll.setPreferredSize(new Dimension(780, 150));
public class Gridlayout extends JFrame {
public Gridlayout()
{
setTitle("xxx");
setSize(540,635);
this.setResizable(false);
this.setLocation(500,50);
initComponents();
setDefaultCloseOperation(3);
}
JLabel etykieta = new JLabel("Poziom trudności: ");
JPanel top = new JPanel(new GridLayout(2, 2));
JPanel mid = new JPanel(new GridLayout(0, 1));
JPanel bot = new JPanel(new GridLayout(1, 0));
JButton start= new JButton("Start");
JButton zakoncz = new JButton("Zakoncz");
JRadioButton latwy = new JRadioButton("Łatwy");
JRadioButton sredni = new JRadioButton("Średni");
JRadioButton trudny = new JRadioButton("Trudny");
ButtonGroup poziomTrudnosci= new ButtonGroup();
public void initComponents() {
this.getContentPane().add(top, BorderLayout.NORTH);
this.getContentPane().add(mid, BorderLayout.CENTER);
this.getContentPane().add(bot, BorderLayout.SOUTH);
start.setPreferredSize(new Dimension(1, 40));
zakoncz.setPreferredSize(new Dimension(1, 40));
mid.add(etykieta);
mid.add(latwy);
mid.add(sredni);
mid.add(trudny);
bot.add(start);
poziomTrudnosci.add(latwy);
poziomTrudnosci.add(sredni);
poziomTrudnosci.add(trudny);
}
public static void main(String[] args) {
new Gridlayout().setVisible(true);
}
}
How can I move this button from the left to the center of the window? They should stay close. I was trying everything but they still are on the left side.
If I understand your question correctly, you want to horizontally center the JRadioButtons in the JFrame, yes? Try the setHorizontalAlignment() method. Add the following lines to your initComponents() function:
latwy.setHorizontalAlignment(JRadioButton.CENTER);
sredni.setHorizontalAlignment(JRadioButton.CENTER);
trudny.setHorizontalAlignment(JRadioButton.CENTER);