I have got a JTextArea and a JTextField and now i want that if i click on JTextArea button the control shifts to JTextArea and
when i click the JTextField button control shifts to JTextField. I am
not getting anything to do such stuff.
The program just changes the text in the JTextField based on the JRadioButton clicked.
***This is the code:***
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class prg_32 extends JPanel implements ItemListener{
JTextArea a1;
JButton t1,t2;
JRadioButton b1,b2,b3,b4;
JTextField fld1;
ButtonGroup grp;
GridBagConstraints gbc = new GridBagConstraints(); //GridBagConstraints object
public prg_32(){
setLayout(new GridBagLayout());
a1 = new JTextArea(3,10); //TextArea
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 3;
gbc.fill = GridBagConstraints.VERTICAL;
add(a1,gbc); //location of JTextArea
t1 = new JButton("TextArea");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridheight = 1;
add(t1,gbc); //location of JButton
t2 = new JButton("TextField");
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridheight = 1;
add(t2,gbc); //location of JButton
b1 = new JRadioButton("Bold",false);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridheight = 1;
add(b1,gbc);
b2 = new JRadioButton("Italic",false);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridheight = 1;
add(b2,gbc);
b3 = new JRadioButton("Plain",false);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridheight = 1;
add(b3,gbc);
b4 = new JRadioButton("Bold/Italic",true);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.gridheight = 1;
add(b4,gbc);
grp = new ButtonGroup();
grp.add(b1);
grp.add(b2);
grp.add(b3);
grp.add(b4);
fld1 = new JTextField("enter your name");
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(fld1,gbc);
fld1.setFont(new Font("Serif",Font.BOLD + Font.ITALIC,14));
b1.addItemListener(this); //Event Handling
b2.addItemListener(this); //Event Handling
b3.addItemListener(this); //Event Handling
b4.addItemListener(this); //Event Handling
}
public void itemStateChanged(ItemEvent e) {
Font font = null;
if(b1.isSelected())
font = new Font("Serif",Font.BOLD,14);
else if(b2.isSelected())
font = new Font("Serif",Font.ITALIC,14);
else if(b3.isSelected())
font = new Font("Serif",Font.PLAIN,14);
else
font = new Font("Serif",Font.BOLD + Font.ITALIC,14);
fld1.setFont(font);
}
public static void main(String[] args){
prg_32 px = new prg_32();
JFrame jf = new JFrame();
jf.setSize(500, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(px);
}
}
I would suggest implementing an ActionListener and using the method Component.requestFocus() in it to set the focus on the text fields.
t1 = new JButton("TextArea");
t1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
a1.requestFocus();
}
});
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridheight = 1;
add(t1,gbc); //location of JButton
t2 = new JButton("TextField");
t2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fld1.requestFocus();
}
});
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridheight = 1;
add(t2,gbc);
Related
I am currently trying to include a JTable to my JPanel. I was not having any problems with my code previously until I started to code the table. Sometimes when I run my program everything will appear, sometimes just the panels appear, and sometimes/majority of the time nothing will appear. I just don't understand why it is not consistent. There are no errors in the console. I have included below my ViewPage.java, Page.java, and Main.java.
`
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ViewPage extends Page implements ActionListener
{
JPanel panel1, panel2, panel3;
JLabel searchLabel, repairsLabel, dateLabel;
JButton goButton, recentButton, oldestButton, homeButton;
JComboBox dropDown;
JTextField textField;
JTable tabel;
JScrollPane scrollpane;
public ViewPage()
{
panel1 = new JPanel();
panel1.setBackground(Color.blue);
panel1.setBounds(0,0,1280,120);
panel2 = new JPanel();
panel2.setBackground(Color.green);
panel2.setBounds(0,120,1280,480);
panel3 = new JPanel();
panel3.setBackground(Color.red);
panel3.setBounds(0,600,1280,120);
//Panel 1 components
repairsLabel = new JLabel("Repairs");
repairsLabel.setFont(new Font("Serif", Font.BOLD, 50));
searchLabel = new JLabel("Search :");
searchLabel.setFont(new Font("Serif", Font.PLAIN, 25));
goButton = new JButton("GO");
goButton.setFocusable(false);
goButton.addActionListener(this);
textField = new JTextField();
String[] filters = {" ", "customerID", "First_Name", "Last_Name"};
dropDown = new JComboBox(filters);
dropDown.addActionListener(this);
panel1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 0);
gbc.weightx = 5.5;
gbc.gridx = 0;
gbc.gridy = 0;
panel1.add(repairsLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.5;
gbc.gridx = 1;
gbc.gridy = 0;
panel1.add(searchLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.weightx = 3;
gbc.gridx = 2;
gbc.gridy = 0;
panel1.add(dropDown, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.ipadx = 100;
panel1.add(textField, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 100);
gbc.gridx = 4;
gbc.gridy = 0;
gbc.ipadx = 1;
panel1.add(goButton, gbc);
//Panel 2 components
panel2.setLayout(new GridBagLayout());
String[][] data = new String[50][8];
String[] headings = {"customer_ID", "Date", "First Name", "Last Name", "Phone #", "OS", "PC Type", "Problem"};
JTable table = new JTable(data, headings);
table.setEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(1000,400));
table.setFillsViewportHeight(true);
scrollpane = new JScrollPane(table);
panel2.add(scrollpane);
//Panel 3 componets
panel3.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
dateLabel = new JLabel("Date Filter: ");
dateLabel.setFont(new Font("Serif", Font.PLAIN, 25));
recentButton = new JButton("Most Recent");
oldestButton = new JButton("Oldest");
homeButton = new JButton("Home");
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(1, 10, 1, 0);
gbc2.weightx = 5.5;
gbc2.gridx = 0;
gbc2.gridy = 0;
panel3.add(dateLabel, gbc);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == dropDown)
{
System.out.println(dropDown.getSelectedItem());
}
}
}
`
`
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public abstract class Page
{
private final static int pageWidth = 1280;
private final static int pageHeight = 720;
protected JFrame frame;
public Page()
{
frame = new JFrame();
frame.setTitle("Computer Repair Store");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(pageWidth, pageHeight);
frame.setLayout(null);
frame.setVisible(true);
}
public int getpageWidth()
{
return pageWidth;
}
public int getpageHeight()
{
return pageHeight;
}
}
`
`
public class Main {
public static void main(String[] args) {
ViewPage viewPage = new ViewPage();
}
}
`
Ouput:
enter image description here
This is what I am expecting to output which has only appeared 2-3 times out of the 50 times I have tried running the program.
enter image description here
I've searched half the internet and I can't find anybody who has had this same problem.
I've tried several different ways to add a vertical scroll bar, but in vain. Every other post I've seen describing this problem did the following:
JTextArea ta = new JTextArea();
JScrollPane sc = new JScrollPane(ta);
and that seemed to work for them. But I'm out of luck and have tried at least thirty different ways that I've found. I'm new to java and the class I'm in is killing me. Thanks for your time.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame
private JTextArea outputArea {
private JButton eastButton;
private JButton westButton;
private JButton northButton;
private JButton southButton;
private JButton helpButton;
private JButton pickupButton;
private JButton dropButton;
private JButton eatButton;
private JButton lookButton;
private JButton listButton;
private JScrollPane scroll;
Gui() {
int x = 0;
int y = 0;
int Width = 1;
int Height = 2;
int anchor;
GridBagConstraints gbc = new GridBagConstraints();
JLabel actionsLabel = null;
JLabel directionsLabel = null;
getContentPane().setBackground(Color.black);
setTitle("Castle Quest");
actionsLabel = new JLabel("Actions");
actionsLabel.setForeground(Color.red);
directionsLabel = new JLabel("Directions");
directionsLabel.setForeground(Color.red);
outputArea = new JTextArea(25, 35);
scroll = new JScrollPane(outputArea);
eastButton = new JButton("east");
eastButton.setSize(100, 30);
westButton = new JButton("west");
westButton.setSize(100, 30);
northButton = new JButton("north");
northButton.setSize(100, 30);
southButton = new JButton("south");
southButton.setSize(100, 30);
helpButton = new JButton("help");
helpButton.setSize(100, 30);
pickupButton = new JButton("pickup");
pickupButton.setSize(100, 30);
dropButton = new JButton("Drop");
dropButton.setSize(100, 30);
eatButton = new JButton("eat");
lookButton = new JButton("look");
lookButton.setSize(100, 30);
listButton = new JButton("list");
listButton.setSize(100, 30);
outputArea.setEditable(true);
GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
gbc.insets = new Insets(10, 10, 10, 10);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 2;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(actionsLabel, gbc);
gbc.gridy += 2;
add(helpButton, gbc);
gbc.gridy += 2;
add(pickupButton, gbc);
gbc.gridy += 2;
add(dropButton, gbc);
gbc.gridy += 2;
add(eatButton, gbc);
gbc.gridy += 2;
add(lookButton, gbc);
gbc.gridy += 2;
add(listButton, gbc);
gbc.gridy = 1;
gbc.gridx = 2;
gbc.gridheight = 50;
outputArea.setBackground(Color.red);
add(outputArea, gbc);
gbc.gridheight = 2;
gbc.gridx = 3;
gbc.gridy = 1;
add(directionsLabel, gbc);
gbc.gridy = 3;
add(eastButton, gbc);
gbc.gridy += 2;
add(westButton, gbc);
gbc.gridy += 2;
add(northButton, gbc);
gbc.gridy += 2;
add(southButton, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
}
public static void main(String[] args) {
Gui newGame = new Gui();
Game funTime = new Game();
newGame.setSize(400, 150);
newGame.setBackground(Color.black);
newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newGame.pack();
newGame.setVisible(true);
newGame.outputArea.setLineWrap(true);
newGame.outputArea.setWrapStyleWord(true);
newGame.outputArea.append(funTime.getMessage() + "\n");
newGame.eastButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("east");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.westButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("west");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.northButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("north");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.southButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("south");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.getHelp();
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.pickupButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (funTime.currentLocation.hasItem()) {
funTime.pickupItem();
newGame.outputArea.append(funTime.getMessage() + "\n");
}
}
});
newGame.listButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < funTime.items.size(); i++) {
System.out.println(funTime.items.get(i));
}
System.out.println(funTime.items);
System.out.println(funTime.currentLocation.getRoomItem1() + " & " + funTime.currentLocation.getRoomItem2());
}
});
}
}
The problem you're facing (the JTextArea expanding) is caused by the fact that you added the JTextArea to the container instead of the JScrollPane.
Here is the logic behind what you should do :
JTextArea is contained by JScrollPane and JScrollPane is contained by the JFrame.
Change this line
add(outputArea, gbc);
to this
add(scroll, gbc);
I made a new class that extended JFrame and new class that extended JPanel to make the swing GUI. It is great, I like this due to its ease of readability.
However, when it comes to event handling things started getting complex. What I did really doesn't really seem like a solution; just like breaking good habit to make something work. How do I make this work properly?
This is my JFrame class
public class MainFrame extends JFrame{
private JTextArea textArea;
public MainFrame(String title){
super(title);
//set layout
setLayout(new BorderLayout());
//create components
JButton buttonOne = new JButton("click me");
textArea = new JTextArea();
JPanel detailedPanel = new leftPanel();
//add to panel
Container c = getContentPane();
c.add(buttonOne, BorderLayout.SOUTH);
c.add(textArea, BorderLayout.CENTER);
c.add(detailedPanel, BorderLayout.WEST);
//Event Listening
leftPanel.buttonAdd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
textArea.setText(textArea.getText() + " " + leftPanel.fieldName.getText() + " : " + leftPanel.fieldOccupation.getText());
}
});
}
}
this is my JPanel
public class leftPanel extends JPanel {
public static JTextField fieldName;
public static JTextField fieldOccupation;
public static JButton buttonAdd;
public leftPanel(){
Dimension panelSize = getPreferredSize();
panelSize.width = 250;
setPreferredSize(panelSize);
setBorder(BorderFactory.createTitledBorder("Personal Info"));
//labels
JLabel labelName = new JLabel("name: ");
JLabel labelOccupation = new JLabel("Occupation: ");
//textFields
fieldName = new JTextField(10);
fieldOccupation = new JTextField(10);
//buttons
buttonAdd = new JButton("Add !");
//actions
buttonAdd.addActionListener(new ActionListener(){
//on click
public void actionPerformed(ActionEvent e) {
String name = fieldName.getText();
String occupation = fieldOccupation.getText();
System.out.print(name + ": " + occupation);
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//// First Y add //////////////////////////////////////
//label NAME
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 0;
add(labelName, gbc);
//label Occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 1;
add(labelOccupation, gbc);
//// SECOND Y add /////////////////////////////////////
//text field name
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 0;
add(fieldName, gbc);
//text feld occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 1;
add(fieldOccupation, gbc);
//// THIRD Y add //////////////////////////////////////
//add button
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.weightx = 1;
gbc.weighty = 10;
add(buttonAdd, gbc);
}
}
For the most part, you component should be as self contained as possible, this would suggest that the component should be responsible for handling the events generated by it's immediate children.
This doesn't mean that the component won't then generate it's own events, but that the component manages it's immediate children itself.
You should try and avoid exposing your child components directly (using public fields or getters) or indirectly (through event objects), this invites possible misuse of those components by external sources, which is never going to be pleasant.
In your example, your first class only wants to known when something happens that would require it to update the text area.
This would suggest that the LeftPanel needs to generate some kind of event (maybe a ActionEvent) and provide a getter for anybody who might be interested to gain access to the information that the LeftPanel is managing.
For example...
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LeftPanel extends JPanel {
private JTextField fieldName;
private JTextField fieldOccupation;
private JButton buttonAdd;
public LeftPanel() {
setBorder(BorderFactory.createTitledBorder("Personal Info"));
//labels
JLabel labelName = new JLabel("name: ");
JLabel labelOccupation = new JLabel("Occupation: ");
//textFields
fieldName = new JTextField(10);
fieldOccupation = new JTextField(10);
//buttons
buttonAdd = new JButton("Add !");
//actions
buttonAdd.addActionListener(new ActionListener() {
//on click
public void actionPerformed(ActionEvent e) {
fireActionPerformed();
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//// First Y add //////////////////////////////////////
//label NAME
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 0;
add(labelName, gbc);
//label Occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 1;
add(labelOccupation, gbc);
//// SECOND Y add /////////////////////////////////////
//text field name
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 0;
add(fieldName, gbc);
//text feld occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 1;
add(fieldOccupation, gbc);
//// THIRD Y add //////////////////////////////////////
//add button
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.weightx = 1;
gbc.weighty = 10;
add(buttonAdd, gbc);
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners.length > 0) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "PropertiesSet");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
public String getPersonName() {
return fieldName.getText();
}
public String getPersonOccupation() {
return fieldOccupation.getText();
}
}
The LeftPanel here now manages the internal state of it's components (no static or public fields). It also provides a ActionListener support to provide notification to interested parties who can obtain the information the component is managing via getters
The MainFrame then simply uses an instance of LeftPanel and registers a ActionListener to it so it can be notified when the panel has been updated and uses the getters to obtain the information it's interested in.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
private JTextArea textArea;
public MainFrame(String title) {
super(title);
//set layout
setLayout(new BorderLayout());
//create components
JButton buttonOne = new JButton("click me");
textArea = new JTextArea();
LeftPanel detailedPanel = new LeftPanel();
//add to panel
Container c = getContentPane();
c.add(buttonOne, BorderLayout.SOUTH);
c.add(textArea, BorderLayout.CENTER);
c.add(detailedPanel, BorderLayout.WEST);
//Event Listening
detailedPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.append(textArea.getText() + " " + detailedPanel.getPersonName() + " : " + detailedPanel.getPersonOccupation() + "\n");
}
});
}
}
In OO, you want to encapsulate the logic and responsibility to the object and then, as required, from callbacks (such as a Observer Pattern) to provide notification to interested parties that some predefined state has changed. Then simply expose the information that the object is managing via getters (and where required, setters for others to change the information as required)
Please have a look at the following code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestForm extends JFrame
{
private JLabel firstLabel, secondLabel;
private JTextField firstTxt, secondTxt;
private GridBagLayout mainLayout = new GridBagLayout();
private GridBagConstraints mainCons = new GridBagConstraints();
private JPanel centerPanel;
public TestForm()
{
this.setLayout(mainLayout);
//Declaring instance variables
firstLabel = new JLabel("First: ");
secondLabel = new JLabel("Second: ");
firstTxt = new JTextField(7);
secondTxt = new JTextField(7);
mainCons.anchor = GridBagConstraints.WEST;
mainCons.weightx = 1;
mainCons.gridy = 2;
mainCons.gridx = 1;
mainCons.insets = new Insets(15, 0, 0, 0);
this.add(createCenterPanel(), mainCons);
System.out.println("Center Panel Width: "+centerPanel.getWidth());
this.setTitle("The Test Form");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenterPanel()
{
centerPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
centerPanel.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,10,0,0);
centerPanel.add(secondLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,-10,0,0);
centerPanel.add(secondTxt,gbc);
centerPanel.setBorder(BorderFactory.createTitledBorder("The Testing Form"));
centerPanel.setPreferredSize(centerPanel.getPreferredSize());
centerPanel.validate();
System.out.println("Width is: "+centerPanel.getWidth());
System.out.println("Width is: "+centerPanel.getHeight());
return centerPanel;
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new TestForm();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I am trying to get the width of the centerPanel in 2 places. But in both cases, I get 0 as the answer! I must get the width and height somehow because the southPanel (not included here) will use those values, with some reduce to the height. Please help!
The width is 0 before pack() or setSize() is called. You can get the width and use it after pack() call
or
define your own LayoutManager which use the width for the height of another layout part (southPanel)
I see that GridBagLayout positions it's children with center alignment within cells. How to align left or right?
UPDATE
Constructing code (I know I could reuse c)
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
// placing controls to dialog
GridBagConstraints c;
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
add(inputSource_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
add(inputSource_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
add(output_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
add(output_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
add(button_panel, c);
When using GridBagLayout for a tabular display of JLabel : JTextField, I like to have a method that makes my GridBagConstraints for me based on the x, y position. For example something like so:
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
The following code makes a GUI that looks like this:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class GridBagEg {
private static void createAndShowGui() {
PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();
int result = JOptionPane.showConfirmDialog(null, playerEditorPane,
"Edit Player", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
// TODO: do something with info
for (PlayerEditorPanel.FieldTitle fieldTitle :
PlayerEditorPanel.FieldTitle.values()) {
System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
playerEditorPane.getFieldText(fieldTitle));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
enum FieldTitle {
NAME("Name"), SPEED("Speed"), STRENGTH("Strength");
private String title;
private FieldTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
};
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
public PlayerEditorPanel() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Player Editor"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
GridBagConstraints gbc;
for (int i = 0; i < FieldTitle.values().length; i++) {
FieldTitle fieldTitle = FieldTitle.values()[i];
gbc = createGbc(0, i);
add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
gbc = createGbc(1, i);
JTextField textField = new JTextField(10);
add(textField, gbc);
fieldMap.put(fieldTitle, textField);
}
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
public String getFieldText(FieldTitle fieldTitle) {
return fieldMap.get(fieldTitle).getText();
}
}
In this example, I display the JPanel in a JOptionPane, but it could just as easily be displayed in a JFrame or JApplet or JDialog or ...
For example
public class DimsPanel extends JPanel
{
public static void main(String[] args){
JFrame main = new JFrame("Dims");
JPanel myPanel = new DimsPanel();
main.setContentPane(myPanel);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(400, 400);
main.setLocationRelativeTo(null);
main.setVisible(true);
}
JButton ok_button = new JButton("OK"), cancel_button = new JButton("Cancel");
JLabel inputSource_label = new JLabel("Input source:"),
output_label = new JLabel("Output:");
JComboBox inputSource_combo = new JComboBox(new String[]{"A", "B", "C"}),
output_combo = new JComboBox(new String[]{"A", "B", "C"});
public DimsPanel(){
super(new BorderLayout());
Box main = new Box(BoxLayout.Y_AXIS);
Dimension labelsWidth = new Dimension(100, 0);
JPanel inputPanel = new JPanel(new BorderLayout());
inputSource_label.setPreferredSize(labelsWidth);
inputPanel.add(inputSource_label, BorderLayout.WEST);
inputPanel.add(inputSource_combo);
JPanel outputPanel = new JPanel(new BorderLayout());
output_label.setPreferredSize(labelsWidth);
outputPanel.add(output_label, BorderLayout.WEST);
outputPanel.add(output_combo);
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
main.add(inputPanel);
main.add(outputPanel);
add(main, BorderLayout.NORTH);
add(button_panel);
}
}
You can run and see it. Resizing works like a charm and the layout code has only 18 lines.
The only disadvantage is that you need to specify the width of the labels by hand. If you really don't want to see setPreferredSize() in the code, then be my guest and go with GridBag. But I personally like this code more.