Unable to add make JTextArea show multiplie lines insidea JScrollPane - java

I am trying to make multiple lines of a JTextArea visible.I am using GridBagLayout to add the components. Here is a code snippet:
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
public class SSCE {
SSCE(){
JFrame f1=new JFrame();
GridBagLayout gbl=new GridBagLayout();
JButton btnAddAcc=new JButton("Add Acount");
JButton insertId=new JButton("Insert");
JButton insertTweet=new JButton("Insert2");
JButton tweetButton=new JButton("TweetButton");
JLabel accountStatusHeader=new JLabel("account status Header");
JLabel accountDisplayNameHeader=new JLabel("account displayname Header");
JLabel enterInterval=new JLabel("enter Interval!!");
final JTextArea accountDispName = new JTextArea(50, 50);
final JTextArea statusDisplay = new JTextArea(50, 50);
final JTextArea jTextAreaId = new JTextArea(20, 50);
final JTextArea jTextAreaTweets = new JTextArea(20, 50);
jTextAreaId.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
Color.PINK, Color.GREEN));
final JTextArea tweetLog = new JTextArea(100, 100);
tweetLog.setPreferredSize(new Dimension(1000, 5000));
JScrollPane tweetLogPaneScroll = new JScrollPane(tweetLog);
JScrollPane idScrollPane = new JScrollPane(jTextAreaId);
JScrollPane tweetScrollPane = new JScrollPane(jTextAreaTweets);
final JTextField timeIntervalInput = new JTextField(20);
final JTextField tagIdInsertTextBox = new JTextField(50);
final JTextField tweetInsertTextBox = new JTextField(50);
f1.setLayout(gbl);
f1.add(btnAddAcc,makeGbc(0,0,1,2));
f1.add(accountDisplayNameHeader,makeGbc(1,0));
f1.add(accountStatusHeader,makeGbc(1,1));
f1.add(accountDispName,makeGbc(2,0));
f1.add(statusDisplay,makeGbc(2,1));
f1.add(enterInterval,makeGbc(3,0));
f1.add(timeIntervalInput,makeGbc(3,1));
f1.add(new JLabel("Twitter Ids"),makeGbc(4,0));
f1.add(new JLabel("Tweets"),makeGbc(4,1));
f1.add(idScrollPane,makeGbc(5,0,5));
f1.add(tweetScrollPane,makeGbc(5,1,5));
f1.add(tagIdInsertTextBox,makeGbc(10,0));
f1.add(tweetInsertTextBox,makeGbc(10,1));
f1.add(insertId,makeGbc(11,0));
f1.add(insertTweet,makeGbc(11,1));
f1.add(tweetButton,makeGbc(12,0,1,2));
f1.add(tweetLogPaneScroll,makeGbc(13,0,6,2));
f1.setSize(800,400);
f1.setVisible(true);
f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
accountDispName.setVisible(false);
statusDisplay.setVisible(false);
}
private GridBagConstraints makeGbc(int y, int x) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
// gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x,int gridheight) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x,int gridheight,int gridwidth) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
public static void main(String args[]){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SSCE a1;
a1 = new SSCE();
}
});
}
}
Please note the following lines:
f1.add(idScrollPane,makeGbc(5,0,5));
f1.add(tweetScrollPane,makeGbc(5,1,5));
In above, I am passing the third paramenter(the gridheight) as 5 but still I see only one row. I want to set the row span to 5.
And Also the following:
f1.add(tweetLogPaneScroll,makeGbc(13,0,6,2));
Here again, I am passing the third param(gridheight) as 6.But yet I see only one Row of textarea. So what is going wrong?? And whats the solution?

