How to Get these JLabels to be Displayed in my JFrame? - java

I am attempting to make a "sentence randomizer" that, when a button is pressed, makes a grammatically correct sentence, that may not make any sense, by looping different types of words from a separate folder and separate files. It also alternates colors in each panel. I so far am able to get the JButton to show up, but I can't seem to figure out how to get the panels to appear? Here is my code so far for the UI:
package user_interface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import code.sentence;
import user_interface.RandomButtonListener;
public class sentenceUI {
private sentence _s;
private JButton _rando;
public sentenceUI() {
_s = new sentence(this);
JFrame f = new JFrame("Ryan Ellis' Lab 9");
f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
f.add(topPanel);
JPanel lowerPanel = new JPanel();
f.add(lowerPanel);
_rando = new JButton("Random Sentence");
_rando.addActionListener(new RandomButtonListener(_s, this));
lowerPanel.add(_rando);
Color c1 = Color.BLUE;
Color c2 = new Color( 255 - c1.getRed(), 255 - c1.getGreen(), 255 - c1.getBlue());
for(int i = 0; i < 8; i++){
JLabel _l = new JLabel();
_l.setBackground(c1);
_l.setForeground(c2);
Color temp = c1;
c1 = c2;
c2 = temp;
_l.setBorder(BorderFactory.createEmptyBorder(0,0,8,5));
_l.setFont(new Font("Comic Sans", Font.BOLD, 18));
topPanel.add(_l);
}
ArrayList<String> _slst = new ArrayList<String>();
_slst.add("WordLists/adjectives.txt");
_slst.add("WordLists/adverbs.txt");
_slst.add("WordLists/determiners.txt");
_slst.add("WordLists/nouns.txt");
_slst.add("WordLists/verbs.txt");
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
list.add(_slst);
int i = 0;
list.get(i % 5);
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
}
private void createRButton(String string, JPanel lowerPanel) {
createRButton("Random", lowerPanel);
}

You're adding topPanel twice to the JFrame, here
JPanel topPanel = new JPanel();
f.add(topPanel);
and here:
f.add(topPanel, BorderLayout.PAGE_START);
f.add(lowerPanel, BorderLayout.PAGE_END);
and in the 2nd addition, you're adding it as if the JFrame currently used a BorderLayout, but it's not since you've given it a BoxLayout.
Instead, only add the topPanel once, and in a logical way. Also consider giving your JLabel's some dummy text, such as " " so that they have some size when you first pack() your GUI.
Also, your labels are being added but they have no size and are non-opaque and so can't be seen. For example try this within your for loop to see for yourself:
JLabel _l = new JLabel("Label " + i); // to give labels size
_l.setOpaque(true); // so you can see the background color
_l.setBackground(c1);
_l.setForeground(c2);

Related

How to Have my JLabels Display Strings stored in my ArrayList?

EDIT: Extension of question How to Get these JPanels to be Display in my JFrame.
I am attempting to make a "sentence randomizer" that, when a button is pressed, makes a grammatically correct sentence by looping different types of words from a separate folder and separate files. The issue that I am encountering is that I am unable to figure out how to get the retrieved words displayed within the JLabels. Here is my code so far to clarify:
package user_interface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import code.sentence;
import user_interface.RandomButtonListener;
public class sentenceUI {
private sentence _s;
private JButton _rando;
public sentenceUI() {
_s = new sentence(this);
JFrame f = new JFrame("Ryan Ellis' Lab 9");
f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
f.add(topPanel);
JPanel lowerPanel = new JPanel();
f.add(lowerPanel);
_rando = new JButton("Random Sentence");
_rando.addActionListener(new RandomButtonListener(_s, this));
lowerPanel.add(_rando);
ArrayList<JLabel> _labels = new ArrayList<JLabel>();
Color c1 = Color.BLUE;
Color c2 = new Color( 255 - c1.getRed(), 255 - c1.getGreen(), 255 - c1.getBlue());
for(int i = 0; i < 8; i++){
JLabel _l = new JLabel();
_l.setOpaque(true);
_l.setBackground(c1);
_l.setForeground(c2);
Color temp = c1;
c1 = c2;
c2 = temp;
_l.setBorder(BorderFactory.createEmptyBorder(0,0,8,5));
_l.setFont(new Font("Comic Sans", Font.BOLD, 18));
topPanel.add(_l);
}
ArrayList<String> _slst = new ArrayList<String>();
_slst.add("WordLists/adjectives.txt");
_slst.add("WordLists/adverbs.txt");
_slst.add("WordLists/determiners.txt");
_slst.add("WordLists/nouns.txt");
_slst.add("WordLists/verbs.txt");
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
list.add(_slst);
int i = 0;
list.get(i % 5);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
}
private void createRButton(String string, JPanel lowerPanel) {
createRButton("Random", lowerPanel);
}
}
You need to store the JLabels in some sort of list so you can retrieve their instance later, after you've generated a random sentence.
Then you can do
jlabel.setText(string)
and after you've added all the words, you may have to repaint the JPanel (with jpanel.repaint()) to update the JLabel's display.

JScrollPane doesn't top align when there is more than enough space to show the content

I have a JScrollPane that show a list of items. I would like the user to be able to scroll through the list if there is not enough space on the screen to show the list and I would like the list to align to the top of the available space if there is more than enough space to show the list. I can do one or the other but can't seem to get both to work. The code shown below accomplishes the goal of allowing the list to be scrollable if the list is larger than the available space but does not align to the top as shown below. I've tried things like putting the JScrollPane in the north section of a borderlayout but when I do this the list is no longer scrollable (i.e. borderlayout gives the scrollpane all of the space it needs and the list is now not scrollable).
Here's what the code below creates:
And here's the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Example {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(400, 200);
// main panel
JPanel pan = new JPanel();
pan.setLayout(new GridLayout(1, 2));
pan.setBackground(Color.BLUE);
jFrame.getContentPane().add(pan, BorderLayout.CENTER);
jFrame.show();
// left panel
JPanel left = getContentPanel();
left.setBackground(Color.ORANGE);
pan.add(left);
// right panel (with scroll pane)
JPanel right = getContentPanel();
right.setBackground(Color.YELLOW);
JScrollPane scr = new JScrollPane(right);
scr.setBackground(Color.CYAN);
scr.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
scr.setAlignmentY(JScrollPane.TOP_ALIGNMENT);
pan.add(scr);
}
private static JPanel getContentPanel() {
JPanel rtn = new JPanel();
rtn.setLayout(new GridBagLayout());
GridBagConstraints cs = new GridBagConstraints();
cs.gridx = 0;
cs.weightx = 1;
cs.anchor = GridBagConstraints.NORTHWEST;
for (int i = 0; i < 20; i++) {
JLabel label = new JLabel("Item " + (i + 1));
label.setBackground(Color.DARK_GRAY);
cs.gridy = i;
rtn.add(label, cs);
}
rtn.setBackground(Color.GREEN);
return rtn;
}
}
You can use Boxlayout.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Example {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(400, 200);
// main panel
JPanel pan = new JPanel();
pan.setLayout(new GridLayout(1, 2));
pan.setBackground(Color.BLUE);
jFrame.getContentPane().add(pan, BorderLayout.CENTER);
jFrame.show();
// left panel
JPanel left = getContentPanel();
left.setBackground(Color.ORANGE);
pan.add(left);
// right panel (with scroll pane)
JPanel right = getContentPanel();
right.setBackground(Color.YELLOW);
JScrollPane scr = new JScrollPane(right);
scr.setBackground(Color.CYAN);
scr.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
scr.setAlignmentY(JScrollPane.TOP_ALIGNMENT);
pan.add(scr);
}
private static JPanel getContentPanel() {
JPanel rtn = new JPanel();
rtn.setLayout(new BoxLayout(rtn, BoxLayout.Y_AXIS));
for (int i = 0; i < 20; i++) {
JLabel label = new JLabel("Item " + (i + 1));
label.setBackground(Color.DARK_GRAY);
rtn.add(label);
}
rtn.add(Box.createVerticalGlue());
rtn.setBackground(Color.GREEN);
return rtn;
}
}

