I am working on this keyboard simulator, however I am relatively new to GUI and I am stuck at the point where I try to add ActionListener to perform the functionality of the buttons, which means I want the letter appear the input area whenever the a button is pressed.
Thanks in advance!
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class StockTicker extends JFrame implements ActionListener
{
String firstRow[] = {"1","2","3","4","5","6","7","8","9","0"};
String secondRow[] = {"Q","W","E","R","T","Y","U","I","O","P","Del"};
String thirdRow[] = {"A","S","D","F","G","H","J","K","L","Return"};
String fourthRow[] = {"Z","X","C","V","B","N","M","."};
JButton first[];
JButton second[];
JButton third[];
JButton fourth[];
public StockTicker()
{
super ("A Simple Stock Market GUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
initWidgets();
}
private void initWidgets()
{
JLabel jlOutput = new JLabel("Output: ");
JLabel jlInput = new JLabel("Intput: ");
final JLabel jtfOutput = new JLabel("");
final JLabel jtfInput = new JLabel();
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
gbc.anchor = GridBagConstraints.PAGE_START;
JLabel bottomLabel = new JLabel(" Input : ", JLabel.LEFT);
setLayout(new BorderLayout());
JPanel jpNorth = new JPanel();
JPanel jpCenter = new JPanel();
JPanel jpKeyboard = new JPanel();
add( jpNorth, BorderLayout.NORTH);
add( jpCenter, BorderLayout.CENTER);
add(jpKeyboard, BorderLayout.SOUTH);
jpNorth.setLayout(new BorderLayout());
jpNorth.add(jlOutput, BorderLayout.WEST);
jpNorth.add(jtfOutput, BorderLayout.SOUTH);
jpCenter.setLayout( new BorderLayout());
jpCenter.add(jlInput, BorderLayout.WEST);
jpCenter.add(jtfInput, BorderLayout.CENTER);
jpKeyboard.setLayout(new GridLayout(4,1));
pack();
first = new JButton[firstRow.length];
JPanel p = new JPanel(new GridLayout(1, firstRow.length));
for(int i = 0; i < firstRow.length; ++i)
{
first[i] = new JButton(firstRow[i]);
p.add(first[i]);
}
jpKeyboard.add(p);
second = new JButton[secondRow.length];
p = new JPanel(new GridLayout(1, secondRow.length));
for(int i = 0; i < secondRow.length; ++i)
{
second[i] = new JButton(secondRow[i]);
p.add(second[i]);
}
jpKeyboard.add(p);
third = new JButton[thirdRow.length];
p = new JPanel(new GridLayout(1, thirdRow.length));
for(int i = 0; i < thirdRow.length; ++i)
{
third[i] = new JButton(thirdRow[i]);
p.add(third[i]);
}
jpKeyboard.add(p);
fourth = new JButton[fourthRow.length];
p = new JPanel(new GridLayout(1, fourthRow.length));
for(int i = 0; i < fourthRow.length; ++i)
{
fourth[i] = new JButton(fourthRow[i]);
p.add(fourth[i]);
}
jpKeyboard.add(p);
}
JButton.addActionListener(listener);
So you would do something like
MyActionListener listener = new MyActionListener();
.
.
.
first[i] = new JButton(firstRow[i]);
first[i].setActionCommand(firstRow[i]);
first[i].addActionListener(listener);
.
.
.
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
// append the cmd value to your out put...
}
}
Related
I was wondering if there is an easier way to add vertical labels to the game board instead of adding individual Jlabels and moving them. I currently have a single letter set up and when i try to change the font size to anything over 10 font the text will become a small dot or just disaster.
public class View {
private JFrame frameMain;
private JPanel panelBoard;
private JPanel panelTitle;
private JPanel panelMain;
private JPanel panelY;
private JPanel panel2;
private JTextArea text;
private JLabel jlabel;
private JLabel jlabelY;
private List<JButton> list;
public View(){
frameMain = new JFrame();
frameMain.setLayout(new FlowLayout());
list = new ArrayList<>();
panelMain = new JPanel();
panelY = new JPanel();
panelY.setLayout(null);
panelBoard = new JPanel();
panelTitle = new JPanel();
panelMain.setLayout(new BorderLayout());
Board x = new Board();
GridLayout grid = new GridLayout(15,15);
x.createBoard();
panelBoard.setLayout(grid);
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
list.add(new JButton());
}
}
for(JButton x5:list){
panelBoard.add(x5);
}
jlabel = new JLabel("game");
jlabelY = new JLabel("A");
Dimension size = jlabelY.getPreferredSize();
jlabelY.setBounds(17,10 ,size.width,size.height);
jlabelY.setFont(new Font("Ariel", Font.BOLD, 10));
panelTitle.setPreferredSize(new Dimension(50,50));
panelY.setPreferredSize(new Dimension(25,600));
panelBoard.setPreferredSize(new Dimension(400,400));
panelMain.setPreferredSize(new Dimension(600,600));
panelY.add(jlabelY);
panelTitle.add(jlabel);
panelMain.add(panelTitle, BorderLayout.NORTH);
panelMain.add(panelBoard, BorderLayout.CENTER);
panelMain.add(panelY, BorderLayout.WEST);
frameMain.add(panelMain);
frameMain.setSize(600, 600);
frameMain.pack();
frameMain.setVisible(true);
}
You "could" do this using a GridLayout, but where's the fun in that. The following example makes use of GridBagLayout to layout the text and the buttons.
Trying to align components across containers is, well, let's just "hard" and leave it there, for this reason, the row labels and buttons are added to the same container. This ensures that the height of each row is based on the needs of the components within the row.
There's a few other ways you could do this, but this gives you the basic idea.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new View();
}
});
}
public class View {
private JFrame frameMain;
private JPanel panelBoard;
private JPanel panelTitle;
private JPanel panelMain;
private JPanel panel2;
private JTextArea text;
private JLabel jlabel;
private JLabel jlabelY;
private List<JButton> list;
public View() {
frameMain = new JFrame();
frameMain.setLayout(new FlowLayout());
list = new ArrayList<>();
panelMain = new JPanel();
panelBoard = new JPanel();
panelTitle = new JPanel();
panelMain.setLayout(new BorderLayout());
panelBoard.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int y = 0; y < 15; y++) {
gbc.gridx = 0;
gbc.gridy = y;
JLabel rowLabel = new JLabel(Character.toString('A' + y));
rowLabel.setFont(new Font("Ariel", Font.BOLD, 24));
panelBoard.add(rowLabel, gbc);
for (int x = 0; x < 15; x++) {
gbc.gridx++;
JButton btn = new JButton();
list.add(btn);
panelBoard.add(btn, gbc);
}
}
jlabel = new JLabel("game");
panelTitle.add(jlabel);
panelMain.add(panelTitle, BorderLayout.NORTH);
panelMain.add(panelBoard, BorderLayout.CENTER);
frameMain.add(panelMain);
frameMain.pack();
frameMain.setVisible(true);
}
}
}
How do I add a break to put my "Make pokemon" buttons and textarea not in the same row as my "Pokemon choice." I'm trying to put an empty JLabel, but I don't think it works.
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton(" Make Pokemon ");
private JButton bClear = new JButton(" Clear ");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel();
private JPanel bottomSubPanel = new JPanel();
private GUIListener listener = new GUIListener();
private Choice chSpe = new Choice();
private JLabel lEmp = new JLabel(" ");
private PokemonGUILizylf st;
private final int capacity = 10;
private PokemonGUILizylf[ ] stArr = new PokemonGUILizylf[capacity];
private int count = 0;
private String sOut = new String("");
private JTextArea textArea = new JTextArea(400, 500);
private JTextArea textArea2 = new JTextArea(400, 500);
private JScrollPane scroll = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lEmp = new JLabel(" ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
chSpe.add("Choose");
chSpe.add("Bulbasaur");
chSpe.add("Venusaur");
chSpe.add("Ivysaur");
chSpe.add("Squirtle");
chSpe.add("Wartortle");
chSpe.add("Blastoise");
chSpe.add("Charmander");
chSpe.add("Charmeleon");
chSpe.add("Charizard");
centerSubPanel.add(lSpe);
centerSubPanel.add(chSpe);
centerSubPanel.add(lEmp);
centerSubPanel.add(bDone);
centerSubPanel.add(lNew);
textArea.setPreferredSize(new Dimension(500, 200));
textArea.setEditable(false);
textArea2.setPreferredSize(new Dimension(500, 200));
textArea2.setEditable(false);
textArea.setBackground(Color.white);
textArea.setEditable(false);
scroll.setBorder(null);
centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
bottomSubPanel.add(lMsg);
bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
This is what my GUI looks like:
enter image description here
But it should show like this:
enter image description here
Can someone explain to me how I can do that?
Use a different layout manager (other then default FlowLayout which JPanel uses)
See Laying Out Components Within a Container for more details.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new PokemonPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
// private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton("Make Pokemon ");
private JButton bClear = new JButton("Clear");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel(new GridBagLayout());
private JPanel bottomSubPanel = new JPanel();
// private GUIListener listener = new GUIListener();
private JComboBox<String> chSpe = new JComboBox<>();
private JLabel lEmp = new JLabel(" ");
// private PokemonGUILizylf st;
private final int capacity = 10;
// private PokemonGUILizylf[] stArr = new PokemonGUILizylf[capacity];
// private int count = 0;
// private String sOut = new String("");
// private JTextArea textArea = new JTextArea(400, 500);
// private JTextArea textArea2 = new JTextArea(400, 500);
//
// private JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
// JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
// this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
DefaultComboBoxModel<String> chSpeModel= new DefaultComboBoxModel<>();
chSpeModel.addElement("Choose");
chSpeModel.addElement("Bulbasaur");
chSpeModel.addElement("Venusaur");
chSpeModel.addElement("Ivysaur");
chSpeModel.addElement("Squirtle");
chSpeModel.addElement("Wartortle");
chSpeModel.addElement("Blastoise");
chSpeModel.addElement("Charmander");
chSpeModel.addElement("Charmeleon");
chSpeModel.addElement("Charizard");
chSpe.setModel(chSpeModel);
centerSubPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.LINE_END;
centerSubPanel.add(lSpe, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
centerSubPanel.add(chSpe);
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy++;
centerSubPanel.add(bDone, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
centerSubPanel.add(lNew, gbc);
gbc.gridx++;
gbc.gridheight = gbc.REMAINDER;
centerSubPanel.add(new JScrollPane(new JTextArea(10, 10)), gbc);
// textArea.setEditable(false);
// textArea2.setEditable(false);
//
// textArea.setBackground(Color.white);
// textArea.setEditable(false);
// scroll.setBorder(null);
// centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
// scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
// bottomSubPanel.add(lMsg);
// bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
// bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
}
}
Also, avoid using setPreferredSize, let the layout managers do their job. In the example I'm used insets (from GridBagConstraints) and an EmptyBorder to add some additional space around the components
Also, be careful of using AWT components (ie Choice), they don't always play nicely with Swing. In this case, you should be using JComboBox
I'm trying to display a series of buttons in a JScrollpane. Reading around, I managed to exit with this code, but nothing is displayed. I do not understand a possible mistake. Thank you for help
As suggested I made some changes, I edited but not works
EDITED
or I'm stupid, or here is some other problem. Here is my complete code with the output image
public class Main extends javax.swing.JFrame {
private final JPanel gridPanel;
public Main() {
initComponents();
// EXISTING PANEL
gridPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane(gridPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel borderLayoutPanel = new JPanel(new BorderLayout());
borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);
this.Avvio();
}
private void Avvio() {
JPanel pane = new JPanel(new GridBagLayout());
pane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
pane.setLayout(new GridBagLayout());
for (int i = 0; i < 10; i++) {
JButton button;
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
button = new JButton("Button 1");
c.weightx = 0.5;
c.gridx = 0;
c.gridy = i;
pane.add(button, c);
button = new JButton("Button 2");
c.gridx = 1;
c.gridy = i;
pane.add(button, c);
button = new JButton("Button 3");
c.gridx = 2;
c.gridy = i;
pane.add(button, c);
}
gridPanel.add(pane);
gridPanel.revalidate();
gridPanel.repaint();
}
}
Alright, from your comments in another answer:
No problem for compile , simply the Jpanel is empty. The buttons does not appear.
After calling this.Avvio(); you must call:
this.add(scrollPane);
this.pack();
This will produce the following outputs (before and after resizing it):
But there's still no JScrollPanel
This at least solves the first problem, however you have more errors in your code, some of which have already been commented in other answers:
You're extending JFrame, this isn't needed as you can create a JFrame instance / object and use it later. You're never changing the JFrame's behavior and that's why it's not needed to extend it. See Extends JFrame vs. creating it inside the program for more information about this.
You're not calling pack() nor setSize(...) this creates a tiny window, which you need to manually resize. Call pack() recommended before making your JFrame visible. (As suggested at the beginning of this answer).
You're calling .invokeLater() method twice. You need to call it just once, I prefer this way:
SwingUtilities.invokeLater(() -> new Main()); //Note there is no call to .setVisible(true); as per point #1. It should go later in the program like: frame.setVisible(true);
You're calling gridPanel.revalidate(); and gridPanel.repaint() while it doesn't affect your program, it's not needed as your GUI is still not visible, and thus those calls have no effect on your program, you can safely remove them.
You're creating a new GridBagConstraints object on each iteration of the for loop, you can just change its properties inside it and declaring it outside the for loop, which will make your program better.
After following the above recommendations, you can end up with a code like this one:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class Main {
private final JPanel gridPanel;
private JFrame frame;
public Main() {
// EXISTING PANEL
gridPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane(gridPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel borderLayoutPanel = new JPanel(new BorderLayout());
borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);
this.Avvio();
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
private void Avvio() {
JPanel pane = new JPanel(new GridBagLayout());
pane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
pane.setLayout(new GridBagLayout());
for (int i = 0; i < 10; i++) {
JButton button;
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
button = new JButton("Button 1");
c.weightx = 0.5;
c.gridx = 0;
c.gridy = i;
pane.add(button, c);
button = new JButton("Button 2");
c.gridx = 1;
c.gridy = i;
pane.add(button, c);
button = new JButton("Button 3");
c.gridx = 2;
c.gridy = i;
pane.add(button, c);
}
gridPanel.add(pane);
}
public static void main(String args[]) {
/* Create and display the form */
SwingUtilities.invokeLater(() -> {
new Main();
});
}
}
Which still produces this output:
BUT... We still can improve it a little more!
We may have two nested for loops, for the GridBagConstraints properties as well as the generation of the buttons:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class ScrollablePaneWithButtons {
private static final int ROWS = 10;
private static final int COLS = 3;
private JFrame frame;
private JPanel pane;
private JButton[][] buttons;
private GridBagConstraints gbc;
private JScrollPane scroll;
private JButton[] menuButtons;
private JPanel menuPane;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ScrollablePaneWithButtons()::createAndShowGui);
}
private void createAndShowGui() {
frame = new JFrame(this.getClass().getSimpleName());
pane = new JPanel();
pane.setLayout(new GridBagLayout());
menuPane = new JPanel();
menuPane.setLayout(new GridLayout(1, 3));
buttons = new JButton[ROWS][COLS];
menuButtons = new JButton[] {new JButton("Edit"), new JButton("Delete"), new JButton("Sort Fields")};
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.weightx = 0.5;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
buttons[i][j] = new JButton("Button " + (j + 1));
gbc.gridx = j;
gbc.gridy = i;
pane.add(buttons[i][j], gbc);
}
}
scroll = new JScrollPane(pane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
for (JButton b : menuButtons) {
menuPane.add(b);
}
frame.add(scroll);
frame.add(menuPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And this example is (in my opinion) easier to read and follow up. And this is the output the above code is generating:
You can still choose which code to use, either doing the modifications at the first part of this answer, the second one following the recommendations above or the last one which is shorter.
Problems noted:
Avvio - the pane layout was reset during each loop. Set it once before the loop.
Avvio - the pane was added to the grid pane in each loop. Add it once after the loop.
Avvio - the constraints place the buttons in the same grid locations. With the previous two issues fixed, only the last three buttons placed appear.
I'm assuming you want three buttons in a row, so I changed the loop to use the counter as a row counter. The code below will create ten rows of three buttons.
What appears:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class Main extends javax.swing.JFrame {
private JPanel gridPanel;
public Main() {
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(600,400);
//EXISTING PANEL
gridPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane(gridPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel borderLayoutPanel = new JPanel(new BorderLayout());
borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);
this.Avvio();
this.add(borderLayoutPanel, BorderLayout.CENTER);
this.setVisible(true);
}
private void Avvio() {
JPanel pane = new JPanel(new GridBagLayout());
pane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
pane.setLayout(new GridBagLayout());
for (int i = 0; i < 10; i++) {
JButton button;
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
button = new JButton("Button 1");
c.weightx = 0.5;
c.gridx = 0;
c.gridy = i;
pane.add(button, c);
button = new JButton("Button 2");
c.gridx = 1;
c.gridy = i;
pane.add(button, c);
button = new JButton("Button 3");
c.gridx = 2;
c.gridy = i;
pane.add(button, c);
}
gridPanel.add(pane);
gridPanel.revalidate();
gridPanel.repaint();
}
public static void main(String args[]) {
new Main();
}
}
There are several things to do to make it work:
Add a main method
This main method is the entry point. This makes sure the swing-code runs in the AWT-thread. This is what the SwingUtilities.invokeLater is for
Instantiate, pack and display the frame. The size setting is only for experimenting with the scrollpane
Declare the gridPanel as an instance variable
wrap the gridPanel with the scrollPane
Optionally, wrap the scrollPane with the borderLayoutPanel
Invoke the Avvio method because this is the one that adds the buttons
Add the outmost element to the frame
Here is the fixed code:
public class MyFrame extends javax.swing.JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MyFrame frame = new MyFrame();
frame.pack();
frame.setSize(600, 300);
frame.setVisible(true);
});
}
private JPanel gridPanel;
public MyFrame() {
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
gridPanel = new JPanel(new GridLayout(0, 1));
JScrollPane scrollPane = new JScrollPane(gridPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel borderLayoutPanel = new JPanel(new BorderLayout());
borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);
this.Avvio();
this.add(borderLayoutPanel, BorderLayout.CENTER);
}
private void Avvio() {...}
}
I have simplified the program and removed all the mistakes
and bad practices. (Missing package, unnecessary panels, calling invokeLater() twice and others.)
Here is a working example:
package com.zetcode;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JavaScrollPaneEx extends JFrame {
public JavaScrollPaneEx() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = createButtonPanel();
JScrollPane scrollPane = new JScrollPane(buttonPanel);
panel.add(scrollPane, BorderLayout.CENTER);
add(panel);
setTitle("Buttons in JScrollBar");
setSize(350, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.insets = new Insets(5, 5, 5, 5);
for (int i = 0, j = 0; i < 5; i++) {
JButton btn = new JButton("Button " + (j + 1));
c.weightx = 0.5;
c.gridx = i;
c.gridy = 0;
panel.add(btn, c);
btn = new JButton("Button " + (j + 2));
c.gridx = i;
c.gridy = 1;
panel.add(btn, c);
btn = new JButton("Button " + (j + 3));
c.gridx = i;
c.gridy = 2;
panel.add(btn, c);
j += 3;
}
return panel;
}
public static void main(String args[]) {
EventQueue.invokeLater(() -> {
JavaScrollPaneEx ex = new JavaScrollPaneEx();
ex.setVisible(true);
});
}
}
And this is the screenshot.
And since I consider GridBagLayout to be a very bad
layout manager, I have created a similar example with MigLayout
manager.
We need the following Maven dependency for this example:
<dependency>
<groupId>com.miglayout</groupId>
<artifactId>miglayout-swing</artifactId>
<version>5.0</version>
</dependency>
The source:
package com.zetcode;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;
public class JavaScrollPaneEx2 extends JFrame {
public JavaScrollPaneEx2() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = createButtonPanel();
JScrollPane scrollPane = new JScrollPane(buttonPanel);
panel.add(scrollPane, BorderLayout.CENTER);
add(panel);
setTitle("Buttons in JScrollBar");
setSize(350, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new MigLayout());
for (int i = 0, j = 0; i < 5; i++) {
JButton btn1 = new JButton("Button " + (j + 1));
JButton btn2 = new JButton("Button " + (j + 2));
JButton btn3 = new JButton("Button " + (j + 3));
JButton btn4 = new JButton("Button " + (j + 4));
JButton btn5 = new JButton("Button " + (j + 5));
panel.add(btn1, "sgx");
panel.add(btn2, "sgx");
panel.add(btn3, "sgx");
panel.add(btn4, "sgx");
panel.add(btn5, "sgx, wrap");
j += 5;
}
return panel;
}
public static void main(String args[]) {
EventQueue.invokeLater(() -> {
JavaScrollPaneEx2 ex = new JavaScrollPaneEx2();
ex.setVisible(true);
});
}
}
below is my code that are adding few swing components to frame.I m using two textpane and setting some text to both.But text is large and only textpane is visible when i run the code.so i tried to add scrollpane to textpane ta2 but then also nothing happens.scrollpane doesnot appear around textpane ta2.What is the mistake
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
public class Test1 {
public Test1() {
String a="vdnogregnroei dfnoj";
JFrame frm = new JFrame("frontend");
JLabel l1= new JLabel("Enter name of text file");
JLabel l2= new JLabel("Enter name of text file");
final JTextField t1=new JTextField(15);
final JTextField t2=new JTextField(15);
JTextPane ta2=new JTextPane();
JLabel l3=new JLabel("SIMILARITY");
JLabel l4=new JLabel("DIFFERENCES");
JTextPane ta1=new JTextPane();
JScrollPane sp2=new JScrollPane(ta2);
frm.getContentPane().add(sp2);
JButton b1=new JButton("COMPARE");
frm.setLayout(new GridBagLayout());
Container cont=frm.getContentPane();
GridBagConstraints cnt=new GridBagConstraints();
cnt.fill=GridBagConstraints.HORIZONTAL;
cnt.insets=new Insets(10,10,10,10);
cnt.gridx=1;
cnt.gridy=1;
cont.add(l1,cnt);
cnt.gridx=2;
cnt.gridy=1;
cont.add(t1,cnt);
cnt.gridx=1;
cnt.gridy=2;
cont.add(l2,cnt);
cnt.gridx=2;
cnt.gridy=2;
cont.add(t2,cnt);
cnt.gridx=1;
cnt.gridy=3;
cont.add(l3,cnt);
cnt.gridx=2;
cnt.gridy=3;
cont.add(ta1,cnt);
cnt.gridx=1;
cnt.gridy=4;
cont.add(l4,cnt);
cnt.gridx=2;
cnt.gridy=4;
cont.add(ta2,cnt);
cnt.gridx=1;
cnt.gridy=5;
cont.add(b1,cnt);
ta1.setContentType("text/html");
ta1.setText("sbdiu sdjj<b>bjksd</b>"+a+"<br/>dnsaod<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>vsdnono");
ta2.setContentType("text/html");
ta2.setText("sbdiu sdjj<b>bjksd</b>"+a+"<br/>dnsaod<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>vsdnono");
frm.pack();
frm.setVisible(true);
}
public static void main(String[] args)
{
Test1 obj=new Test1();
}
}
You need to add the JTextPane to the JScrollPane and then add the JScrollPane to the JFrame (or its content pane):
public class Test1 {
public Test1() {
JFrame frm = new JFrame("frontend");
JLabel l1 = new JLabel("Enter name of text file");
JLabel l2 = new JLabel("Enter name of text file");
JLabel l3 = new JLabel("SIMILARITY");
JLabel l4 = new JLabel("DIFFERENCES");
JTextField t1 = new JTextField(15);
JTextField t2 = new JTextField(15);
JTextPane ta1 = new JTextPane();
JTextPane ta2 = new JTextPane();
ta1.setContentType("text/html");
ta2.setContentType("text/html");
String a = "vdnogregnroei dfnoj";
ta1.setText(a);
ta2.setText(a);
JScrollPane sp1 = new JScrollPane(ta1);
JScrollPane sp2 = new JScrollPane(ta2);
JButton b1 = new JButton("COMPARE");
Container cont = frm.getContentPane();
cont.setLayout(new GridBagLayout());
GridBagConstraints cnt = new GridBagConstraints();
cnt.fill = GridBagConstraints.HORIZONTAL;
cnt.insets = new Insets(10, 10, 10, 10);
cnt.gridx = 0;
cnt.gridy = 0;
cont.add(l1, cnt);
cnt.gridx = 1;
cnt.gridy = 0;
cont.add(t1, cnt);
cnt.gridx = 0;
cnt.gridy = 1;
cont.add(l2, cnt);
cnt.gridx = 1;
cnt.gridy = 1;
cont.add(t2, cnt);
cnt.gridx = 0;
cnt.gridy = 2;
cont.add(l3, cnt);
cnt.gridx = 1;
cnt.gridy = 2;
// cnt.weightx = 1;
// cnt.weighty = 1;
cont.add(sp1, cnt);
cnt.gridx = 0;
cnt.gridy = 3;
// cnt.weightx = 0;
// cnt.weighty = 0;
cont.add(l4, cnt);
cnt.gridx = 1;
cnt.gridy = 3;
cont.add(sp2, cnt);
cnt.gridx = 0;
cnt.gridy = 4;
cont.add(b1, cnt);
frm.pack();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
public static void main(String[] args) {
new Test1();
}
}
I will advise you to look carefully at the differences between this code and yours. Notice where I set the layout and what components I add.
Notes:
I commented out some lines that hint you about resizing behavior.
You probably want to call setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) on the frame.
The grid starts from x=0 and y=0, not x=1 and y=1.
So what I want to do is create multiple jpanels of the different menus that i need. At first, only the visibility of the main menu is set to true. Then depending on which buttons I click, i can go to different menus by turning off the visibility of the previous menu and turning on the visibility of the current one. It's not working though, and I think it's with the way I add my JPanels. Any quick fix to this?
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import com.opencsv.CSVWriter;
public class justawindow extends JFrame{
public static void main (String[] args){
justawindow w = new justawindow();
}
//JPanels
JPanel mainMenu = new JPanel();
JPanel createUserMenu = new JPanel();
JPanel loginUserMenu = new JPanel();
//mainMenu stuff
JButton createMenu = new JButton("Create new user");
JButton loginMenu = new JButton("Login");
//createUserMenu stuff
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
JTextField realname = new JTextField(15);
JButton backFromCreateUser = new JButton("Back");
JButton createUser = new JButton("Create new user");
JLabel usernameLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
JLabel realnameLabel = new JLabel("Real name:");
JButton login = new JButton("Login");
JButton backFromLoginUser = new JButton ("Back");
public justawindow(){
createMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
mainMenu.setVisible(false);
createUserMenu.setVisible(true);
}
});
loginMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
mainMenu.setVisible(false);
loginUserMenu.setVisible(true);
}
});
GridBagLayout g1 = new GridBagLayout();
GridBagConstraints c1 = new GridBagConstraints();
mainMenu.setLayout(g1);
c1.gridx = 0;
c1.gridy = 0;
mainMenu.add(createMenu,c1);
c1.gridy = 1;
mainMenu.add(loginMenu,c1);
mainMenu.setVisible(true);
GridBagLayout g2 = new GridBagLayout();
GridBagConstraints c2 = new GridBagConstraints();
createUserMenu.setLayout(g2);
c2.gridx = 0;
c2.gridy = 0;
createUserMenu.add(usernameLabel,c2);
c2.gridx = 1;
createUserMenu.add(username,c2);
c2.gridx = 0;
c2.gridy = 1;
createUserMenu.add(passwordLabel,c2);
c2.gridx = 1;
createUserMenu.add(password,c2);
c2.gridx = 0;
c2.gridy = 2;
createUserMenu.add(realnameLabel,c2);
c2.gridx = 1;
createUserMenu.add(realname,c2);
c2.gridx = 0;
c2.gridy = 3;
createUserMenu.add(createUser,c2);
c2.gridy = 4;
createUserMenu.add(backFromCreateUser,c2);
createUserMenu.setVisible(false);
GridBagLayout g3 = new GridBagLayout();
GridBagConstraints c3 = new GridBagConstraints();
loginUserMenu.setLayout(g3);
c3.gridx = 0;
c3.gridy = 0;
loginUserMenu.add(usernameLabel,c3);
c3.gridx = 1;
loginUserMenu.add(username,c3);
c3.gridx = 0;
c3.gridy = 1;
loginUserMenu.add(passwordLabel,c3);
c3.gridx = 1;
loginUserMenu.add(password,c3);
c3.gridx = 0;
c3.gridy = 2;
loginUserMenu.add(login,c3);
c3.gridy = 3;
loginUserMenu.add(backFromLoginUser,c3);
loginUserMenu.setVisible(false);
this.add(createUserMenu);
this.add(loginUserMenu);
this.add(mainMenu);
setSize(400,500);
setTitle("Bomberman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
The following code may help you
JPanel mainMenu = new JPanel();
createUserMenu.setVisible(false);
JPanel createUserMenu = new JPanel();
createUserMenu.setVisible(false);
JPanel loginUserMenu = new JPanel();
loginUserMenu.setVisible(false);
ActionPerformed
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn1)
{
mainMenu.setVisible(true);
createUserMenu.setVisible(false);
loginUserMenu.setVisible(false);
}
else if(e.getSource()==btn2)
{
mainMenu.setVisible(false);
createUserMenu.setVisible(true);
loginUserMenu.setVisible(false);
}
else if(e.getSource()==btn3)
{
mainMenu.setVisible(false);
createUserMenu.setVisible(false);
loginUserMenu.setVisible(true);
}
}
This is not a complete solution, Just an Example
Using arrayLists
components1 = new ArrayList<Component>();
components1.add(label11);
components1.add(label12);
to set visibility
panel1.setVisible(true);
for (Component component1 : components1) {
component1.setVisible(true);
}
panel2.setVisible(false);
for (Component component2 : components2) {
component2.setVisible(false);
}
panel3.setVisible(false);
for (Component component : components3) {
component.setVisible(false);
}