Your SSCCE helps me to see everything -- thanks! I've voted to open your question and have up-voted it. You're killing yourself with your unrealistic JTextArea row numbers, and then setting the size of your GUI. Get rid of all setSize(...) and setPreferredSize(...) method calls. Make your JTextArea row counts 5 or 10, not 50, not 100. Call pack() before setVisible(true).
For example, please see the changes I've made below as well as comments with !! in them. Note that I've tried to get rid of most of your magic numbers, but you still need to do the same with the column counts. I've also added text to your text components for the sake of debugging, so that I can see at a glance which text component goes with which variable. You'll of course not want to have this text present in the presentation code, but again, it's a useful debugging tool:
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
public class SSCE {
private static final int SMALL_ROWS = 5; // !! was 20!
private static final int BIG_ROWS = 10; // !! was 50!
SSCE() {
JFrame f1 = new JFrame();
GridBagLayout gbl = new GridBagLayout();
JButton btnAddAcc = new JButton("Add Acount");
JButton insertId = new JButton("Insert");
JButton insertTweet = new JButton("Insert2");
JButton tweetButton = new JButton("TweetButton");
JLabel accountStatusHeader = new JLabel("account status Header");
JLabel accountDisplayNameHeader = new JLabel(
"account displayname Header");
JLabel enterInterval = new JLabel("enter Interval!!");
final JTextArea accountDispName = new JTextArea("accountDispName JTA",
BIG_ROWS, 50);
final JTextArea statusDisplay = new JTextArea("statusDisplay JTA",
BIG_ROWS, 50);
final JTextArea jTextAreaId = new JTextArea("jTextAreaId JTA",
SMALL_ROWS, 50);
final JTextArea jTextAreaTweets = new JTextArea("jTextAreaTweets JTA",
SMALL_ROWS, 50);
jTextAreaId.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
Color.PINK, Color.GREEN));
final JTextArea tweetLog = new JTextArea("tweetLog JTA", BIG_ROWS, 100); // was
// 100!
// !! tweetLog.setPreferredSize(new Dimension(1000, 5000));
JScrollPane tweetLogPaneScroll = new JScrollPane(tweetLog);
JScrollPane idScrollPane = new JScrollPane(jTextAreaId);
JScrollPane tweetScrollPane = new JScrollPane(jTextAreaTweets);
final JTextField timeIntervalInput = new JTextField(
"timeIntervalInput JTF", 20);
final JTextField tagIdInsertTextBox = new JTextField(
"tagIdInsertTextBox JTF", 50);
final JTextField tweetInsertTextBox = new JTextField(
"tweetInsertTextBox JTF", 50);
f1.setLayout(gbl);
f1.add(btnAddAcc, makeGbc(0, 0, 1, 2));
f1.add(accountDisplayNameHeader, makeGbc(1, 0));
f1.add(accountStatusHeader, makeGbc(1, 1));
f1.add(accountDispName, makeGbc(2, 0));
f1.add(statusDisplay, makeGbc(2, 1));
f1.add(enterInterval, makeGbc(3, 0));
f1.add(timeIntervalInput, makeGbc(3, 1));
f1.add(new JLabel("Twitter Ids"), makeGbc(4, 0));
f1.add(new JLabel("Tweets"), makeGbc(4, 1));
f1.add(idScrollPane, makeGbc(5, 0, 5));
f1.add(tweetScrollPane, makeGbc(5, 1, 5));
f1.add(tagIdInsertTextBox, makeGbc(10, 0));
f1.add(tweetInsertTextBox, makeGbc(10, 1));
f1.add(insertId, makeGbc(11, 0));
f1.add(insertTweet, makeGbc(11, 1));
f1.add(tweetButton, makeGbc(12, 0, 1, 2));
f1.add(tweetLogPaneScroll, makeGbc(13, 0, 6, 2));
// !! f1.setSize(800, 400);
f1.pack(); // !!
f1.setVisible(true);
f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
accountDispName.setVisible(false);
statusDisplay.setVisible(false);
}
private GridBagConstraints makeGbc(int y, int x) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
// gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
System.out.printf("gridwidth, gridheight: [%d, %d]%n", gbc.gridwidth,
gbc.gridheight);
return gbc;
}
private GridBagConstraints makeGbc(int y, int x, int gridheight) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x, int gridheight,
int gridwidth) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SSCE a1;
a1 = new SSCE();
}
});
}
}
This results in a GUI that looks like so:
Note, I would also change the GridBagConstraints for JTextFields from BOTH to HORIZONTAL.
Edit
You state in comment:
One more question if u dont mind answering.the TimeIntervalInput is appearing so wide although I have defined it to hold at max 20 chars.Any solution to that?
You need to continue to play with your grid bag constraints as the ones you're using are quite restrictive. For example, note what happens when I use more exacting constraints on the GBC for that JTextField:
GridBagConstraints gbc = makeGbc(3, 1);
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
f1.add(timeIntervalInput, gbc);

