I have a JTextArea named as txtChat which is used as the chatting area in my chatbot. I have created a JScrollPane scroll = new JScrollPane(txtChat) and added my txtChat inside the JScrollPane. My JTextArea is being put inside a Panel which has BorderLayout, so I have added my scroll to the panel which contains my JTextArea chatPanel.add(scroll, BorderLayout.East). BUT IT IS NOT WORKING! Like when my conversation go longer, the scroll does not appear!
Sorry the code is quite long, so I just pasted the essential parts here.
public class GUI_V3 extends JFrame {
//mainPanel into Frame
private JPanel mainPanel = new JPanel();
//clock component
private JTextField timeF = new JTextField(8);
//Button component
private Box btnBox = Box.createHorizontalBox();
private JButton button1 = new JButton("Add Keywords");
private JButton button2 = new JButton("Help");
//Top menu bar
private JPanel topPanel = new JPanel();
//Typing Area
private JTextField txtEnter = new JTextField();
//Typing Panel
private JPanel typingPanel = new JPanel();
//Chat Area
private JTextArea txtChat = new JTextArea();
private JPanel chatPanel = new JPanel();
//Scroll
private JScrollPane scroll = new JScrollPane(txtChat);
private String name;
private Conversation_V3 convo = new Conversation_V3();
public GUI_V3(){
//Frame attributes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000,1000);
this.setVisible(true);
//this.setResizable(false);
this.setLocationRelativeTo(null);
this.setTitle("Welcome to Haidilao");
//clock attributes
timeF.setEditable(false);
timeF.setFont(new Font("Arial",Font.BOLD,48));
timeF.setBackground(new Color(228,224,199));
timeF.setHorizontalAlignment(SwingConstants.RIGHT);
//button attributes
button1.setFont(new Font("Arial",Font.PLAIN,38));
button2.setFont(new Font("Arial",Font.PLAIN,38));
btnBox.add(button1);
btnBox.add(Box.createRigidArea(new Dimension(10,70)));
btnBox.add(button2);
//Add ActionListener to buttons
Button1Handler handlerB1 = new Button1Handler();
button1.addActionListener(handlerB1);
Button2Handler handlerB2 = new Button2Handler();
button2.addActionListener(handlerB2);
//Top menu bar
topPanel.setLayout(new BorderLayout());
topPanel.add(btnBox, BorderLayout.WEST);
topPanel.add(timeF, BorderLayout.EAST);
topPanel.setBackground(new Color(228,224,199));
//Typing Area Attribute
txtEnter.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
typingPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
typingPanel.setLayout(new BorderLayout());
typingPanel.setBackground(new Color(228,224,199));
typingPanel.add(txtEnter);
//Add action listener for typing area
TypingHandler handlerT = new TypingHandler();
txtEnter.addActionListener(handlerT);
//Chat Area Attribute
txtChat.setEditable(false);
txtChat.setFont(new Font("DejaVu Sans",Font.PLAIN,30));
txtChat.setLineWrap(true);
txtChat.setWrapStyleWord(true);
chatPanel.setBorder(BorderFactory.createEmptyBorder(5,20,10,20));
chatPanel.setLayout(new BorderLayout());
chatPanel.setBackground(new Color(228,224,199));
chatPanel.add(txtChat, BorderLayout.CENTER);
chatPanel.add(scroll, BorderLayout.EAST);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//mainPanel Layout
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(typingPanel, BorderLayout.SOUTH);
mainPanel.add(chatPanel, BorderLayout.CENTER);
//Add components to the JFrame
this.add(mainPanel);
//Add actionListener to clock
ClockHandler handlerC = new ClockHandler();
Timer t = new Timer(500, handlerC);
t.start();
//display greetings and ask for name
name = greetings();
addText(botSays("Welcome! " + name + ", you can ask me anything about the menu by providing keywords."));
}
//Action handler for txtEnter
private class TypingHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//grab input
String input = txtEnter.getText();
//add to chat area
txtChat.append(name + ": " + input + "\n");
//set input field to empty
txtEnter.setText("");
SoundEffect.music();
convo.setInput(input);
addText(botSays(convo.getReply()));
//set the chat area to bottom of scroll
txtChat.setCaretPosition(txtChat.getDocument().getLength());
}
}
Please find a working solution and tweak this as per your requirements.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
}
}
Hope this will be helpful. :-)
Related
A frame which includes panels where buttons are located in a column on the left side of the frame:
I tried to make this picture in real Java code but failed.
I can't find the right solution for this issue...
BorderLayout borderLayout = new BorderLayout();
GridBagLayout gridBagLayout = new GridBagLayout();
GridLayout gridLayout = new GridLayout();
CardLayout cardLayout = new CardLayout();
JPanel panelMain = new JPanel();
JPanel panelLeft = new JPanel();
JPanel panelInnerLeft = new JPanel();
JPanel panelRight = new JPanel();
panelMain.setLayout(borderLayout);
panelLeft.setLayout(gridBagLayout);
panelInnerLeft.setLayout(gridLayout);
panelRight.setLayout(cardLayout);
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button4 = new JButton("Button 4");
panelInnerLeft.add(button1,gridLayout);
panelInnerLeft.add(button2,gridLayout);
panelInnerLeft.add(button3,gridLayout);
panelInnerLeft.add(button4,gridLayout);
panelLeft.add(panelInnerLeft);
panelMain.add(panelLeft);
panelMain.add(panelRight);
add(panelMain);
This is the exact code used to make that screenshot.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class CompoundLayout01 {
private JComponent ui = null;
CompoundLayout01() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new TitledBorder("BorderLayout"));
CardLayout cardLayout = new CardLayout();
JPanel cards = new JPanel(cardLayout);
cards.setBorder(new TitledBorder("CardLayout"));
ui.add(cards);
JPanel lineStart = new JPanel(new GridBagLayout());
lineStart.setBorder(new TitledBorder("GridBagLayout"));
// will appear on the left, in a LTR text orientation locale
ui.add(lineStart, BorderLayout.LINE_START);
JPanel buttonsCentered = new JPanel(new GridLayout(0, 1, 10, 10));
buttonsCentered.setBorder(new TitledBorder("GridLayout"));
// as single component added w/no constraint, will be centered
lineStart.add(buttonsCentered);
for (int ii=1; ii<5; ii++) {
JButton b = new JButton("Button " + ii);
buttonsCentered.add(b);
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
CompoundLayout01 o = new CompoundLayout01();
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);
}
}
panelMain.setLayout(borderLayout);
...
panelMain.add(panelLeft);
panelMain.add(panelRight);
Read the Swing tutorial on Layout Managers.
It will show you how to use the BorderLayout.
You need to specify the "constraint" when you add each component. Like BorderLayout.LINE_START, or BorderLayout.CENTER.
The following is also wrong:
panelInnerLeft.setLayout(gridLayout);
...
panelInnerLeft.add(button1,gridLayout);
panelInnerLeft.add(button2,gridLayout);
panelInnerLeft.add(button3,gridLayout);
panelInnerLeft.add(button4,gridLayout);
Read the section on GridLayout. A GridLayout does not require a constraint.
I don't know if you need some specific layout, but if you want more control, you can take a look at my example. Note that I have to handle some sizes myself. Also if you need even more control you can always use null as layout.
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.SwingUtilities;
public class NewJFrame extends javax.swing.JFrame {
private JPanel jPanel1;
private JButton jButton1;
private JButton jButton2;
private JButton jButton3;
private JPanel jPanel2;
private JButton jButton4;
private JPanel ButtonsPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
NewJFrame inst = new NewJFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public NewJFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
jPanel1 = new JPanel();
getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.setLayout(null);
ButtonsPanel = new JPanel();
FlowLayout ButtonsPanelLayout = new FlowLayout();
jPanel1.add(ButtonsPanel);
ButtonsPanel.setLayout(ButtonsPanelLayout);
ButtonsPanel.setBounds(12, 23, 104, 215);
ButtonsPanel.setBorder(
BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
jButton1 = new JButton();
ButtonsPanel.add(jButton1);
jButton1.setText("jButton1");
jButton1.setPreferredSize(new java.awt.Dimension(85, 23));
jButton2 = new JButton();
ButtonsPanel.add(jButton2);
jButton2.setText("jButton2");
jButton2.setPreferredSize(new java.awt.Dimension(85, 23));
jButton3 = new JButton();
ButtonsPanel.add(jButton3);
jButton3.setText("jButton3");
jButton3.setPreferredSize(new java.awt.Dimension(85, 23));
jButton4 = new JButton();
ButtonsPanel.add(jButton4);
jButton4.setText("jButton4");
jButton4.setPreferredSize(new java.awt.Dimension(85, 23));
jPanel2 = new JPanel();
jPanel1.add(jPanel2);
jPanel2.setLayout(null);
jPanel2.setBounds(122, 23, 250, 215);
jPanel2.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED));
pack();
setSize(400, 300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hello I am trying to add a border or a line break separating the north section from the rest of the JPanel. Basically using set border I have a border around the whole window but then want a line from one section of the border straight across horizontally to the other side. when i add a border to a JPanel that is added to BorderLayout.NORTH it puts a whole border inside the section. not the outline of the section. hope you know what i mean.
Attached I have a section of my code that is holding all my JPanel code in it so far. any help I would love, thanks.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class GamePanel extends JPanel {
private JTextPane playertext;
private JTextField wealthstring, currentwealth;
public GamePanel() {
super();
setLayout(new BorderLayout());
setBackground(Game.getBackgroundColor());
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(4, 4, 4, 4), (BorderFactory.createCompoundBorder(raised, lowered))));
add(northpanel(), BorderLayout.NORTH);
add(eastpanel(), BorderLayout.EAST);
}
private JPanel northpanel() {
Font northfont = new Font("Engravers MT", Font.BOLD, 12);
playertext = new JTextPane();
playertext.setFont(northfont);
playertext.setEditable(false);
playertext.setText("Player: \n" + Game.getName());
playertext.setBackground(Game.getBackgroundColor());
playertext.setBorder(new EmptyBorder(10,10,10,10));
wealthstring = new JTextField("Money: ");
wealthstring.setFont(northfont);
wealthstring.setEditable(false);
wealthstring.setHorizontalAlignment(wealthstring.RIGHT);
wealthstring.setBorder(null);
wealthstring.setBackground(Game.getBackgroundColor());
currentwealth = new JTextField();
currentwealth.setFont(northfont);
currentwealth.setEditable(false);
currentwealth.setHorizontalAlignment(wealthstring.RIGHT);
currentwealth.setBackground(Game.getBackgroundColor());
currentwealth.setBorder(null);
String wealthrounded = String.format("%.2f", Game.getMoney());
currentwealth.setText(wealthrounded);
JPanel wealthtext = new JPanel();
wealthtext.setLayout(new GridLayout(2, 1));
wealthtext.setBackground(Game.getBackgroundColor());
wealthtext.setBorder(new EmptyBorder(10,10,10,10));
wealthtext.add(wealthstring);
wealthtext.add(currentwealth);
JPanel northpanel = new JPanel();
northpanel.setLayout(new BorderLayout());
northpanel.setBackground(Game.getBackgroundColor());
northpanel.add(playertext, BorderLayout.WEST);
northpanel.add(wealthtext, BorderLayout.EAST);
return northpanel;
}
private JPanel eastpanel() {
JButton tab1 = new JButton("Tab 1");
JButton tab2 = new JButton("Tab 2");
JButton tab3 = new JButton("Tab 3");
JPanel easttabs = new JPanel();
easttabs.setLayout(new GridLayout(1, 3));
easttabs.add(tab1);
easttabs.add(tab2);
easttabs.add(tab3);
JPanel eastpanels = new JPanel();
eastpanels.setLayout(new BorderLayout());
eastpanels.add(easttabs, BorderLayout.NORTH);
return eastpanels;
}
}
Like this?
For that we would use a JSeparator.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class UnderlinePageStart {
private JComponent ui = null;
UnderlinePageStart() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel pageStart = new JPanel(new BorderLayout(2,2));
ui.add(pageStart, BorderLayout.PAGE_START);
pageStart.add(new JLabel("Page Start", SwingConstants.CENTER));
// add a 'horizontal line'
pageStart.add(new JSeparator(), BorderLayout.PAGE_END);
ui.add(new JScrollPane(new JTextArea(5, 25)));
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
UnderlinePageStart o = new UnderlinePageStart();
JFrame f = new JFrame("Underline Page Start");
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);
}
}
I was wondering how I would move my buttons to the bottom of the frame/window.
What I have now is this:
And what I want it to look like is this:
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Font;
public class checkbook{
static JButton Button[] = new JButton[8];
JLabel begin, accountName, balance;
JFrame frame;
JPanel jpanel, jpanel1;
Container contentPane;
private JTextField textAccount, textBalance;
public static void main(String[] args){
checkbook checkbook = new checkbook();
checkbook.startFrame();
}
checkbook(){
frame = new JFrame("Checkbook");
}
public void startFrame(){
String bottomButtons[] = {
"Create a New Account", "Load Trans from a file", "Add New Transactions", "Search Transactions",
"Sort Transactions", "View/Delete Transactions", "Backup Transactions", "Exit"
};
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
Font beginFont = new Font("Arial", Font.PLAIN + Font.BOLD, 22);
textAccount = new JTextField(" ", 15);
textBalance = new JTextField("0.0", 15);
begin = new JLabel("Use The Buttons below To Manage Transactions");
begin.setFont(beginFont);
contentPane.add(begin);
//Container contentPane1 = frame.getContentPane();
//contentPane1.setLayout(new FlowLayout());
JPanel jpanel = new JPanel();
accountName = new JLabel ("Account Name: ");
jpanel.add(accountName);
jpanel.add(textAccount);
balance = new JLabel ("Balance: ");
jpanel.add(balance);
jpanel.add(textBalance);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridLayout(2,4));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
jpanel1.add(Button[i]);
//Button[i].addActionListener(AL);
}
frame.pack();
frame.setSize(800, 300);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(jpanel);
frame.add(jpanel1);
}
}
So I was wondering what would I do to move the buttons down to the bottom. Would I have to use a BorderLayout and use BorderLayout.SOUTH etc or is there a way to do this with the GridLayout I already have. If I have to use the BorderLayout how would I keep my buttons in order (2 rows, 4 columns).
Would I have to use a BorderLayout and use BorderLayout.SOUTH
Yes, but the best answer is for you to try it and see what happens. Why don't you?
If I have to use the BorderLayout how would I keep my buttons in order(2 rows, 4 columns).
Nest JPanels. Put the buttons in a GridLayout using JPanel, and place that JPanel BorderLayout.SOUTH, or better, BorderLayout.PAGE_END
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class NestedPanels extends JPanel {
private static final String TITLE_TEXT = "Use The Buttons Below To Manage Transactions";
private static final String[] BTN_TEXTS = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
private static final int TITLE_POINTS = 24;
public NestedPanels() {
JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD,
TITLE_POINTS));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(20));
accountBalancePanel.add(new JLabel("Balance:"));
accountBalancePanel.add(new JTextField(10));
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for (String btnText : BTN_TEXTS) {
southBtnPanel.add(new JButton(btnText));
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(400, 400))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Nested Panels Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:
For some reason I can't get the BorderLayout to set the way it's supposed to. Just would like to know where I'm going wrong.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorFactory extends JFrame
{
final int width = 500;
final int height = 300;
private JPanel buttonPanel;
private JPanel radioButtonPanel;
private JLabel msgChangeColor;
public ColorFactory()
{
setTitle("Color Factory");
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
createTopPanel();
add(buttonPanel, BorderLayout.NORTH);
createBottomPanel();
add(radioButtonPanel, BorderLayout.SOUTH);
msgChangeColor = new JLabel("Top buttons change the panel color and bottom radio buttons change the text color.");
add(msgChangeColor, BorderLayout.CENTER);
pack();
}
private void createTopPanel()
{
buttonPanel = new JPanel();
setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(new ButtonListener());
redButton.setActionCommand("R");
JButton orangeButton = new JButton("Orange");
orangeButton.setBackground(Color.ORANGE);
orangeButton.addActionListener(new ButtonListener());
orangeButton.setActionCommand("O");
JButton yellowButton = new JButton("Yellow");
yellowButton.setBackground(Color.YELLOW);
yellowButton.addActionListener(new ButtonListener());
yellowButton.setActionCommand("Y");
buttonPanel.add(redButton);
buttonPanel.add(orangeButton);
buttonPanel.add(yellowButton);
}
private void createBottomPanel()
{
radioButtonPanel = new JPanel();
setLayout(new FlowLayout());
JRadioButton greenRadioButton = new JRadioButton("Green");
greenRadioButton.setBackground(Color.GREEN);
greenRadioButton.addActionListener(new RadioButtonListener());
greenRadioButton.setActionCommand("G");
JButton blueRadioButton = new JButton("Blue");
blueRadioButton.setBackground(Color.BLUE);
blueRadioButton.addActionListener(new RadioButtonListener());
blueRadioButton.setActionCommand("B");
JButton cyanRadioButton = new JButton("Cyan");
cyanRadioButton.setBackground(Color.CYAN);
cyanRadioButton.addActionListener(new RadioButtonListener());
cyanRadioButton.setActionCommand("C");
radioButtonPanel.add(greenRadioButton);
radioButtonPanel.add(blueRadioButton);
radioButtonPanel.add(cyanRadioButton);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionColor = e.getActionCommand();
if(actionColor.equals("R"))
{
buttonPanel.setBackground(Color.RED);
radioButtonPanel.setBackground(Color.RED);
}
if(actionColor.equals("O"))
{
buttonPanel.setBackground(Color.ORANGE);
radioButtonPanel.setBackground(Color.ORANGE);
}
if(actionColor.equals("Y"))
{
buttonPanel.setBackground(Color.YELLOW);
radioButtonPanel.setBackground(Color.YELLOW);
}
}
}
private class RadioButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionTextColor = e.getActionCommand();
if(actionTextColor.equals("G"))
{
msgChangeColor.setForeground(Color.GREEN);
}
if(actionTextColor.equals("B"))
{
msgChangeColor.setForeground(Color.BLUE);
}
if(actionTextColor.equals("C"))
{
msgChangeColor.setForeground(Color.CYAN);
}
}
}
public static void main(String[] args)
{
ColorFactory run = new ColorFactory();
run.setVisible(true);
}
}
The problem is you are changing the layout manager for the frame when you create your top and bottom panels...
private void createTopPanel() {
buttonPanel = new JPanel();
setLayout(new FlowLayout()); // <--- This is call setLayout on the frame
This is why it's dangerous to...
Extend from something like JFrame directly...
Dynamically build components
It's all to easy to lose context and start effecting components you didn't actually want to...
Another problem (besides the one posted by MadProgrammer) is that you add your components to the JFrame itself.
You should add content to the content pane of the frame which you can get by calling JFrame.getContentPane().
Example:
JFrame f = new JFrame("Test");
Container c = f.getContentPane();
c.add(new JButton("In Center"), BorderLayout.CENTER);
c.add(new JButton("At the Bottom"), BorderLayout.SOUTH);
c.add(new JButton("At the Top"), BorderLayout.NORTH);
c.add(new JButton("On the Left"), BorderLayout.WEST);
c.add(new JButton("On the Right"), BorderLayout.EAST);
You can set/change the content panel by calling JFrame.setContentPane(). The default content panel already has BorderLayout so you don't even need to change it nor to set a new panel.
I wrote a program to compose a GUI using swing/awt framework for my assignment. So far, I am able to get the pieces working together, but when I put them all into a JFrame, they are not coming out as expected.
I have recently started working on Java GUI framework, and not sure what is missing in my code. How can I get this working properly?
I am also attaching the screen shots (see at the bottom) of the output I am getting.
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
This comes by default on running the code.
This comes after manually resizing the frame.
The combination of BorderLayout , GirdLayout and BoxLayout can do this for you(Actually it's not the only choice).
Here is the code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridLayoutTest {
public void createUI(){
JFrame frame = new JFrame();
JPanel topPanel = new TopPanel();
JPanel buttomPanel = new ButtomPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.CENTER);
mainPanel.add(buttomPanel,BorderLayout.SOUTH);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutTest test = new GridLayoutTest();
test.createUI();
}
#SuppressWarnings("serial")
class TopPanel extends JPanel{
public TopPanel(){
setLayout(new GridLayout(2, 3));
ImageIcon icon = new ImageIcon("capture.png");
JLabel label1 = new JLabel(icon);
label1.setVisible(false);
JLabel label2 = new JLabel(icon);
JLabel label3 = new JLabel(icon);
label3.setVisible(false);
JLabel label4 = new JLabel(icon);
JLabel label5 = new JLabel(icon);
JLabel label6 = new JLabel(icon);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
add(label6);
}
}
#SuppressWarnings("serial")
class ButtomPanel extends JPanel{
public ButtomPanel(){
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
JButton recordButton = new JButton("record");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
}
}
}
BoxLayout is so good too provide white space and help you to center the component.
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
Add Glue before the first component and after the last component will help you too center the component and add strut can help you to provide white space you want. you can refer to https://stackoverflow.com/a/22525005/3378204 for more details.
Here is the effect:
The BoxLayout won't affect your component's size. Hope it can help you.
Try this :
public class Main{
private JFrame f;
private JLabel l1, l2, l3,l4;
private JPanel p1, p2, p3;
private JButton b1, b2, b3;
public Main(){
this.f = new JFrame();
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setLayout(new GridLayout(3,1));
this.p1 = new JPanel();
this.p1.setLayout(null)
this.p1.setSize(yoursize);
this.l1 = new JLabel();
this.l1.setBounds(x,y,xspan,yspan);
this.p1.add(l1);
this.p2 = new JPanel();
this.p2.setLayout(new GridLayout(1,3));
this.l2 = new JLabel();
this.l3 = new JLabel();
this.l4 = new JLabel();
this.p2.add(l2);
this.p2.add(l3);
this.p2.add(l4);
this.p3 = new JPanel();
this.p3.setLayout(new GridLayout(1,3));
this.b1 = new JButton();
this.b2 = new JButton();
this.b3 = new JButton();
this.p3.add(b1);
this.p3.add(b2);
this.p3.add(b3);
this.f.add(p1);
this.f.add(p2);
this.f.add(p3);
this.f.pack();
this.f.setResizeable(false)
}}
Add your video components instead of labels and you can change the color of the components as you wish.
Also if you want more control over the size and position of the components, use null layout and place them individually using setBounds() function as once shown in the program above. It is surely time consuming but makes the layout perfect.