Connection of JButton and JTextField?

I just want to know how to do a new frame via typing a specific character then if you click the Jbutton, all the information (of that character) will pop up - for example a picture or a text.
For example, if I type the word "Dog", a picture of a dog and the information about it will pop out on a new window. Is this possible without database?
I want to do it without a database if it's possible.
Here's my code:
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
//Bago
import java.awt.GridBagLayout; // Para mahatihati yung panel
import java.awt.GridBagConstraints; // para customize yung pagkahati ng panel
class ProgDraftMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ProgDraft gui = new ProgDraft();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setResizable(true);
gui.pack();
gui.setVisible(true);
}
});
}
}
class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
private JButton butones;
private JTextField textField;
ProgDraft() {
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel title = new JLabel("Dog Check", JLabel.CENTER);
Font font = new Font("Gigi", Font.BOLD, 50);
title.setFont(font);
mainPanel.add(title, BorderLayout.NORTH);
String text = "Dogs" + "<br>"
+ "Cute dogs are everywhere" + "<br>" + "<br>"
+ "Take care and stay safe!" + "<br>"
+ "I love my dogs" + "<br>" + "<br>" + "<br>"
+ "Please help!";
JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
dog.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(dog);
ImageIcon pics = new ImageIcon(getClass().getResource("Capture.png"));
JLabel logo = new JLabel(pics);
logo.setHorizontalAlignment(JLabel.CENTER);
logo.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
logo.setToolTipText("PIcture.");
JPanel iconFieldPanel = new JPanel();
iconFieldPanel.setLayout( new GridBagLayout() );
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.CENTER; // Saan ikakabit yung component
gc.weightx = 0.5; // (left and right)Space between sa edge nung panel at component
gc.weighty = 0.5; // (top and bottom)^
gc.gridx = 0; //saang cell x-axis
gc.gridy = 0; //^ y axis naman
iconFieldPanel.add(logo, gc);
gc.gridy = 1;
JLabel titleBut = new JLabel("Enter Dog Code:");
iconFieldPanel.add(titleBut, gc);
gc.gridy = 2;
textField = new JTextField(10);
iconFieldPanel.add(textField, gc );
JButton buton1 = new JButton("OK");
gc.gridy = 3;
iconFieldPanel.add( buton1, gc);
JPanel iconFieldWrapper = new JPanel();
iconFieldWrapper.add(iconFieldPanel);
mainPanel.add(iconFieldWrapper, BorderLayout.SOUTH); // add icon and field to bottom
getContentPane().add(mainPanel);
}
}
The following code may help you to solve your problem,
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class PopupExample implements ActionListener
{
JFrame frame;
JTextField t1;
JButton btn;
public PopupExample()
{
frame=new JFrame();
frame.setLayout(null);
frame.setSize(700,700);
frame. setLocation(300,10);
t1=new JTextField();
t1.setBounds(82,10,100,20);
frame.add(t1);
btn=new JButton("SUBMIT");
btn.setBounds(200,10,100,20);
btn.addActionListener(this);
frame.add(btn);
frame.setVisible(true);
}
public static void main(String ar[])
{
PopupExample obj=new PopupExample();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn)
{
String input=t1.getText();
if(input.equals("dog"))
{
JOptionPane.showMessageDialog(null,"my dog");
//you can popup new frame here about dog
//create the object of new class (which contain dog details)here.
//you can use show()
}
}
}
}
It is possible to write a program without database but you have to think about a way to store the data. For database concern, I guess you mean how to store the code and picture of these dogs.
Yes, we can do that without database, but you need to write different logic i.e. hard coding like based on the condition
Example: After getting the data from the text field
String a=xx.getText().toString().trim();if(a.equals("dog"))
{
//call the iframe which u need
}
Note: As you need to store all the images in your working directory, or store all the frames with different names which includes images and information regarding the image and call them according to your requirement.