Related

Make components immune to GridBagConstrains.fill in GridBagLayout

I have a little Java swing GUI with a GridBagLayout. I have set the GridBagConstraints.fill = GridBagConstraints.BOTH but don't want that my buttons or text fields to get resized vertically. Furthermore, I only want my JTextArea to be resized and tried putting in maximum size for the components I don't want to size up, but it is not working. Any ideas on how I can make the GBC.fill only applicable for some components?
Reproducible example:
public class Main {
static JFrame frame = new JFrame("Create New Entry");
static JPanel wrapper = new JPanel();
static JTextField title = new JTextField(20);
static JLabel titleLabel = new JLabel("Title");
static JTextField username = new JTextField(20);
static JLabel usernameLabel = new JLabel("Username");
static JTextField email = new JTextField(20);
static JLabel emailLabel = new JLabel("Email Address");
static JPasswordField password = new JPasswordField(20);
static JLabel passwordLabel = new JLabel("Password");
static JButton generatePassword = new JButton("Generate Password");
static JPasswordField confirmPassword = new JPasswordField();
static JLabel confirmPasswordLabel = new JLabel("Confirm Password");
static JToggleButton showPassword = new JToggleButton("Show Password");
static JButton submit = new JButton("Submit Entry");
static JLabel notesLabel = new JLabel("Notes");
static JTextArea textArea = new JTextArea(5, 0);
static JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public static void main(String[] args) {
GridBagConstraints gbc = new GridBagConstraints();
wrapper.setLayout(new GridBagLayout());
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 10, 10);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
wrapper.add(titleLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
wrapper.add(title, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
wrapper.add(usernameLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
wrapper.add(username, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 2;
wrapper.add(emailLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
wrapper.add(email, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 3;
wrapper.add(passwordLabel, gbc);
gbc.gridx = 1;
wrapper.add(password, gbc);
gbc.gridx = 2;
wrapper.add(generatePassword, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 4;
wrapper.add(confirmPasswordLabel, gbc);
gbc.gridx = 1;
wrapper.add(confirmPassword, gbc);
gbc.gridx = 2;
wrapper.add(showPassword, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
wrapper.add(notesLabel, gbc);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 1;
gbc.gridwidth = 2;
wrapper.add(scrollPane, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 3;
gbc.gridy = 6;
wrapper.add(submit, gbc);
password.setPreferredSize(new Dimension(300, 26));
confirmPassword.setPreferredSize(new Dimension(300, 26));
title.setPreferredSize(new Dimension(300, 26));
username.setPreferredSize(new Dimension(300, 26));
email.setPreferredSize(new Dimension(300, 26));
frame.add(wrapper);
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Any ideas on how I can make the GBC.fill only applicable for some components?
Yes. Don't have all components use a GridBagConstraints object whose fill field is .BOTH. Each component should be added with its own GBC object, and the ones you want filled both horizontally and vertically should have the fill property set to .BOTH, and the components that should only expand horizontally should have GBC fill field of .HORIZONTAL. When I use the GridBagLayout, I often create helper method(s) for creating constraint objects, methods that know what settings to use based on parameters passed into them, and I suggest that you consider doing the same.
As Abra mentions, yes, you can modify a GridBagConstraints (GBC) object, by changing the settings of one or more fields as necessary, and I sometimes do this too, but more often, I use helper methods to create GBC objects on the fly. It just works better for me that way.
For example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class Main2 extends JPanel {
private static final long serialVersionUID = 1L;
private static final int FIELD_COLS = 20;
private static final int TA_ROWS = 10;
private static final int INGS_GAP = 10;
private JLabel titleLabel = new JLabel("Title");
private JLabel userNameLabel = new JLabel("Username");
private JLabel emailAddrLabel = new JLabel("EmailAddress");
private JLabel passwordLabel = new JLabel("Password");
private JLabel confirmPasswordLabel = new JLabel("Confirm Password");
private JLabel notesLabel = new JLabel("Notes");
private JTextField titleField = new JTextField(FIELD_COLS);
private JTextField userNameField = new JTextField(FIELD_COLS);
private JTextField emailField = new JTextField(FIELD_COLS);
private JPasswordField passwordField = new JPasswordField(FIELD_COLS);
private JPasswordField confirmPasswordField = new JPasswordField(FIELD_COLS);
private JTextArea NotesArea = new JTextArea(TA_ROWS, FIELD_COLS);
private JScrollPane textAreaScrollPane = new JScrollPane(NotesArea);
private JButton generatePasswordBtn = new JButton("Generate Password");
private JButton showPasswordBtn = new JButton("Show Password");
private JButton submitEntryBtn = new JButton("Submit Entry");
public Main2() {
setLayout(new GridBagLayout());
// basic GBC use
int row = 0;
GridBagConstraints gbc = createGbc(0, row, GridBagConstraints.HORIZONTAL);
add(titleLabel, gbc);
gbc = createGbc(1, row, GridBagConstraints.HORIZONTAL, 2, 1);
add(titleField, gbc);
row++;
gbc = createGbc(0, row, GridBagConstraints.HORIZONTAL);
add(userNameLabel, gbc);
gbc = createGbc(1, row, GridBagConstraints.HORIZONTAL, 2, 1);
add(userNameField, gbc);
row++;
gbc = createGbc(0, row, GridBagConstraints.HORIZONTAL);
add(emailAddrLabel, gbc);
gbc = createGbc(1, row, GridBagConstraints.HORIZONTAL, 2, 1);
add(emailField, gbc);
row++;
gbc = createGbc(0, row, GridBagConstraints.HORIZONTAL);
add(passwordLabel, gbc);
gbc = createGbc(1, row, GridBagConstraints.HORIZONTAL);
add(passwordField, gbc);
gbc = createGbc(2, row, GridBagConstraints.HORIZONTAL);
add(generatePasswordBtn, gbc);
row++;
gbc = createGbc(0, row, GridBagConstraints.HORIZONTAL);
add(confirmPasswordLabel, gbc);
gbc = createGbc(1, row, GridBagConstraints.HORIZONTAL);
add(confirmPasswordField, gbc);
gbc = createGbc(2, row, GridBagConstraints.HORIZONTAL);
add(showPasswordBtn, gbc);
// here we set the GBC weighty to non-0 value to allow vertical expansion
// of added components
row++;
int txtAreaRows = TA_ROWS;
gbc = createGbc(0, row, GridBagConstraints.HORIZONTAL);
gbc.anchor = GridBagConstraints.WEST;
gbc.weighty = 1.0;
add(notesLabel, gbc);
gbc = createGbc(1, row, GridBagConstraints.BOTH, 2, txtAreaRows);
gbc.weighty = 1.0;
add(textAreaScrollPane, gbc);
textAreaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
row += txtAreaRows;
gbc = createGbc(0, row, GridBagConstraints.HORIZONTAL);
add(new JLabel(""), gbc);
gbc = createGbc(1, row, GridBagConstraints.HORIZONTAL, 2, 1);
add(submitEntryBtn, gbc);
}
private static GridBagConstraints createGbc(int x, int y, int fill, int width, int height) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.fill = fill;
// allow horizontal expansion *unless* at left-most position in row
gbc.weightx = x == 0 ? 0.0 : 1.0;
gbc.weighty = 0.0; // default to no vertical expansion
gbc.insets = new Insets(INGS_GAP, INGS_GAP, INGS_GAP, INGS_GAP);
return gbc;
}
private static GridBagConstraints createGbc(int x, int y, int fill) {
return createGbc(x, y, fill, 1, 1);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Main2 mainPanel = new Main2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

Check if a slot of a GridBayLayout is empty

Suppose you have a panel initialized like so
JPanel panel_playerBuffs = new JPanel();
panel_playerBuffs.setBounds(249, 165, 71, 227);
panel_playerBuffs.setOpaque(false);
panel_playerBuffs.setLayout(new GridBagLayout());
getContentPane().add(panel_playerBuffs);
And its layout is GridBayLayout with the following constraints
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 1;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
panel_playerBuffs.add(new JLabel("located at 1, 3"), gbc);
As you can see, this adds a JLabel at (1, 1) and another one at (1, 3). Now I'm trying to add a conditional somewhere else in the program to check whether or not there's a label at a given position. For instance, I would like to find out if the position (1, 2) has a label (in this case it doesn't). What method should I use for this?
How about using the GridBagLayout#getLayoutDimensions()
If the width or height of the given position is 0, there is empty.
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
public class GridBayLayoutSlotTest {
private JComponent makeUI() {
GridBagLayout layout = new GridBagLayout();
JPanel panel_playerBuffs = new JPanel();
panel_playerBuffs.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 1;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
gbc.gridx = 3;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 3, 1"), gbc);
EventQueue.invokeLater(() -> {
int[][] a = layout.getLayoutDimensions();
System.out.println(Arrays.deepToString(a));
System.out.format("isEmpty(%d, %d): %s%n", 2, 1, isEmpty(a, 2, 1));
System.out.format("isEmpty(%d, %d): %s%n", 3, 1, isEmpty(a, 3, 1));
});
return panel_playerBuffs;
}
private static boolean isEmpty(int[][] a, int x, int y) {
int[] w = a[0];
int[] h = a[1];
return w[x] == 0 || h[y] == 0;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new GridBayLayoutSlotTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

GUI won't display two seperate scrollpanes

As you can see in my code, there are two scroll panes at the bottom. I need my gui to show both of these scroll panes on the right side, the smaller one(displaying the current amount of money the player has, this one I need to stay one line thick) and the second one, which will be constantly spitting out information of the player's rolls on the bottom.
Also how do I make it so that my combo box listener will give every item a 10 to its output to start out with then when it is being sent out it gives each 1 more so that they have their unique number starting at 11 then 12, 13, and so on.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class dicebot extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JComboBox combo;
private JButton btnConfirm;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dicebot frame = new dicebot();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public dicebot() {
setTitle("Dice Bot");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
//Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
JLabel userTag = new JLabel("Username:");
GridBagConstraints gbc_userTag = new GridBagConstraints();
gbc_userTag.insets = new Insets(0, 0, 0, 5);
gbc_userTag.anchor = GridBagConstraints.EAST;
gbc_userTag.gridx = 0;//Here are your x + y coords
gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
panel.add(userTag, gbc_userTag);
//Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel startTag = new JLabel("Starting Bid:");
GridBagConstraints gbc_startTag = new GridBagConstraints();
gbc_startTag.insets = new Insets(0, 0, 0, 5);
gbc_startTag.anchor = GridBagConstraints.EAST;
gbc_startTag.gridx = 0;
gbc_startTag.gridy = 2;
panel.add(startTag, gbc_startTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldStartBid = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 2;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel multTag = new JLabel("Multiplier:");
GridBagConstraints gbc_multTag = new GridBagConstraints();
gbc_multTag.insets = new Insets(0, 0, 0, 5);
gbc_multTag.anchor = GridBagConstraints.EAST;
gbc_multTag.gridx = 0;
gbc_multTag.gridy = 3;
panel.add(multTag, gbc_multTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMultiplier = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel minTag = new JLabel("Min Remaining:");
GridBagConstraints gbc_minTag = new GridBagConstraints();
gbc_minTag.insets = new Insets(0, 0, 0, 5);
gbc_minTag.anchor = GridBagConstraints.EAST;
gbc_minTag.gridx = 0;
gbc_minTag.gridy = 4;
panel.add(minTag, gbc_minTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMinRemaining = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 4;
panel.add(textField, gbc_textField);
textField.setColumns(10);
textField = new JTextField();
GridBagConstraints gbc_textFieldPassword = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel passTag = new JLabel("Password:");
GridBagConstraints gbc_passTag = new GridBagConstraints();
gbc_passTag.insets = new Insets(0, 0, 0, 5);
gbc_passTag.anchor = GridBagConstraints.EAST;
gbc_passTag.gridx = 0;
gbc_passTag.gridy = 1;
panel.add(passTag, gbc_passTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldOdds = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel oddsTag = new JLabel("Odds %:");
GridBagConstraints gbc_oddsTag = new GridBagConstraints();
gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
gbc_oddsTag.anchor = GridBagConstraints.EAST;
gbc_oddsTag.gridx = 0;
gbc_oddsTag.gridy = 5;
panel.add(oddsTag, gbc_oddsTag);
textField = new JTextField();
GridBagConstraints gbc_textFieldMaxBet = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 6;
panel.add(textField, gbc_textField);
textField.setColumns(10);
//This is the Combo Box
combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
combo.addActionListener(this);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.fill = GridBagConstraints.HORIZONTAL;
gbc_list.gridx = 1;
gbc_list.gridy = 7;
panel.add(combo, gbc_list);
JLabel maxTag = new JLabel("MaxBet:");
GridBagConstraints gbc_maxTag = new GridBagConstraints();
gbc_maxTag.insets = new Insets(0, 0, 0, 5);
gbc_maxTag.anchor = GridBagConstraints.EAST;
gbc_maxTag.gridx = 0;
gbc_maxTag.gridy = 6;
panel.add(maxTag, gbc_maxTag);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea("Current Balance");
textArea.setColumns(1);
scrollPane.setViewportView(textArea);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textAreal = new JTextArea("Input bot information here...");
textArea.setColumns(20);
scrollPane.setViewportView(textArea);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == combo) {
System.out.println(combo.getSelectedIndex()+1);
}else if (e.getSource() == btnConfirm){
Dicebotcode dbc = new Dicebotcode();
dbc.dbc();
}
}
}
Two things...
One, if you've added the same scroll pane twice...
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
^--- Note no "l"
And, even if you have added the two scroll pane instances, you've added them to the same place, BorderLayout.CENTER
BorderLayout only allows a single component to be added to one of the available positions it supports, so, in this case, only the second scroll pane would be visible

How to take these labels in exactly required position

I am trying to create a small GUI with some lables and txtAreas. I did it by using absolute positioning, but I want to go on gridbag layout. I am trying from last 3 days, but couldnt get these lables as required position. either stucking in the middle around, or they stucking near the border. Please help to get them in these positions.
public void initUIPanel()
{
jf = new JFrame();
jf.setTitle("Mortgage Calculator");
jf.setLocation(100,200);
jf.setSize(400,500);
jf.setVisible (true);
//jf.setResizable(false);
JPanel panel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
loanAmount = new JTextField(15);
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(loanAmount, gbc);
panel.add(loanAmount);
loanTerm = new JTextField(15);
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(loanTerm, gbc);
panel.add(loanTerm);
amount = new JLabel("Loan Amount");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(amount, gbc);
panel.add(amount);
term= new JLabel("Loan Term");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(term, gbc);
panel.add(term);
currency = new JLabel ("AUD");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(currency, gbc);
panel.add(currency);
numOfYear = new JLabel ("Year");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(numOfYear, gbc);
panel.add(numOfYear);
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );
txtResult = new JTextArea();
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(txtResult, gbc);
panel.add(txtResult);
jf.add(panel,"Center");
//panel.setBounds(200,200,200,20);
jf.setVisible(true);
}
It is giving everything in 2 lines. all messed.
What I want is
First Line: Loan Amount: ............(txt Area).... "AUD"
Second LIne: Loan Term: .............(Txt Area......Years
Then Txtbox
Thank you
You haven't set the layout of the panel:
panel.setLayout(gbl);
And, as already said in the comments, all the components have the same gridx and gridy, which is obviously not right.
Here's a complete example which, if I understand correctly, does what you want:
import javax.swing.*;
import java.awt.*;
public class GblTest extends JFrame {
public GblTest() {
add(createPanel(), BorderLayout.NORTH);
}
private JPanel createPanel() {
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.BASELINE_LEADING;
p.add(new JLabel("Loan amount"), c);
c.gridx++;
p.add(new JTextField(15), c);
c.gridx++;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
p.add(new JLabel("AUD"), c);
c.gridx = 0;
c.gridy++;
c.fill = GridBagConstraints.NONE;
c.weightx = 0.0;
p.add(new JLabel("Loan term"), c);
c.gridx++;
p.add(new JTextField(15), c);
c.gridx++;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
p.add(new JLabel("Years"), c);
return p;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GblTest test = new GblTest();
test.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
}
});
}
}

JRadio Buttons are "Hiding" in GridBagLayout

Please have a look at the following code
package normal;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Form extends JFrame
{
private JLabel heightLabel, weightLabel, waistLabel, neckLabel, hipsLabel,genderLabel,valuesLabel,bfPercentageLabel;
private JLabel logoLabel;
private ImageIcon logo;
private JTextField heightTxt, weightTxt, waistTxt, neckTxt, hipsTxt;
private JRadioButton maleRadio, femaleRadio, inchesRadio, cmRadio;
private ButtonGroup genderGroup, valuesGroup;
private JComboBox percentageCombo;
private JPanel centerPanel, northPanel, southPanel;
public Form()
{
//Declaring instance variables
heightLabel = new JLabel("Height: ");
weightLabel = new JLabel("Weight: ");
waistLabel = new JLabel("Waist: ");
neckLabel = new JLabel("Neck: ");
hipsLabel = new JLabel("Hips: ");
genderLabel = new JLabel("Gender: ");
valuesLabel = new JLabel("Values in: ");
logoLabel = new JLabel();
logo = new ImageIcon(getClass().getResource("/images/calc_logo_final_2_edit.gif"));
logoLabel.setIcon(logo);
heightTxt = new JTextField(10);
weightTxt = new JTextField(10);
waistTxt = new JTextField(10);
neckTxt = new JTextField(10);
hipsTxt = new JTextField(10);
maleRadio = new JRadioButton("Male");
femaleRadio = new JRadioButton("Female");
genderGroup = new ButtonGroup();
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
inchesRadio = new JRadioButton("Inches");
cmRadio = new JRadioButton("Centimeters");
valuesGroup = new ButtonGroup();
valuesGroup.add(inchesRadio);
valuesGroup.add(cmRadio);
percentageCombo = new JComboBox();
percentageCombo.addItem("No Value is Set");
this.add(createNorthPanel(),"North");
this.add(createCenterPanel(),"Center");
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createNorthPanel()
{
northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(logoLabel);
return northPanel;
}
private JPanel createCenterPanel()
{
centerPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
centerPanel.setLayout(gbl);
//creating a jpanel for gender radio buttons
JPanel genderPanel = new JPanel();
genderPanel.setLayout(new FlowLayout());
genderPanel.add(genderLabel);
genderPanel.add(maleRadio);
genderPanel.add(femaleRadio);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(heightLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(heightTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(weightLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(weightTxt,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(waistLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(waistTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(neckLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(neckTxt,gbc);
gbc.gridx = 5;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(hipsLabel,gbc);
gbc.gridx = 6;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(hipsTxt,gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(genderLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(maleRadio,gbc);
gbc.gridx = 3;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,-10,0,0);
centerPanel.add(femaleRadio,gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(50,5,0,0);
centerPanel.add(valuesLabel,gbc);
return centerPanel;
}
}
As you can see, the JRadio button "female" is hiding a part of it, and once you move your cursor, it shows up completely. I guess this is happening because it is using minus spacing in "insets".
However I did it like that to reduce the gap between 2 radio buttons. Male is in gridx = 2, and female is in gridx = 3, which is a massive space between the buttons.So I used minus space in insets to reduce the space, unfortunately it came like this.
I tried adding the JLabel, maleRadio and femaleRadio into a seperate JPanel which is having flowlayout, and put it into gbc.gridx = 2; gbc.gridy = 3;. It made everything worst by matching all the cells in gridy = 3 into the width of new JPanel.
Please help me to reduce the gap between these 2 JRadio buttons, without having any issue. Thank you.
Dont extend JFrame rather create an instance and use that.
Also I see you add your radio buttons to a panel but you dont add the panel rather you re-add the radio buttons to centerpanel? choose one way lose the other (though I think this might have occurred in trying to mend the problem?)
An SSCCE most importantly is compilable (via correct syntax and no compile error) and runnable (via a main method and no runtime exceptions (unless thats the problem :P) - like your reading of the image - please find a way to include resources i.e link to an URL with the logo or make a method return a simple image the same size as logo or simply leave it out).
The problem is here:
gbc.gridx = 3;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15, -10, 0, 0);
centerPanel.add(femaleRadio, gbc);
-10 should definitely not be there (maybe typo?) as this will cause it to overlap or in this case underlap another component, rather use anything greater than or equal to 0:
gbc.gridx = 3;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15, 10, 0, 0);
centerPanel.add(femaleRadio, gbc);
which would give us:
UPDATE:
Also it is important to note GridBagContsraints like gridx etc start at 0 and not 1.
+1 to #Gagandeeps balis comment on re-using values which have been set already and are the same in GridBagConstraints, here is your code with all talked about fixes:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
class Form {
private JLabel heightLabel, weightLabel, waistLabel, neckLabel, hipsLabel, genderLabel, valuesLabel, bfPercentageLabel;
private JLabel logoLabel;
private ImageIcon logo;
private JTextField heightTxt, weightTxt, waistTxt, neckTxt, hipsTxt;
private JRadioButton maleRadio, femaleRadio, inchesRadio, cmRadio;
private ButtonGroup genderGroup, valuesGroup;
private JComboBox percentageCombo;
private JPanel centerPanel, northPanel, southPanel;
public Form() {
//Declaring instance variables
heightLabel = new JLabel("Height: ");
weightLabel = new JLabel("Weight: ");
waistLabel = new JLabel("Waist: ");
neckLabel = new JLabel("Neck: ");
hipsLabel = new JLabel("Hips: ");
genderLabel = new JLabel("Gender: ");
valuesLabel = new JLabel("Values in: ");
logoLabel = new JLabel();
//logo = new ImageIcon(getClass().getResource("/images/calc_logo_final_2_edit.gif"));
//logoLabel.setIcon(logo);
heightTxt = new JTextField(10);
weightTxt = new JTextField(10);
waistTxt = new JTextField(10);
neckTxt = new JTextField(10);
hipsTxt = new JTextField(10);
maleRadio = new JRadioButton("Male");
femaleRadio = new JRadioButton("Female");
genderGroup = new ButtonGroup();
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
inchesRadio = new JRadioButton("Inches");
cmRadio = new JRadioButton("Centimeters");
valuesGroup = new ButtonGroup();
valuesGroup.add(inchesRadio);
valuesGroup.add(cmRadio);
percentageCombo = new JComboBox();
percentageCombo.addItem("No Value is Set");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createNorthPanel(), "North");
frame.add(createCenterPanel(), "Center");
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private JPanel createNorthPanel() {
northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(logoLabel);
return northPanel;
}
private JPanel createCenterPanel() {
centerPanel = new JPanel(new GridBagLayout());
GridBagLayout gbl = new GridBagLayout();
centerPanel.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15, 5, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
centerPanel.add(heightLabel, gbc);
gbc.gridx = 1;
centerPanel.add(heightTxt, gbc);
gbc.gridx = 2;
centerPanel.add(weightLabel, gbc);
gbc.gridx = 3;
centerPanel.add(weightTxt, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
centerPanel.add(waistLabel, gbc);
gbc.gridx = 1;
centerPanel.add(waistTxt, gbc);
gbc.gridx = 2;
centerPanel.add(neckLabel, gbc);
gbc.gridx = 3;
centerPanel.add(neckTxt, gbc);
gbc.gridx = 4;
centerPanel.add(hipsLabel, gbc);
gbc.gridx = 5;
centerPanel.add(hipsTxt, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
centerPanel.add(genderLabel, gbc);
gbc.gridx = 1;
centerPanel.add(maleRadio, gbc);
gbc.gridx = 2;
centerPanel.add(femaleRadio, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(50, 5, 0, 0);
centerPanel.add(valuesLabel, gbc);
return centerPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Form();
}
});
}
}

Categories