Controlling multiple JPanels visibility in a JFrame - java

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);
}

Related

Java JScrollpane not visible

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);
});
}
}

Replace panels with another

How can I replace a JPanel or JFrame & its contents with another one by a simple button click in the same container ?
here a simple example that you can follow please show code at lest so we can follow your problem this a snap of code from unknowing source (old one)
package layout;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class CardLayoutExample extends JFrame{
JPanel totelPanel,btnPan,showPan;
JButton btn1,btn2;
public static void main(String[] args) {
CardLayoutExample ex = new CardLayoutExample();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.pack();
ex.setLocationRelativeTo(null);
ex.setTitle("BookClube library system");
ex.setVisible(true);
}
public CardLayoutExample(){
btn1 = new JButton("menu button");
btn2 = new JButton("back button");
CardLayout c1 = new CardLayout();
btnPan = new JPanel();
btnPan.add(btn1);
showPan = new JPanel();
showPan.add(btn2);
totelPanel = new JPanel(c1);
totelPanel.add(btn1,"1");
totelPanel.add(btn2,"2");
c1.show(totelPanel,"1");
JPanel fullLayout = new JPanel(new BorderLayout());
fullLayout.add(totelPanel,BorderLayout.NORTH);
add(fullLayout);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
c1.show(totelPanel,"2");
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
c1.show(totelPanel,"1");
}
});
}
}
The trick would be to use CardLayout or modify panel visibility.
Please look at the following example that modifies panel visibility.
public class PanelExample {
private JPanel _myPanel1,_myPanel2;
public void init() {
JFrame frame = new JFrame("Testing");
JPanel mainPanel = new JPanel(new GridBagLayout());
_myPanel1 = new JPanel();
_myPanel1.add(new JLabel("Panel 1"));
_myPanel1.setVisible(true);
_myPanel2 = new JPanel();
_myPanel2.add(new JLabel("Panel 2"));
_myPanel2.setVisible(false);
JButton button = new JButton("Switch to Panel2");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(_myPanel1.isVisible()) {
_myPanel1.setVisible(false);
_myPanel2.setVisible(true);
button.setText("Switch to Panel1");
} else {
_myPanel1.setVisible(true);
_myPanel2.setVisible(false);
button.setText("Switch to Panel2");
}
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.weighty = 0;
mainPanel.add(button,gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 1;
gbc.weighty = 1;
mainPanel.add(_myPanel1,gbc);
mainPanel.add(_myPanel2,gbc);
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
PanelExample exmp = new PanelExample();
exmp.init();
}
}

swing scrollpane setting to textpane

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.

Adding JScrollPane in JTextArea using GridBagLayout

I'm having an issue adding JScrollPane in JTextArea using GridBagLayout. Basically the program runs fine when the scrollbar isn't needed but the layout gets messed up and the content gets cut off when it is. The relevent code is as follows
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class testGUI extends JFrame
{
public static String name;
static JTextField textfield = new JTextField(30);
static JTextArea textarea = new JTextArea(30,30);
public static void main( String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Checkem");
frame.setLocation(500,400);
frame.setSize(800,800);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JScrollPane scrolltxt = new JScrollPane(textarea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrolltxt.setWheelScrollingEnabled(true);
scrolltxt.getVerticalScrollBar().isVisible();
panel.add(scrolltxt, c);
JLabel label = new JLabel("Enter the Name of the file:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,2,2,2);
panel.add(label,c);
c.gridx = 0;
c.gridy = 1;
panel.add(textarea,c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button,c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield,c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
Checkem record = new Checkem();
name = textfield.getText();
String [] print = record.run(name);
for (int i=0;i<print.length;i++)
{
if(print[i] == null || print[i].isEmpty())
{
continue;
}
else
{
textarea.append(print[i] + "\n");
}
}
}
});
}
}
I'm really new to swing and I'm really at a loss where to go from here. Thanks for all your help.
First please learn Java Naming Conventions, that makes it a bit easier for the other person to understand the Java code.
Now to the actual thingy :-)
Why not simply use JTextArea.setLineWrap(true) and
JTextArea.setWrapStyleWord(true) instead of defining JScrollBar policy,
this will even look nice on the view :-)
Moreover, instead of specifying setSize()/setLocation() methods,
simply use frameReference.pack() and
frame.setLocationByPlatform(true), a very wonderful answer
regarding the benefit of the latter is mentioned in this answer, how
to best position Swing GUIs
Do not make so many static fields in a class, this smells like a bad
programming design, and makes your class less extensible.
You are extending JFrame to your TestGUI class and then inside
it's main() method you creating an instance of the same. Actually
again, try to give more weightage to composition over inheritance, since
over here, you not actually trying to modify the already defined
features of JFrame, instead you just using them as is, so there is
no need to extend JFrame in this case atleast :-)
Read about Concurrency in Swing
Here is your modified code :
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class TestGUI {
private String name;
private JTextField textfield = new JTextField(30);
private JTextArea textarea = new JTextArea(30,30);
private void displayGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Checkem");
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
textarea.setLineWrap(true);
textarea.setWrapStyleWord(true);
JScrollPane scrolltxt = new JScrollPane();
scrolltxt.setViewportView(textarea);
scrolltxt.setWheelScrollingEnabled(true);
JLabel label = new JLabel("Enter the Name of the file:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,2,2,2);
panel.add(label,c);
c.gridx = 0;
c.gridy = 1;
panel.add(scrolltxt,c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button,c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield,c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
//frame.setSize(800,800);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/*Checkem record = new Checkem();
name = textfield.getText();
String [] print = record.run(name);
for (int i=0;i<print.length;i++)
{
if(print[i] == null || print[i].isEmpty())
{
continue;
}
else
{
textarea.append(print[i] + "\n");
}
}*/
}
});
}
public static void main( String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new TestGUI().displayGUI();
}
};
EventQueue.invokeLater(r);
}
}
You add the JScrollPane, but then you add the JLabel into the same grid position. Then you add the raw JTextArea without the JScrollPane later.
Try this which only adds the JScrollPane that contains your JTextArea. I also moved your GUI creation into a constructor that is called with a SwingUtilities.invokeLater call to ensure it is on the EDT. See Concurrency in Swing for more details on the EDT. This also allows you to not have all your class member variables static, which is not very good practice.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestGUI extends JFrame {
String name;
JTextField textfield = new JTextField(30);
JTextArea textarea = new JTextArea(30, 30);
public TestGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JScrollPane scrolltxt = new JScrollPane(textarea);
JLabel label = new JLabel("Enter the Name of the file:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2, 2, 2, 2);
panel.add(label, c);
c.gridx = 0;
c.gridy = 1;
panel.add(scrolltxt, c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button, c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield, c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Checkem record = new Checkem();
name = textfield.getText();
String [] print = record.run(name);
for (int i=0;i<print.length;i++) {
if(print[i] == null || print[i].isEmpty()) {
continue;
} else {
textarea.append(print[i] + "\n");
}
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGUI();
}
});
}
}

GUI keyboard simulator

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...
}
}

Categories