How to fix gap in GridBagLayout

I am using a GridBagLayout to create a JPanel, called 'Preset', that gets replicated several times in a JFrame. Each Preset will have multiple rows (JPanels). My goal is that only one line (the first) will show up, but when the edit button is clicked, they will all show. Right now, the edit button works, but there is a massive space between the lines. I want it to be such that when the extra lines are collapsed, each Preset will be directly above each other (no space). You can see in the following picture what I am talking about.
This is how it looks:
This is how I want it to Look:
I am fairly certain I need to do something with the GridBag, but I don't know what. I have read several tutorials and have written it as I thought it should be, but no luck.
package SSCCE;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
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.JTextField;
public class UI extends JFrame{
private final static int HEIGHT = 600;
private final static int WIDTH = 730;
private JPanel pane; //Pane that stores accounts
private JScrollPane scroller;
private Preset[] branches;
public static void main(String[] args) {
JFrame frame = new UI();
}
public UI(){
//Make the UI close when the exit button is clicked
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Sets the size of the UI
this.setSize(WIDTH, HEIGHT);
//Set the layout and add components to it
this.setLayout(new BorderLayout());
//Reads in the settings and sets up the branches
populateBranches();
pane = new JPanel();
pane.setLayout(new GridLayout(branches.length,1));
for (int i = 0; i < branches.length; i++){
pane.add(branches[i]);
}
//Create the center pane of the BorderLayout
scroller = new JScrollPane(pane);
scroller.createVerticalScrollBar();
this.add(scroller,BorderLayout.CENTER);
//Makes the UI visible
this.setVisible(true);
}
private void populateBranches(){
//Populates the branches array based on what is read in, or not read in from the file
branches = new Preset[15];
for (int i = 0; i < branches.length; i++){
branches[i] = new Preset();
branches[i].setEnabled(false);
}
}
public class Preset extends JPanel{
private JTextField eName;
private JButton edit;
private JButton activate;
private JComboBox printer;
private JPanel line1;
private JPanel line2;
private String branchName;
private String ipAddress;
private boolean enableAll;
public Preset(){
eName = new JTextField(20);
edit = new JButton("Edit");
activate = new JButton("Activate");
JPanel nameContainer = new JPanel();
nameContainer.setLayout(new FlowLayout());
nameContainer.add(eName);
printer = new JComboBox();
//
line1 = new JPanel();
line1.setLayout(new FlowLayout());
line1.add(nameContainer);
line1.add(edit);
line1.add(activate);
//
line2 = new JPanel();
line2.setLayout(new BorderLayout());
line2.add(printer, BorderLayout.WEST);
GridBagLayout grid = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();
cons.fill = GridBagConstraints.BOTH;
this.setLayout(grid);
cons.ipady = 100;
cons.ipadx = 100;
cons.weighty = 0D;
cons.gridx = 0;
cons.gridy = 0;
cons.gridwidth = 2;
cons.gridheight = 1;
grid.setConstraints(line1, cons);
this.add(line1);
cons.ipady = 100;
cons.ipadx = 100;
cons.weighty = 0D;
cons.gridx = 0;
cons.gridy = 1;
cons.gridwidth = 2;
cons.gridheight = 1;
grid.setConstraints(line2, cons);
this.add(line2);
//Enable all components
enableAll = true;
}
}
}
Remove every statement that assigns padding in the Y AXIS for the GridBagConstraints of the Preset JPanel, i.e.
cons.ipady = 100;
I don't consider this a "real" answer to your question, but something for you to consider: get rid of gridbag. I don't see anything in your desired layout that requires it. Create each panel with two subpanels; the second subpanel contains the stuff that you want to make invisible by default and display later, and use setVisible() to do that.
I've never gotten comfortable with all of the GridBagConstraints, which seem to interact in ways for which I have no clear model. I avoid GridBagLayout for that reason, so I can't help do this with GridBagLayout. But I don't see why you can't do this with simpler (and less wordy) existing Swing containers and layout managers.
This is a real answer to the background question (how to get the effect you want):
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesOneAndTwo implements ActionListener
{
private static final long serialVersionUID = 1L;
JFrame mainWindow = new JFrame("LinesOneandTwo");
JButton showButton = null;
JButton hideButton = null;
JPanel firstb = new JPanel();
public static void main(String[] args)
{
LinesOneAndTwo main = new LinesOneAndTwo();
main.go();
}
private void go()
{
mainWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container contentPane = mainWindow.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel first = new JPanel();
JPanel firsta = new JPanel();
JPanel second = new JPanel();
JPanel seconda = new JPanel();
JPanel secondb = new JPanel();
first.setLayout(new BoxLayout(first, BoxLayout.Y_AXIS));
firsta.setLayout(new BoxLayout(firsta, BoxLayout.X_AXIS));
showButton = new JButton("show");
hideButton = new JButton("hide");
firsta.add(showButton);
firsta.add(hideButton);
firstb.setLayout(new BoxLayout(firstb, BoxLayout.X_AXIS));
firstb.add(new JButton("one"));
firstb.add(new JButton("two"));
first.add(firsta);
first.add(firstb);
second.setLayout(new BoxLayout(second, BoxLayout.Y_AXIS));
seconda.setLayout(new BoxLayout(seconda, BoxLayout.X_AXIS));
secondb.setLayout(new BoxLayout(secondb, BoxLayout.X_AXIS));
seconda.add(new JButton("hiya"));
seconda.add(new JButton("there"));
secondb.add(new JButton("not here"));
second.add(seconda);
second.add(secondb);
secondb.setVisible(false);
firstb.setVisible(false);
showButton.addActionListener(this);
hideButton.addActionListener(this);
mainWindow.add(first);
mainWindow.add(second);
mainWindow.pack();
mainWindow.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == showButton)
{
firstb.setVisible(true);
mainWindow.pack();
}
else if (event.getSource() == hideButton)
{
firstb.setVisible(false);
mainWindow.pack();
}
}
}
Of course, I don't know what's different about the internals of your panels, or how they differ otherwise, but the "show" and "hide" buttons cause the secondary panel within the top panel of the frame to appear and disappear, leaving no gaps.
I still don't like GridBagLayout.
I got the same problem and found a 70% Solution .
If you use rowWeights and set it to 0 for all but your last component (with rowWeights 1.0), nearly all spaces vanish. If your containing Component is larger than all the other components, there remains only the gap before the last component.
GridBagLayout gbl_panelFoo = new GridBagLayout();
gbl_panelFoo.rowWeights = new double[] {0.0, 0.0, 0.0, ... 0.0, 1.0};
Maybe this helps a little

