I am trying to make a simple gui window with images.
Here's my code:
import java.awt.*;
import javax.swing.*;
public class Image extends JFrame
{
private ImageIcon [] image = new ImageIcon[10];
private JLabel [] label = new JLabel[10];
Image()
{
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
for(int i=0; i<10; i++)
{
for(int j = 0; j<10;j++)
{
image[i] = new ImageIcon(getClass().getResource((i+1) +".jpg"));
label[i] = new JLabel (image[i]);
c.fill = GridBagConstraints.REMAINDER;
c.gridx = j;
c.gridy = i;
add(label[i]);
}
}
}
public static void main(String[] args)
{
Image i = new Image();
i.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
i.setVisible(true);
i.pack();
i.setTitle("My Title");
}
}
What I am trying to do is after the counter exits the inner loop, it should go on a new line in the window.
But i get the whole thing in the same line. Any suggestions?
You need to pass the constraints as a parameter when adding the labels:
add(label[i], c);
instead of
add(label[i]);
Not directly related to the problem, but you should create the GUI in the event dispatch thread; also, call setVisible(true) on the frame only after it is otherwise ready.
Related
I am a computer scientist in my first year of my apprenticeship.
In the beginning we started with procedural Java programming, now we have to learn the object oriented Java. To begin with that, we have to program a GUI with some features and something to save some Strings like in a Database.
Anyway, I'm not there yet. I'm still stuck at creating and Structure the GUI. It has everything inside that it needs, but the structure I'm trying to get does not really work.
So here's what I got:
TestGUI.Java
import javax.swing.*;
public class TestGui {
public static void main(String[] args){
ModulGui GUI = new ModulGui();
ImageIcon img = new ImageIcon("icon.png");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(250,350);
GUI.setIconImage(img.getImage());
GUI.setLocationByPlatform(true);
GUI.setResizable(false);
GUI.setVisible(true);
}
}
ModulGui.java
import javax.swing.*;
import java.awt.*;
import java.security.PrivateKey;
public class ModulGui extends JFrame {
private final JLabel LabelModulID;
private final JLabel LabelModulName;
private final JLabel LabelStartDatum;
private final JTextField TextFeldModulId;
private final JTextField TextFeldModulName;
private final JTextField TextFeldStartDatum;
private final JButton ButtonHinzufuegen;
private final JButton ButtonEntfernen;
private final JButton ButtonAlleAusgeben;
public ModulGui(){
super("Modulliste");
setLayout(new FlowLayout());
GridBagConstraints GuiGrid = new GridBagConstraints();
LabelModulID = new JLabel("Modul ID");
LabelModulID.setToolTipText("Bitte Modul ID eintragen.");
GuiGrid.gridx = 0;
GuiGrid.gridy = 1;
add(LabelModulID);
LabelModulName = new JLabel("Modulname");
LabelModulName.setToolTipText("Bitte Modulnamen eintragen");
GuiGrid.gridx = 0;
GuiGrid.gridy = 2;
add(LabelModulName);
LabelStartDatum = new JLabel("Startdatum");
LabelStartDatum.setToolTipText("Startdatum des Moduls eintragen");
GuiGrid.gridx = 0;
GuiGrid.gridy = 3;
add(LabelStartDatum);
TextFeldModulId = new JTextField(25);
GuiGrid.gridx = 0;
GuiGrid.gridy = 4;
add(TextFeldModulId);
TextFeldModulName = new JTextField(25);
GuiGrid.gridx = 0;
GuiGrid.gridy = 5;
add(TextFeldModulName);
TextFeldStartDatum = new JTextField(25);
GuiGrid.gridx = 0;
GuiGrid.gridy = 6;
add(TextFeldStartDatum);
ButtonHinzufuegen = new JButton("Hinzufügen");
GuiGrid.gridx = 0;
GuiGrid.gridy = 7;
add(ButtonHinzufuegen);
ButtonEntfernen = new JButton("Entfernen");
GuiGrid.gridx = 0;
GuiGrid.gridy = 8;
add(ButtonEntfernen);
ButtonAlleAusgeben = new JButton("Alle Ausgeben");
GuiGrid.gridx = 0;
GuiGrid.gridy = 9;
add(ButtonAlleAusgeben);
}
}
Sorry Maybe the Problem is really easy, but like I said I'm pretty new to programing :D
I also tried it with setBounds and setLayout(null)... Well didn't really work either.
I want to structure my Code as the following:
LabelModulID
TextFeldModulID
LabelModulName
TextFeldModulName
LabelStartDatum
TextFeldStartDatum
ButtonHinzufuegen
ButtonEntfernen
ButtonAlleAusgeben
Do you guys have an idea of how I could do this?
And does someone know how I could use Objects or something else to store some Modules (Module) like in a Database. Like the class Modulelist and Module.
Thank you guys in advance!!
//Edit//
So that's the new code I got with your help. It doesn't look good, but it isn't bad for the second attempt:
import javax.swing.*;
import java.awt.*;
import java.security.PrivateKey;
public class ModulGui extends JFrame {
public final JPanel panelModulID = new JPanel();
public final JPanel panelModulName = new JPanel();
public final JPanel panelStartDatum = new JPanel();
public final JPanel panelButtons = new JPanel();
private final JLabel LabelModulID;
private final JLabel LabelModulName;
private final JLabel LabelStartDatum;
private final JTextField TextFeldModulId;
private final JTextField TextFeldModulName;
private final JTextField TextFeldStartDatum;
private final JButton ButtonHinzufuegen;
private final JButton ButtonEntfernen;
private final JButton ButtonAlleAusgeben;
public ModulGui(){
super("Modulliste");
setLayout(new FlowLayout(FlowLayout.CENTER));
LabelModulID = new JLabel("Modul ID");
LabelModulID.setToolTipText("Bitte Modul ID eintragen.");
panelModulID.add(LabelModulID);
LabelModulName = new JLabel("Modulname");
LabelModulName.setToolTipText("Bitte Modulnamen eintragen");
panelModulName.add(LabelModulName);
LabelStartDatum = new JLabel("Startdatum");
LabelStartDatum.setToolTipText("Startdatum des Moduls eintragen");
panelStartDatum.add(LabelStartDatum);
TextFeldModulId = new JTextField(25);
panelModulID.add(TextFeldModulId);
TextFeldModulName = new JTextField(25);
panelModulName.add(TextFeldModulName);
TextFeldStartDatum = new JTextField(25);
panelStartDatum.add(TextFeldStartDatum);
ButtonHinzufuegen = new JButton("Hinzufügen");
panelButtons.add(ButtonHinzufuegen);
ButtonEntfernen = new JButton("Entfernen");
panelButtons.add(ButtonEntfernen);
ButtonAlleAusgeben = new JButton("Alle Ausgeben");
panelButtons.add(ButtonAlleAusgeben);
add(panelModulID);
add(panelModulName);
add(panelStartDatum);
add(panelButtons);
}
}
And it gets me this:
Ok, i'll try to do it with a layout Manager... Which one did you use? I would have tried with GroupLayout.
Ah, therein lies a common error. Few, if any, good layouts are created using a single layout. Instead we usually combine them to create the needed GUI.
Take this layout for example:
It uses a GridBagLayout for the 'outer' part, but then puts a (JPanel with a) FlowLayout in the last row of that GBL to hold the buttons.
Here is the code used to put it together:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class GUILayout {
private JComponent ui = null;
GUILayout() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(4,4,4,4));
addLabelAndField("Module ID", 5, 0);
addLabelAndField("Module Name", 15, 1);
addLabelAndField("Start Datum", 10, 2);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 3;
gbc.gridwidth = 2;
JPanel p = new JPanel();
ui.add(p, gbc);
p.add(new JButton("Hinzufuegen"));
p.add(new JButton("Entfernen"));
p.add(new JButton("Alle Ausgeben"));
}
private void addLabelAndField(String labelText, int fieldWidth, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,5,5,5);
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
ui.add(new JLabel(labelText), gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.WEST;
ui.add(new JTextField(fieldWidth), gbc);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
GUILayout o = new GUILayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
At the moment, you're adding your GUI components directly to the JFrame. Instead, you need a JPanel to hold all your GUI components and then add that JPanel to your JFrame
For example:
JPanel panel = new JPanel();
panel.add(button1);
panel.add(button2);
panel.add(label1);
add(panel); // Adds panel to the JFrame
If you want to play around with specific layouts, you can check out the Java tutorials. There's also more information on how to use a JPanel in the Java documentation.
Hi guys I'm using Eclipse and I'm trying to create a Connect4 Game Grid , which is an JPanel gridArray [6] [7]. I later add the different Panels for buttons and the grid into a main panel and add it into my frame.
My Problem:
I want to fill the gridArray JPanel with Pictures of an empty field(white color) but first of all i want to create a new Panel and insert it into my gridArray through a loop until gridArray has all 42 Panels inside it and is fully filled. I have my Code below but somehow it doesnt work, although my logic should be fine.
I tried it with using a helper Function to create a new JPanel and call the function for each loop in fillGrid();, basically calling it 42 times but it still wont work...
I will gladly appreciate some help!
package connect4;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GridTest extends JFrame {
JFrame mainWindow;
JPanel buttonPanel, mainPanel;
JPanel gridPanel;
JPanel emptyPanel;
JPanel panel1;
ImageIcon emptyBox;
JPanel[][] gridArray;
JLabel emptyLabel;
JButton arrow1,arrow2,arrow3,arrow4,arrow5,arrow6,arrow7;
public GridTest() {
createGameGrid();
fillGrid();
}
public void createGameGrid() {
//creating window and mainpanel
mainWindow = new JFrame("Connect 4");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
//defining top panel with 7 buttons;
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 7));
arrow1 = new JButton("V");
arrow2 = new JButton("V");
arrow3 = new JButton("V");
arrow4 = new JButton("V");
arrow5 = new JButton("V");
arrow6 = new JButton("V");
arrow7 = new JButton("V");
buttonPanel.add(arrow1);
buttonPanel.add(arrow2);
buttonPanel.add(arrow3);
buttonPanel.add(arrow4);
buttonPanel.add(arrow5);
buttonPanel.add(arrow6);
buttonPanel.add(arrow7);
//create Grind Panel
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(6,7));
mainPanel.add(buttonPanel, BorderLayout.NORTH);
mainPanel.add(gridPanel, BorderLayout.SOUTH);
mainWindow.add(mainPanel);
mainWindow.pack();
mainWindow.setLocationRelativeTo(null);
mainWindow.setVisible(true);
}
private JPanel greateOnePanel(){
//here we need to insert the icon which is in empty box into a newly created panel
//ifirst wanted to insert black panels do ensure it works as intended but it doesnt
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setSize(50,50);
return panel;
}
//here we need to fill the grid with the panels created above from left to right...
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
gridPanel.add(greateOnePanel());
}
}
}
public static void main(String[] args) {
new GridTest();
}
}
i tried it with this method using gridArray, but it throws NullPointer Exeptions and wont fill the grid with simple textlabels "Hallo" (just for testing purposes)
public void fillGrid() {
for(int j = 0; j < 6; j++) {
for (int k = 0; k < 7; k++) {
JLabel label = new JLabel("Hallo");
gridArray[j][k] = new JPanel();
gridArray[j][k].setSize(50, 50);
gridArray[j][k].setBackground(Color.RED);
gridArray[j][k].add(label);
gridPanel.add(gridArray[j][k]);
}
}
}
Here is a short, self contained, code that should help with various aspects of the task.
There is no need for a panel in each cell. The only thing it helped with was setting a BG color. That can be done in a label as long as the background is set to opaque.
This code defines a SquareLabel which overrides getPreferredSize() to return the maximum of preferred width and height as the value of both (usually it is the width).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class SquareLabelGrid {
int rows = 6;
int cols = 7;
JLabel[][] labelArray = new JLabel[cols][rows];
Font bigFont = new Font(Font.SANS_SERIF, Font.BOLD, 30);
Insets labelInsets;
SquareLabelGrid() {
JPanel gameBoard = new JPanel(new GridLayout(rows, cols));
// a border to make the cell boundaries more clear and add
// some space around the text
Border border = new CompoundBorder(
new LineBorder(Color.BLACK),new EmptyBorder(4,4,4,4));
for (int yy = 0; yy < rows; yy++) {
for (int xx = 0; xx < cols; xx++) {
JLabel l = getColoredSquareLabel(xx, yy);
labelArray[xx][yy] = l;
gameBoard.add(l);
l.setBorder(border);
}
}
JOptionPane.showMessageDialog(null, gameBoard);
}
private JLabel getColoredSquareLabel(int x, int y) {
SquareLabel label = new SquareLabel(
String.format("%1s,%1s", (x+1), (y+1)));
label.setFont(bigFont);
label.setOpaque(true); // so we can see the BG color
label.setBackground(Color.ORANGE); // I prefer orange!
// make the GUI less 'crowded'
label.setBorder(new EmptyBorder(4,4,4,4));
return label;
}
public static void main(String[] args) {
Runnable r = () -> {
new SquareLabelGrid();
};
SwingUtilities.invokeLater(r);
}
}
class SquareLabel extends JLabel {
SquareLabel(String label) {
super(label);
}
/* This will create a square component that accounts for the
size of the String / Icon it contains. No guesswork! */
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int w = d.width;
int h = d.height;
int sz = w > h ? w : h;
return new Dimension(sz, sz);
}
}
The problem is that you have not initialized the grid array .
Otherwise it will throw Null pointer exception.
JPanel[][] gridArray = new JPanel[6][8];
Also set the preferred size of main panel to make the grids visible .
mainPanel.setPreferredSize(new Dimension(400, 200));
Here is what i can see when I run your code with the modifications mentioned here .
Also please execute it from main with following code .
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GridTest();
}
});
}
In my project, I have got a class FramesUtil which contains a set of frames stored in a HashMap -
ConcurrentHashMap<Integer, Frame> frameMap
I have another class Arbiter.java that should render video using frames from frameMap.
However, I can only see the first frame when the playVideo() method is being called from Arbiter.java.
public static void main(String[] args) {
try {
FramesUtil.ensureExistence();
FrameReader reader = new FrameReader();
reader.readBinary();
playVideo();
} catch (Exception e) {
e.printStackTrace();
}
}
Looks like the JFrame is not getting updated with new BufferedImage in the loop during the iteration
Below is my playVideo method from Arbiter.java -
public static void playVideo() {
BufferedImage img;
JFrame frame = new JFrame();
GridBagLayout gLayout = new GridBagLayout();
frame.getContentPane().setLayout(gLayout);
JLabel lbIm1;
for(int i=0; (img=FramesUtil.frameMap.get(i).bufferedImage)!=null; i++) {
lbIm1 = new JLabel(new ImageIcon(img));
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
System.out.println(lbIm1);
frame.getContentPane().add(lbIm1, c);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
PS. I have tried creating new JFrame and GridBagLayout instances inside the for loop
I'm new to Java programming. Can you help me with the layout of my first application (which is a simple calculator) please?
Here's the code I wrote:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class InputPad extends JFrame {
private JLabel statusLabel;
private JTextArea expTextArea;
InputPad() {
prepareGUI();
}
private void prepareGUI(){
JFrame mainFrame = new JFrame("My Calculator");
mainFrame.setSize(450,450);
mainFrame.setLayout(new GridLayout(3,2));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
JLabel headerLabel = new JLabel("Put your expression here:", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
expTextArea = new JTextArea("1+(2^3*4)");
//Digits Panel
JPanel digitPanel = new JPanel();
GroupLayout layoutDigits = new GroupLayout(digitPanel);
digitPanel.setLayout(layoutDigits);
layoutDigits.setAutoCreateGaps(true);
layoutDigits.setAutoCreateContainerGaps(true);
//Operators Panel
JPanel operatorPanel = new JPanel();
GroupLayout layoutOperators = new GroupLayout(operatorPanel);
operatorPanel.setLayout(layoutOperators);
layoutOperators.setAutoCreateGaps(true);
layoutOperators.setAutoCreateContainerGaps(true);
JButton[] numButtons= new JButton[10];
int i;
for (i=0;i<10;i++){
numButtons[i] = new JButton(Integer.toString(i));
numButtons[i].addActionListener(e -> {
// TODO
});
}
JButton bEquals = new JButton("=");
bEquals.addActionListener(e -> {
// TODO
});
JButton bPlus = new JButton("+");
bPlus.addActionListener(e -> {
// TODO
});
JButton bMinus = new JButton("-");
bMinus.addActionListener(e -> {
// TODO
});
JButton bMultiply = new JButton("*");
bMultiply.addActionListener(e -> {
// TODO
});
JButton bDivide = new JButton("/");
bDivide.addActionListener(e -> {
// TODO
});
JButton bLeftParenthesis = new JButton("(");
bLeftParenthesis.addActionListener(e -> {
// TODO
});
JButton bRightParenthesis = new JButton(")");
bRightParenthesis.addActionListener(e -> {
// TODO
});
JButton bPower = new JButton("^");
bPower.addActionListener(e -> {
// TODO
});
JButton bDel = new JButton("←");
bDel.addActionListener(e -> {
// TODO
});
layoutDigits.setHorizontalGroup(
layoutDigits.createSequentialGroup()
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numButtons[7])
.addComponent(numButtons[4])
.addComponent(numButtons[1])
.addComponent(numButtons[0]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numButtons[8])
.addComponent(numButtons[5])
.addComponent(numButtons[2])
.addComponent(bEquals))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numButtons[9])
.addComponent(numButtons[6])
.addComponent(numButtons[3]))
);
layoutDigits.setVerticalGroup(
layoutDigits.createSequentialGroup()
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[7])
.addComponent(numButtons[8])
.addComponent(numButtons[9]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[4])
.addComponent(numButtons[5])
.addComponent(numButtons[6]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[1])
.addComponent(numButtons[2])
.addComponent(numButtons[3]))
.addGroup(layoutDigits.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(numButtons[0])
.addComponent(bEquals))
);
layoutOperators.setHorizontalGroup(
layoutOperators.createSequentialGroup()
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(bPlus)
.addComponent(bMinus)
.addComponent(bLeftParenthesis)
.addComponent(bPower))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(bMultiply)
.addComponent(bDivide)
.addComponent(bRightParenthesis)
.addComponent(bDel))
);
layoutOperators.setVerticalGroup(
layoutOperators.createSequentialGroup()
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bPlus)
.addComponent(bMultiply))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bMinus)
.addComponent(bDivide))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bLeftParenthesis)
.addComponent(bRightParenthesis))
.addGroup(layoutOperators.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bPower)
.addComponent(bDel))
);
mainFrame.add(headerLabel);
mainFrame.add(expTextArea);
mainFrame.add(digitPanel);
mainFrame.add(operatorPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
}
I tried the GridLayout for my JFrame, but I couldn't resize and of my JComponent except the main JFrame. Even I can't place two JPanels (side by side) in one cell of the GridLayout or expand a JLabel to two cells of the GridLayout.
This is what I got:
And here's what I want:
Let's start from the use of Layout Managers, from the link on the part of GridLayout
GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns
So, this isn't what you want, but if you read the GridBagLayout part it says:
GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths.
We can combine both of them, along with a BoxLayout and you will get a similar output to what you're trying to achieve:
PLEASE NOTE:
Before posting the code, take note of the following tips:
You're extending JFrame and at the same time you're creating a JFrame object, this is discouraged, remove one of them, in this case as you're using the object and this is the recommended thing to do, simply remove the extends JFrame from your class. If you really need to extend something, don't extend JFrame but a JPanel instead.
Place your program inside the EDT, as I did in the main() method
Don't use System.exit(0); instead call setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) as shown in the above code
And now the code
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class CalculatorExample {
private JFrame frame;
private JTextArea area;
private JButton[][] digitsButtons, symbolsButtons;
private String[][] digitsText = {{"7", "8", "9"}, {"4", "5", "6"}, {"1", "2", "3"}, {"0", "="}}; //Looks strange but this will make the button adding easier
private String[][] symbolsText = {{"+", "*"}, {"-", "/"}, {"(", ")"}, {"^", "←"}};
private JPanel buttonsPane, areaAndResultsPane, digitsPane, symbolsPane;
private JLabel label;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CalculatorExample().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame("Calculator Example");
area = new JTextArea();
area.setRows(5);
area.setColumns(20);
label = new JLabel("Results go here");
digitsButtons = new JButton [4][3];
symbolsButtons= new JButton [4][2];
areaAndResultsPane = new JPanel();
areaAndResultsPane.setLayout(new BoxLayout(areaAndResultsPane, BoxLayout.PAGE_AXIS));
buttonsPane = new JPanel();
buttonsPane.setLayout(new GridLayout(1, 2, 10, 10));
digitsPane = new JPanel();
digitsPane.setLayout(new GridBagLayout());
symbolsPane = new JPanel();
symbolsPane.setLayout(new GridLayout(4, 2));
GridBagConstraints c = new GridBagConstraints();
for (int i = 0; i < digitsText.length; i++) {
for (int j = 0; j < digitsText[i].length; j++) {
digitsButtons[i][j] = new JButton(digitsText[i][j]);
}
}
for (int i = 0; i < symbolsText.length; i++) {
for (int j = 0; j < symbolsText[i].length; j++) {
symbolsButtons[i][j] = new JButton(symbolsText[i][j]);
}
}
areaAndResultsPane.add(area);
areaAndResultsPane.add(label);
boolean shouldBreak = false;
for (int i = 0; i < digitsButtons.length; i++) {
for (int j = 0; j < digitsButtons[i].length; j++) {
c.gridx = j;
c.gridy = i;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
if (i == 3) {
if (j == 1) {
c.gridwidth = 2; //This makes the "=" button larger
shouldBreak = true;
}
}
digitsPane.add(digitsButtons[i][j], c);
if (shouldBreak) {
break;
}
}
}
for (int i = 0; i < symbolsButtons.length; i++) {
for (int j = 0; j < symbolsButtons[i].length; j++) {
symbolsPane.add(symbolsButtons[i][j]);
}
}
frame.add(areaAndResultsPane, BorderLayout.NORTH);
buttonsPane.add(digitsPane);
buttonsPane.add(symbolsPane);
frame.add(buttonsPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This was done nesting JPanels, each with a different layout, I hope it helps you to continue from here.
According to the Oracle documentation :
Each component takes all the available space within its cell, and each cell is exactly the same size.
So sadly, you can't resize any components inside a GridLayout.
You could instead use a GridBagLayout. It is a little bit more complicated to understand but offers more features. I let you make some tests with the documentation to get in touch with it !
I want to have a for loop, that can implement and add a specified number of JButtons the one after the other. I was trying to implement it and this is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ArrayForm extends JFrame implements ActionListener
{
JPanel numPanel = new JPanel();
JPanel opPanel = new JPanel();
JTextField textField = new JTextField(25);
JButton [] buttons = new JButton[10];
JButton [] OPbuttons = new JButton[6];
String num="";
String [] operation = {"+","-","*","/","=","C"};
public static void main(String[] args)
{ArrayForm fobject = new ArrayForm();}
public ArrayForm()
{
setLayout(new FlowLayout());
setSize(400,300);
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
numPanel.setPreferredSize(new Dimension(180,150));
numPanel.setLayout(new FlowLayout());
opPanel.setPreferredSize(new Dimension(200,70));
opPanel.setLayout(new FlowLayout());
for (int i = 0; i<10; i++)
{
//The code in here
}
for (int i = 0; i<6; i++)
{
//The code in here
}
add(textField);
this.textField.setEditable(false);
add(numPanel);
add(opPanel);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
}
Can you please help me with for loop part? where the first one is buttons array, and the second one is for OPbuttons array.
Your for loop part might be as follows:
for (int i = 0; i<10; i++)
{
buttons[i] = new JButton(""+i);
numPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
for (int i = 0; i<6; i++)
{
OPbuttons[i] = new JButton(operation[i]);
opPanel.add(OPbuttons[i]);
OPbuttons[i].addActionListener(this);
}
What i have understood, is that you are trying to add the buttons of a calculator automatically, within two different panels...
NB: don't forget to add the code for your Action Listener.