import java.awt.*;
import javax.swing.*;
public class GBLClumpingExample extends JFrame{
GBLClumpingExample(){
GridBagLayout g = new GridBagLayout();
GridBagConstraints gv = new GridBagConstraints();
GridBagLayout b = new GridBagLayout();
GridBagConstraints gc = new GridBagConstraints();
setVisible(true);
setSize(720,720);
setLayout(g);
JPanel p = new JPanel();
p.setLayout(b);
gv.fill = GridBagConstraints.BOTH;
add(p,gv);
Label l1 = new Label("Label 1");
Label l2 = new Label("Label 2");
Label l3 = new Label("Label 3");
Label l4 = new Label("Label 4");
Label l5 = new Label("Label 5");
gc.weightx =1.0;
gc.weighty = 1.0;
gc.gridx= 1;
gc.gridy= 1;
gc.anchor = GridBagConstraints.PAGE_START;
gc.gridx= -1;
gc.gridy= 0;
p.add(l1,gc);
gc.anchor = GridBagConstraints.SOUTH;
p.add(l2,gc);
gc.anchor = GridBagConstraints.EAST;
p.add(l3,gc);
gc.anchor = GridBagConstraints.WEST;
p.add(l4,gc);
gc.anchor = GridBagConstraints.CENTER;
p.add(l5,gc);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
GBLClumpingExample e = new GBLClumpingExample();
}
}
I was trying to use GridBagLayout but maybe it is not working correctly.
This is my code I don't know what is wrong but anchor constraints of GridBagConstraints are not working, they are all just clump together.
You are adding you components to a panel p which you are then adding to the frame (to its content pane) using add(p,gv);. The constraints in gv have been initialized with gv.fill = GridBagConstraints.BOTH;, but its weightx and weighty are left at their initial zero. As a result, this panel will stay at its preferred size and not receive additional space, so it has no additional space to distribute to its own content.
Since all labels have the same size, their anchors have no effect when there is no additional space.
When you change the line
gv.fill = GridBagConstraints.BOTH;
to
gv.fill = GridBagConstraints.BOTH;
gv.weightx = 1;
gv.weighty = 1;
you will see the effect of the anchors. Alternatively, you can get rid of the additional panel. There are other redundant operations too. You can simplify your code to:
import java.awt.*;
import javax.swing.*;
public class GBAnchorExample extends JFrame{
GBAnchorExample() {
Container c = super.getContentPane();
c.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = gc.weighty = 1.0;
JLabel l1 = new JLabel("Label 1");
JLabel l2 = new JLabel("Label 2");
JLabel l3 = new JLabel("Label 3");
JLabel l4 = new JLabel("Label 4");
JLabel l5 = new JLabel("Label 5");
gc.anchor = GridBagConstraints.PAGE_START;
c.add(l1,gc);
gc.anchor = GridBagConstraints.SOUTH;
c.add(l2,gc);
gc.anchor = GridBagConstraints.EAST;
c.add(l3,gc);
gc.anchor = GridBagConstraints.WEST;
c.add(l4,gc);
gc.anchor = GridBagConstraints.CENTER;
c.add(l5,gc);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
GBAnchorExample e = new GBAnchorExample();
e.setSize(720,720);
e.setVisible(true);
}
}
To visualize the actual effect of the anchor you may change the main method to
public static void main(String[] args){
GBAnchorExample e = new GBAnchorExample();
Component grid = new JComponent() {
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.GREEN);
int w = getWidth(), h = getHeight();
for(int i = 1; i < 5; i++) {
int x = (int)(w/5.0*i);
g.drawLine(x, 0, x, h);
}
}
};
e.setGlassPane(grid);
grid.setVisible(true);
e.setSize(720,720);
e.setVisible(true);
}
This will paint a green grid to show the logical cells containing the labels, so it becomes apparent how the anchors affect the labels’ positions within their cells.
If I understand the intent of this layout correctly (I'm not sure I do) then this might be done using a BorderLayout.
Here it is with more width and height:
The titled borders are only there to provide a quick visual reference to the constraint used to place the component. The (spacer) is only added to the 3 labels in the center row to allow the full TitledBorder to appear!
Here is the code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BLNotClumpingExample {
private JComponent ui = null;
BLNotClumpingExample() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(10,10));
ui.setBorder(new EmptyBorder(4,4,4,4));
ui.add(getLabel("Label 1", "PAGE_START"), BorderLayout.PAGE_START);
ui.add(getLabel("Label 2", "PAGE_END"), BorderLayout.PAGE_END);
ui.add(getLabel("Label 3 (spacer)", "LINE_END"), BorderLayout.LINE_END);
ui.add(getLabel("Label 4 (spacer)", "LINE_START"), BorderLayout.LINE_START);
ui.add(getLabel("Label 5 (spacer)", "CENTER"), BorderLayout.CENTER);
}
private JLabel getLabel(String text, String constraint) {
JLabel l = new JLabel(text, SwingConstants.CENTER);
l.setBorder(new TitledBorder(constraint));
return l;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BLNotClumpingExample o = new BLNotClumpingExample();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
Related
I was testing something with JPanel. When I added random text to the JTextArea inside it, it kept increasing the size of the JPanel until it reached the edge.
How do I keep the text inside the JPanel without stretching it?
public class Game
{
TitleScreenHandler tsHandler = new TitleScreenHandler();
ChoiceHandler choiceHandler = new ChoiceHandler();
ComponentHandler compHandler = new ComponentHandler();
GridBagConstraints gbc = new GridBagConstraints();
Border whiteline = BorderFactory.createLineBorder(Color.WHITE);
JFrame window;
Container con;
JPanel titlePanel , startPanel, mainTextPanel, choiceButtonPanel, playerPanel;
JLabel titleLabel, hpLabel, hpLabelNumber, weaponLabel, weaponLabelName;
public static JButton startButton, choice1,choice2,choice3,choice4,choice5,choice6,choice7,choice8;
public static JTextArea mainTextArea;
Font titleFont = new Font("Times New Roman", Font.PLAIN, 100);
Font normalFont = new Font("Times New Roman", Font.PLAIN, 30);
public static String playerName;
public static String weapon,position;
public static int playerHP;
public static int weaponDamage;
public static void main(String[] args)
{
new Game();
}
public Game()
{
window = new JFrame();
window.setSize(1440,900);
window.setTitle("W: " + window.getWidth() + " H: " + window.getHeight());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(new GridBagLayout());
con = window.getContentPane();
//Panels are used to make sections in the window (Background)
//Labels are used to write in the sections/panels (Foreground)
//Buttons can be pressed inside Panels
//To make a text you need to design a panel, design its size/color,
//Design its text the same way, then add it to the panel
titlePanel = new JPanel();
titlePanel.setBounds(100, 100, 1080 , 150);
titlePanel.setBackground(Color.black);
titleLabel = new JLabel("Adventure");
titleLabel.setForeground(Color.white);
titleLabel.setFont(titleFont);
startPanel = new JPanel();
startPanel.setBounds(540, 600, 200, 100);
startPanel.setBackground(Color.black);
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
startButton.addActionListener(tsHandler);
window.addComponentListener(compHandler);
titlePanel.add(titleLabel);
startPanel.add(startButton);
con.add(titlePanel, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
con.add(startPanel, gbc);
window.setVisible(true);
}
public void createGameScreen()
{
titlePanel.setVisible(false);
startButton.setVisible(false);
mainTextPanel = new JPanel();
//mainTextPanel.setBounds(100, 100, 1080, 250);
mainTextPanel.setBackground(Color.black);
mainTextPanel.setBorder(whiteline);
mainTextArea = new JTextArea("This is the main text area");
mainTextArea.setBounds(100,100,1080,250);
mainTextArea.setBackground(Color.black);
mainTextArea.setForeground(Color.white);
mainTextArea.setLayout(new GridLayout());
mainTextArea.setFont(normalFont);
mainTextArea.setLineWrap(true);
mainTextArea.setWrapStyleWord(true);
playerPanel = new JPanel();
playerPanel.setBounds(100, 100, 1080, 50);
playerPanel.setBackground(Color.blue);
playerPanel.setLayout(new GridLayout(1,4));
choiceButtonPanel = new JPanel();
choiceButtonPanel.setBounds(500, 350, 300, 250);
choiceButtonPanel.setLayout(new GridLayout(2,4, 50, 50));
choiceButtonPanel.setBackground(Color.red);
choice1 = new JButton("Choice 1");
choice1.setBackground(Color.black);
choice1.setForeground(Color.white);
choice1.setFont(normalFont);
choice1.setFocusPainted(false);
choice1.addActionListener(choiceHandler);
choice1.setActionCommand("c1");
choiceButtonPanel.add(choice1);
choice2 = new JButton("Choice 2");
choice2.setBackground(Color.black);
choice2.setForeground(Color.white);
choice2.setFont(normalFont);
choice2.setFocusPainted(false);
choice2.addActionListener(choiceHandler);
choice2.setActionCommand("c2");
choiceButtonPanel.add(choice2);
choice3 = new JButton("Choice 3");
choice3.setBackground(Color.black);
choice3.setForeground(Color.white);
choice3.setFont(normalFont);
choice3.setFocusPainted(false);
choice3.addActionListener(choiceHandler);
choice3.setActionCommand("c3");
choiceButtonPanel.add(choice3);
choice4 = new JButton("Choice 4");
choice4.setBackground(Color.black);
choice4.setForeground(Color.white);
choice4.setFont(normalFont);
choice4.setFocusPainted(false);
choice4.addActionListener(choiceHandler);
choice4.setActionCommand("c4");
choiceButtonPanel.add(choice4);
choice5 = new JButton("Choice 5");
choice5.setBackground(Color.black);
choice5.setForeground(Color.white);
choice5.setFont(normalFont);
choice5.setFocusPainted(false);
choice5.addActionListener(choiceHandler);
choice5.setActionCommand("c5");
choiceButtonPanel.add(choice5);
choice6 = new JButton("Choice 6");
choice6.setBackground(Color.black);
choice6.setForeground(Color.white);
choice6.setFont(normalFont);
choice6.setFocusPainted(false);
choice6.addActionListener(choiceHandler);
choice6.setActionCommand("c6");
choiceButtonPanel.add(choice6);
choice7 = new JButton("Choice 7");
choice7.setBackground(Color.black);
choice7.setForeground(Color.white);
choice7.setFont(normalFont);
choice7.setFocusPainted(false);
choice7.addActionListener(choiceHandler);
choice7.setActionCommand("c7");
choiceButtonPanel.add(choice7);
choice8 = new JButton("Choice 8");
choice8.setBackground(Color.black);
choice8.setForeground(Color.white);
choice8.setFont(normalFont);
choice8.setFocusPainted(false);
choice8.addActionListener(choiceHandler);
choice8.setActionCommand("c8");
choiceButtonPanel.add(choice8);
gbc.anchor = GridBagConstraints.PAGE_END;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
con.add(playerPanel,gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
//gbc.ipadx = 750;
gbc.ipady = 1000;
gbc.gridwidth = 2;
gbc.gridx = 1;
gbc.gridy = 0;
con.add(mainTextPanel,gbc);
gbc.fill = GridBagConstraints.NONE;
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.gridx = 1;
gbc.gridy = 5;
con.add(choiceButtonPanel,gbc);
hpLabel = new JLabel("HP: ");
hpLabel.setFont(normalFont);
hpLabel.setForeground(Color.white);
hpLabelNumber = new JLabel();
hpLabelNumber.setFont(normalFont);
hpLabelNumber.setForeground(Color.white);
weaponLabel = new JLabel("Weapon: ");
weaponLabel.setFont(normalFont);
weaponLabel.setForeground(Color.white);
weaponLabelName = new JLabel();
weaponLabelName.setFont(normalFont);
weaponLabelName.setForeground(Color.white);
playerPanel.add(hpLabel);
playerPanel.add(hpLabelNumber);
playerPanel.add(weaponLabel);
playerPanel.add(weaponLabelName);
mainTextPanel.add(mainTextArea, BorderLayout.PAGE_START);
playerSetup();
}
public void playerSetup()
{
playerHP = 15;
weapon = "Fists";
weaponLabelName.setText(weapon);
hpLabelNumber.setText("" + playerHP);
ForestEvents.townGate();
}
/*public void townGate()
{
position = "towngate";
mainTextArea.setText("You are at the gates of the town. A guard is standing in front of you. What do you do?");
choice1.setText("Talk to the Guard");
choice2.setText("Attack the Guard");
choice3.setText("Leave");
choice4.setText("");
}*/
public void talkGuard()
{
position = "talkguard";
mainTextArea.setText("Guard: Hello Stranger. I have never seen you before. I'm sorry but I cannot let you enter.");
choice1.setText("Go Back");
choice2.setText("");
choice3.setText("");
choice4.setText("");
}
public void attackGuard()
{
position = "attackguard";
mainTextArea.setText("Guard: HOW DARE YOU!\nThe guard fought back and hit you hard.\n(You received 3 damage)");
playerHP -= 3;
hpLabelNumber.setText("" + playerHP);
choice1.setText("Go Back");
choice2.setText("");
choice3.setText("");
choice4.setText("");
}
public void crossRoad()
{
position = "crossroads";
mainTextArea.setText("You are at the crossroad.\n Go south to go back to the town.");
choice1.setText("Go North");
choice2.setText("Go East");
choice3.setText("Go South");
choice4.setText("Go West");
}
public class ComponentHandler implements ComponentListener
{
public void componentResized(ComponentEvent e)
{
Component c = (Component)e.getSource();
window.setTitle("W: " + c.getWidth() + " H: " + c.getHeight());
}
#Override
public void componentHidden(ComponentEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void componentMoved(ComponentEvent e)
{
}
#Override
public void componentShown(ComponentEvent e)
{
}
}
public class TitleScreenHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
createGameScreen();
}
}
public class ChoiceHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String yourChoice = event.getActionCommand();
switch (position)
{
case "towngate":
switch(yourChoice)
{
case "c1":
talkGuard();
break;
case "c2":
attackGuard();
break;
case "c3":
crossRoad();
break;
case "c4":
break;
}
break;
case "talkguard":
switch(yourChoice)
{
case "c1":
ForestEvents.townGate();
break;
}
break;
case "attackguard":
switch(yourChoice)
{
case "c1":
ForestEvents.townGate();
break;
}
break;
case "crossroad":
switch(yourChoice)
{
case"c1":
break;
case"c2":
break;
case"c3":
ForestEvents.townGate();
break;
case"c4":
break;
}
break;
}
}
}
}
Edit: Added the rest of the code and added the textarea to the scrollpane and the scrollpane to the Jpanel now the text isnt showing up in the panel.
import javax.swing.JTextArea;
public class ForestEvents
{
String pos;
int hp;
public ForestEvents()
{
pos = Game.position;
hp = Game.playerHP;
}
public static void townGate()
{
Game.position = "towngate";
Game.mainTextArea.setText("You are at the gates of the town. A guard is standing in front of you. What do you do? \na\nas\n\n\n\n\\n"
+ "\n\n\n\1\n1\n\n\n\n\n\\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n1\n1\n2\n2\n3\n4\n6");
Game.choice1.setText("Talk to the Guard");
Game.choice2.setText("Attack the Guard");
Game.choice3.setText("Leave");
Game.choice4.setText("");
}
}
You will want to get your JTextArea into JScrollPane, as Adeel said in the comments (+1), then control it with GridBagLayout. No need to set component bounds, preferred size etc. If you want to use GridBagLayout, you have to learn how weights work with fill and anchor. In code below change gbc.fill HORIZONTAL to VERTICAL and swap weights I used for adding scroll to window (so it should be weightx=0,y=1), or change fill to BOTH and make both weights equal to 1 (in this case, you can comment out this empty JLabel I added at the end). Observe and learn.
In your code, you're not setting weights. So, as you may have guessed, everything has the same weight. mainTextArea is added while gbc.fill is HORIZONTAL, no weights and is not inside JScrollPane - that's why it stretches. And be careful with ipads.
SSCCE (comments in code)
public class DontStretchMyTextArea {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setSize(1440, 900);
window.setTitle("W: " + window.getWidth() + " H: " + window.getHeight());
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
window.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTH;
gbc.insets = new Insets(10, 10, 10, 10);
JTextArea mainTextArea = new JTextArea( "This is the main text area" , 10 , 30 ); //here you can set how many rows/columns you want,
//but anyway GridBagLayout will recalculate size of component
//based on gbc.fill, weights and surrounding components
//mainTextArea.setLayout(new GridLayout());
mainTextArea.setLineWrap(true);
mainTextArea.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(mainTextArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints panelGBC = new GridBagConstraints();
panelGBC.weightx = 1; //I want to fill whole panel with JTextArea
panelGBC.weighty = 1; //so both weights =1
panelGBC.fill = GridBagConstraints.BOTH; //and fill is set to BOTH
panel.add(scroll, panelGBC);
panel.setBackground(Color.gray);//this shouldn't be visible
gbc.weightx = 1;
gbc.weighty = 0;
window.add(panel, gbc);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx++;
window.add(new JLabel(), gbc); //GridBagLayout always needs component with both weights =1
SwingUtilities.invokeLater(() -> { //we get our frame on EDT
window.pack();
window.setVisible(true);
});
}
}
How to use GridBagLayout
You can also add scroll directly to window. panel was created just for illustration purposes.
I have a pretty basic GUI organized with a GridBagLayout. The most complex portion is the bottom where West is populated with ScrollPane and the right is a panel with a CardLayout that has multiple ChartPanels so I can switch between a few graphs.
My issue comes when I start the program.
The resizing issue goes away after I resize the frame in any direction. I have confirmed the chartpanel is the issue because not adding this to the CardLayout panel fixes it. I create a blank ChartPanel and populate it later after some action is taken but this is what I've done:
public class Tester {
public static void main(String[] args) {
JFrame frame = new JFrame("Chipmunk: Variant Data Collection Tool");
JPanel hotspotPanel = new JPanel(new CardLayout());
ChartPanel subHotspotPanel = new ChartPanel(null);
JPanel indelHotspotPanel = new JPanel(new BorderLayout());
JTextPane resultPane = new JTextPane();
JPanel main = new JPanel(new GridBagLayout());
JPanel header = new JPanel(new BorderLayout());
header.setBackground(Color.WHITE);
frame.setLayout(new BorderLayout());
frame.setMinimumSize(new Dimension(875, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
resultPane.setOpaque(false);
resultPane.setEditable(false);
GridBagConstraints c = new GridBagConstraints();
DocumentFilter filter = new UppercaseDocumentFilter();
JTextField geneField = new JTextField(10);
((AbstractDocument) geneField.getDocument()).setDocumentFilter(filter);
geneField.setMinimumSize(geneField.getPreferredSize());
JTextField proEffField = new JTextField(10);
proEffField.setMinimumSize(proEffField.getPreferredSize());
String[] mutTypes = { "missense", "nonsense", "frameshift", "nonframeshift"};
JComboBox<String> mutTypeComboBox = new JComboBox<String>(mutTypes);
JButton saveResultsButton = new JButton("Save to TSV");
JPanel glass = (JPanel) frame.getGlassPane();
JButton clearButton = new JButton("Clear");
JButton cosmicButton = new JButton("To COSMIC");
JButton dataButton = new JButton("Show Data");
dataButton.setEnabled(false);
JButton goButton = new JButton("GO");
c.weightx = 1.0;c.gridx = 0;c.gridy = 0;c.anchor = GridBagConstraints.EAST;c.ipadx=5;c.ipady=5;
main.add(new JLabel("Gene: "), c);
c.gridx = 1;c.gridy = 0;c.anchor = GridBagConstraints.WEST;
main.add(geneField, c);
c.gridx = 0;c.gridy = 1;c.anchor = GridBagConstraints.EAST;
main.add(new JLabel("Protein Effect: "), c);
c.gridx = 1;c.gridy = 1;c.anchor = GridBagConstraints.WEST;
main.add(proEffField, c);
c.gridx =0;c.gridy = 2;c.anchor = GridBagConstraints.EAST;
main.add(new JLabel("Mutation Type: "), c);
c.gridx =1;c.gridy = 2;c.anchor = GridBagConstraints.WEST;
main.add(mutTypeComboBox, c);
c.gridx =0;c.gridy = 3;c.anchor = GridBagConstraints.WEST;
main.add(saveResultsButton, c);
c.gridx = 0;c.gridy = 3;c.anchor = GridBagConstraints.EAST;
main.add(goButton, c);
c.gridx = 1;c.gridy = 3;c.anchor = GridBagConstraints.WEST;
main.add(clearButton,c);
c.gridx = 0;c.gridy = 3;c.anchor = GridBagConstraints.CENTER;
main.add(dataButton,c);
c.gridx = 1;c.gridy = 3;c.anchor = GridBagConstraints.EAST;
main.add(cosmicButton,c);
c.gridx = 0; c.gridy =4;c.gridwidth =1; c.weightx = 1.0;c.weighty = 1.0; c.fill = GridBagConstraints.BOTH;
JScrollPane scrollPane = new JScrollPane(resultPane);
main.add(scrollPane, c);
c.gridx = 1; c.gridy =4;c.gridwidth = 1; c.weightx = 1.0;c.weighty = 1.0; c.fill = GridBagConstraints.BOTH;
hotspotPanel.add(subHotspotPanel, "SUBPANEL");
hotspotPanel.add(indelHotspotPanel, "INDELPANEL");
hotspotPanel.add(new JPanel(), "BLANK");
main.add(hotspotPanel, c);
frame.add(header, BorderLayout.NORTH);
frame.add(main, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Using this example, it's clear that a ChartPanel works correctly in a CardLayout. The example below overrides getPreferredSize(), as shown here, to establish an initial size for the ChartPanel. The use of GridLayout on each card allows the chart to fill the panel as the enclosing frame is resized.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
/**
* #see https://stackoverflow.com/a/36392696/230513
* #see https://stackoverflow.com/a/36243395/230513
*/
public class CardPanel extends JPanel {
private static final Random r = new Random();
private static final JPanel cards = new JPanel(new CardLayout());
private final String name;
public CardPanel(String name) {
super(new GridLayout());
this.name = name;
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("One", r.nextInt(10) + 10);
pieDataset.setValue("Two", r.nextInt(20) + 10);
pieDataset.setValue("Three", r.nextInt(30) + 10);
JFreeChart chart = ChartFactory.createPieChart3D(
"3D Pie Chart", pieDataset, true, true, true);
chart.setTitle(name);
this.add(new ChartPanel(chart) {
#Override
public Dimension getPreferredSize() {
return new Dimension(500, (int)(500 * 0.62));
}
});
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i < 9; i++) {
CardPanel p = new CardPanel("Chart " + String.valueOf(i));
cards.add(p, p.toString());
}
JPanel control = new JPanel();
control.add(new JButton(new AbstractAction("\u22b2Prev") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.previous(cards);
}
}));
control.add(new JButton(new AbstractAction("Next\u22b3") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
}));
f.add(cards, BorderLayout.CENTER);
f.add(control, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
I am designing an application, in which there should be 5 different JPanels containing different Swing components. For the JRadioButton part, I ran into an issue for which couldn't find proper solution. The 'radioSizePanel' is supposed to be placed somewhere in upper middle of the main panel. Has anyone solved this problem before ? Here is the code, that I am using :
import java.awt.*;
import javax.swing.*;
public class PizzaShop extends JFrame
{
private static final long serialVersionUID = 1L;
private JRadioButton[] radio_size = new JRadioButton[3];
private JRadioButton[] radio_type = new JRadioButton[3];
public PizzaShop()
{
initializaUI();
}
private void initializaUI()
{
setSize(700, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel container to wrap checkboxes and radio buttons
JPanel panel = new JPanel();
//sizes radio buttons
String Size[] = {"Small: $6.50", "Medium: $8.50", "Large: $10.00"};
JPanel radioSizePanel = new JPanel(new GridLayout(3, 1));
ButtonGroup radioSizeGroup = new ButtonGroup();
for (int i=0; i<3; i++)
{
radio_size[i] = new JRadioButton(Size[i]);
radioSizePanel.add(radio_size[i]);
radioSizeGroup.add(radio_size[i]);
}
radioSizePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Size"));
radioSizePanel.setPreferredSize(new Dimension(100, 200));
//
panel.add(radioSizePanel);
setContentPane(panel);
setContentPane(radioSizePanel);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PizzaShop().setVisible(true);
}
});
}
}
Here is what I want as an expected OUTPUT :
Please do watch the code example and Please do watch everything carefully , the sequence of adding things to the JFrame. Since in your example you calling setSize() much before something has been added to the JFrame, hence first add components to the container, and then call it's pack()/setSize() methods, so that it can realize that in a good way.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PizzaLayout
{
/*
* Five JPanels we will be using.
*/
private JPanel headerPanel;
private JPanel footerPanel;
// This JPanel will contain the middle components.
private JPanel centerPanel;
private JPanel toppingPanel;
private JPanel sizePanel;
private JPanel typePanel;
private JPanel buttonPanel;
private String[] toppings = {
"Tomato",
"Green Pepper",
"Black Olives",
"Mushrooms",
"Extra Cheese",
"Pepproni",
"Sausage"
};
private JCheckBox[] toppingsCBox;
private String[] sizePizza = {
"Small $6.50",
"Medium $8.50",
"Large $10.00"
};
private JRadioButton[] sizePizzaRButton;
private String[] typePizza = {
"Thin Crust",
"Medium Crust",
"Pan"
};
private JRadioButton[] typePizzaRButton;
private JButton processButton;
private ButtonGroup bGroupType, bGroupSize;
private JTextArea orderTArea;
private StringBuilder sBuilderOrder;
private void displayGUI()
{
JFrame frame = new JFrame("Pizza Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*
* This JPanel is the base of all the
* other components, and at the end
* we will set this as Content Pane
* for the JFrame.
*/
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(10, 10, 10, 10));
/*
* TOP PART of the LAYOUT.
*/
headerPanel = new JPanel();
JLabel headerLabel = new JLabel(
"Welcome to Home Style Pizza Shop"
, JLabel.CENTER);
headerLabel.setForeground(Color.RED);
headerPanel.add(headerLabel);
/*
* CENTER PART of the LAYOUT.
*/
centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 2;
gbc.weightx = 0.3;
gbc.weighty = 1.0;
/*
* Above Constraints are for this part.
*/
toppingPanel = new JPanel();
toppingPanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Each Topping $1.50"));
JPanel checkBoxesPanel = new JPanel();
checkBoxesPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
checkBoxesPanel.setLayout(new GridLayout(0, 1, 5, 5));
toppingsCBox = new JCheckBox[toppings.length];
for (int i = 0; i < toppings.length; i++)
{
toppingsCBox[i] = new JCheckBox(toppings[i]);
checkBoxesPanel.add(toppingsCBox[i]);
}
toppingPanel.add(checkBoxesPanel);
centerPanel.add(toppingPanel, gbc);
// Till this.
gbc.gridx = 1;
gbc.gridheight = 1;
gbc.weighty = 0.7;
/*
* Above Constraints are for this part.
*/
sizePanel = new JPanel();
sizePanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Pizza Size"));
JPanel radioBoxesPanel = new JPanel();
radioBoxesPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
radioBoxesPanel.setLayout(new GridLayout(0, 1, 10, 10));
sizePizzaRButton = new JRadioButton[sizePizza.length];
bGroupSize = new ButtonGroup();
for (int i = 0; i < sizePizza.length; i++)
{
sizePizzaRButton[i] = new JRadioButton(sizePizza[i]);
bGroupSize.add(sizePizzaRButton[i]);
radioBoxesPanel.add(sizePizzaRButton[i]);
}
sizePanel.add(radioBoxesPanel);
centerPanel.add(sizePanel, gbc);
// Till this.
gbc.gridx = 2;
gbc.weighty = 0.7;
/*
* Above Constraints are for this part.
*/
typePanel = new JPanel();
typePanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.RED),
"Pizza Type"));
JPanel radioBoxesTypePanel = new JPanel();
radioBoxesTypePanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
radioBoxesTypePanel.setLayout(new GridLayout(0, 1, 10, 10));
typePizzaRButton = new JRadioButton[typePizza.length];
bGroupType = new ButtonGroup();
for (int i = 0; i < typePizza.length; i++)
{
typePizzaRButton[i] = new JRadioButton(typePizza[i]);
bGroupType.add(typePizzaRButton[i]);
radioBoxesTypePanel.add(typePizzaRButton[i]);
}
typePanel.add(radioBoxesTypePanel);
centerPanel.add(typePanel, gbc);
// Till this.
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weighty = 0.3;
gbc.gridwidth = 2;
processButton = new JButton("Process Selection");
processButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
sBuilderOrder = new StringBuilder();
sBuilderOrder.append("Pizza type : ");
for (int i = 0; i < typePizza.length; i++)
{
if (typePizzaRButton[i].isSelected())
sBuilderOrder.append(typePizzaRButton[i].getText());
}
sBuilderOrder.append("\n");
sBuilderOrder.append("Pizza Size : ");
for (int i = 0; i < sizePizza.length; i++)
{
if (sizePizzaRButton[i].isSelected())
sBuilderOrder.append(sizePizzaRButton[i].getText());
}
sBuilderOrder.append("\n");
sBuilderOrder.append("Toppings : ");
/*
* I hope you can do this part yourself now :-)
*/
orderTArea.setText(sBuilderOrder.toString());
}
});
centerPanel.add(processButton, gbc);
footerPanel = new JPanel();
footerPanel.setLayout(new BorderLayout(5, 5));
footerPanel.setBorder(
BorderFactory.createTitledBorder("Your Order : "));
orderTArea = new JTextArea(10, 10);
footerPanel.add(orderTArea, BorderLayout.CENTER);
contentPane.add(headerPanel, BorderLayout.PAGE_START);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new PizzaLayout().displayGUI();
}
});
}
}
Here is the output of the same :
Another problem with swing. How can I stop GridBagLayout from respacing components if one of them changes size? For example, I have few columns, in one of which there is a JLabel with text "text". When I change it to "texttext" layout manager resizes the whole column. I don't want it to do that. Is there any way to prevent it?
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ResizeIssue {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
It is visible while 9 -> 10 or anytime text changes width.
GridBagLayout ignores maximumWidth/Height. There's not an easy way to set the maximum size of the JLabel.
But, what I think you really want is the layout to not shift when the text in the JLabel changes.
That can be done by making the JLabel wide enough to hold the largest value it needs to display. For example:
jLabel1.setFont(new Font("monospace", Font.PLAIN, 12));
FontMetrics fm = jLabel1.getFontMetrics(jLabel1.getFont());
int w = fm.stringWidth("0000");
int h = fm.getHeight();
Dimension size = new Dimension(w, h);
jLabel1.setMinimumSize(size);
jLabel1.setPreferredSize(size);
Update:
To center the label text, just add:
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
This might work:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ResizeIssue2 {
static int value = 99;
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel valueLabel = new JLabel(String.valueOf(value));
JButton decButton = new JButton("-");
decButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(--value));
}
});
JButton incButton = new JButton("+");
incButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
valueLabel.setText(String.valueOf(++value));
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel.add(decButton, c);
c.gridx = 1;
panel.add(valueLabel, c);
c.gridx = 2;
panel.add(incButton, c);
//*
c.gridy = 1;
int w = 32; //incButton.getPreferredSize().width;
for(c.gridx=0;c.gridx<3;c.gridx++) {
panel.add(Box.createHorizontalStrut(w), c);
}
// */
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
I need to display a single component within a JPanel, and I want to keep that component in bottom right corner at all times. I tried to do it with GridBagLayout:
val infoArea = new TextArea {
text = "Hello!"
border = Swing.EmptyBorder(30)
background = Color.RED
editable = false
}
val p = new JPanel
p.setLayout(new GridBagLayout)
val c = new GridBagConstraints
c.gridx = 0
c.gridy = 0
c.anchor = GridBagConstraints.LAST_LINE_END
p.add(infoArea.peer,c)
val f = new JFrame
f.setContentPane(p)
f.setVisible(true)
But the text area is at the center for some reason:
What am I doing wrong here?
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
public class LayoutDemo {
private static void createAndShowGui() {
JLabel label = new JLabel("Hello");
label.setOpaque(true);
label.setBackground(Color.red);
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(label, BorderLayout.LINE_END);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
mainPanel.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame("LayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
frame.add(Box.createGlue(), gbc);
final JTextArea textArea = new JTextArea("SE");
textArea.setPreferredSize(new Dimension(50, 50));
textArea.setOpaque(true);
textArea.setBackground(Color.RED);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
frame.add(textArea, gbc);
frame.setSize(640, 480);
frame.setVisible(true);
...if you realy want to use GridBagLayout
you have to put a dummy (use Box.createGlue() to make a dummy component) component on gridx = 0 and gridy = 0 and the component you want to put at the bottom right at gridx = 1, gridy = 1.like this