JButton: Icon left-aligned, text right-aligned

I'm trying to create a JButton with an icon and some text in it. My problem is that I want the icon to be left-aligned and the text right-aligned (It isn't necessary to be right-aligned, but I don't want the text to stick to the icon).
Not being able to do this on my own, I tried a slightly different solution. I used the iconTextGap to create some space between the icon and the text, what worked fine in principle, but when I create multiple buttons, which all have the width of the widest, the icon isn't at the very left anymore (except in the button with the longest text).
I included a code to demonstrate that:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.File;
import java.net.MalformedURLException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Main{
private JFrame frame;
private JPanel buttonPanel;
private GridBagConstraints constraints;
public Main() throws MalformedURLException{
frame = new JFrame();
buttonPanel = new JPanel();
frame.add(buttonPanel);
buttonPanel.setLayout(new GridBagLayout());
constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 3, 5);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
String[] text = { "some Text", "this text is longer" };
for (int i = 0; i < text.length; i++) {
JButton button= new JButton(text[i], new ImageIcon(new File("icon.png").toURI().toURL()));
button.setAlignmentX(SwingConstants.WEST);
button.setIconTextGap(30);
button.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 10));
buttonPanel.add(button, constraints);
constraints.gridy++;
}
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
try {
new Main();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Does anyone know of a way to have the icon at the left end and have some space between the icon and the text (or the text right-aligned)?
Have a look at JButton#setHorizontalTextPosition and JButton#setHorizontalAlignment
And just because it might be helpful JButton#setVerticalTextPosition and JButton#setVerticalAlignment
Classic solution to this problem to use additional panel that has a layout that alows to align components such as BorderLayout. Then put the button and label inside it with the corresponding layout alignment. Pack or validate the frame.
Try to set margin to smaller then default values in button properties,
and then set iconTextGap to have it rightmost horizontal position

Categories