JScrollPane not scrolling in a MigLayout - java

In this code I am trying to insert a JScrollPane into my panel which is using the MigLayout.
import java.awt.*;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
public class Simple2
{
JFrame simpleWindow = new JFrame("Simple MCVE");
JPanel simplePanel = new JPanel();
JLabel lblTitle;
JLabel lblSimple;
JTextArea txtSimple;
JScrollPane spSimple;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
public void numberConvertGUI()
{
simpleWindow.setBounds(10, 10, 285, 170);
simpleWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
simpleWindow.setLayout(new GridLayout(1,1));
createSimplePanel();
simpleWindow.getContentPane().add(simplePanel);
simpleWindow.setVisible(true);
simpleWindow.setResizable(false);
}
public void createSimplePanel()
{
MigLayout layout = new MigLayout("" , "[][grow]");
simplePanel.setLayout(layout);
lblTitle = new JLabel();
lblTitle.setText("This is a Title");
simplePanel.add(lblTitle, "wrap, align center,span 2");
lblSimple = new JLabel();
lblSimple.setText("Next to me is a JTextArea: ");
simplePanel.add(lblSimple);
txtSimple = new JTextArea();
txtSimple.setLineWrap(false);
txtSimple.setWrapStyleWord(true);
spSimple = new JScrollPane(txtSimple);
simplePanel.add(txtSimple,"width 100:100:100 , height 100:100:100");
}
public static void main(String[] args)
{
Simple2 s = new Simple2();
s.numberConvertGUI();
}
}
However when the text gets to the end of the JTextArea and continues off the screen there are no scroll bars horizontally or vertically. I am unsure of what I am doing wrong.
With txtSimple.setLineWrap(false);
With txtSimple.setLineWrap(true);
Edit
My desired outcome is to have scroll bars on the scroll pane
The code which provided these samples is
import java.awt.*;
import javax.swing.*;
import java.lang.Object.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.Checkbox;
public class TextAreaSample extends JFrame implements ActionListener
{
JFrame myMainWindow = new JFrame("This is my title");
JTabbedPane myTabs = new JTabbedPane();
JPanel firstPanel = new JPanel(); //a panel for first tab
//first panel components
JTextArea txtSimple;
JLabel lblSimple;
JScrollPane myScrollTable;
JCheckBox TextWrap;
//end first panel
public void runGUI()
{
myMainWindow.setBounds(10, 10, 800, 800); //set position, then dimensions
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel(); //call method to create each panel
myMainWindow.getContentPane().add(firstPanel); //adds the tabbedpane to mainWindow
myMainWindow.setVisible(true); //make the GUI appear
}
public void createFirstPanel()
{
firstPanel.setLayout(null);
txtSimple = new JTextArea();
txtSimple.setLineWrap(false);
txtSimple.setWrapStyleWord(true);
myScrollTable = new JScrollPane(txtSimple);
myScrollTable.setSize(700,700);
myScrollTable.setLocation(20,20);
firstPanel.add(myScrollTable);
System.out.println("Creating compare table");
lblSimple = new JLabel();
lblSimple.setText("Text Wrap");
lblSimple.setSize(100,25);
lblSimple.setLocation(20,730);
lblSimple.setHorizontalAlignment(JLabel.RIGHT);
firstPanel.add(lblSimple);
TextWrap = new JCheckBox();
TextWrap.setLocation(125,730);
TextWrap.setSize(25,25);
TextWrap.addActionListener(this);
firstPanel.add(TextWrap);
}
public void actionPerformed(ActionEvent e)
{
if(TextWrap.isSelected())
{
txtSimple.setLineWrap(true);
}
else
{
txtSimple.setLineWrap(false);
}
}
public static void main(String[] args)
{
TextAreaSample TSA = new TextAreaSample();
TSA.runGUI();
}
}

Here's the issue:
spSimple = new JScrollPane(txtSimple);
simplePanel.add(txtSimple,"width 100:100:100 , height 100:100:100");
You're not adding the JScrollPane to the layout. You need this:
spSimple = new JScrollPane(txtSimple);
simplePanel.add(spSimple,"width 100:100:100 , height 100:100:100");
Notice the use of spSimple in the second line.

Related

How can I add for JPanel show/hide action to the JButton in implemented ActionListener?

I am trying to understand implemented ActionListener. I couldn't find a way out to add it to JButtons in an othor method. I simply trying to add show and hide action to buttons but I could't. Any help? My code is here. There are 3 colored JPanel and every button should hide or show related color JPanel.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class ShowHidePanels implements ActionListener {
public static void main(String[] args) {
new ShowHidePanels();
}
public ShowHidePanels() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1, 2));
frame.add(bluePanel());
frame.add(greenPanel());
frame.add(redPanel());
frame.add(buttonPanel());
frame.setSize(950, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static JPanel greenPanel() {
String greenTitle = "Green Panel";
Border greenBorder = BorderFactory.createTitledBorder(greenTitle);
JPanel greenPanel = new JPanel();
greenPanel.setBorder(greenBorder);
greenPanel.setBackground(new Color(165, 195, 70));
return greenPanel;
}
public static JPanel bluePanel() {
String blueTitle = "Blue Panel";
Border blueBorder = BorderFactory.createTitledBorder(blueTitle);
JPanel bluePanel = new JPanel();
bluePanel.setBorder(blueBorder);
bluePanel.setBackground(new Color(80, 105, 212));
return bluePanel;
}
public static JPanel redPanel() {
String redTitle = "Kirmizi Panel";
Border redBorder = BorderFactory.createTitledBorder(redTitle);
JPanel redPanel = new JPanel();
redPanel.setBorder(redBorder);
redPanel.setBackground(new Color(255, 100, 90));
return redPanel;
}
public static JPanel buttonPanel() {
Border greyBorder = BorderFactory.createTitledBorder("Grey Panel");
JButton b_BlueHide = new JButton("Hide Blue");
JButton b_BlueShow = new JButton("Show Blue");
JButton b_RedHide = new JButton("Hide Red");
JButton b_RedShow = new JButton("Show Red");
JButton b_GreenHide = new JButton("Hide Green");
JButton b_GreenShow = new JButton("Show Green");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBorder(greyBorder);
buttonPanel.setBackground(new Color(200, 200, 200));
buttonPanel.add(b_BlueHide);
buttonPanel.add(b_BlueShow);
buttonPanel.add(b_GreenHide);
buttonPanel.add(b_GreenShow);
buttonPanel.add(b_RedHide);
buttonPanel.add(b_RedShow);
return buttonPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
}
}
static is not your friend. It has its place and purpose, but this is not one of them. Learn to live without it.
Instead, your methods and components should be instance based (that is, obviously, not static and reliant on a instance of the parent class).
The following example is slightly modified and makes use of a CardLayout to switch the panels, which is a lot more fun then trying to handle z-order issues ;)
Take a look at How to Use CardLayout
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel implements ActionListener {
private CardLayout cardLayout;
private JPanel contentPane;
public TestPane() {
cardLayout = new CardLayout();
setLayout(new BorderLayout());
contentPane = new JPanel(cardLayout);
contentPane.add(bluePanel(), "blue");
contentPane.add(greenPanel(), "green");
contentPane.add(redPanel(), "red");
add(contentPane);
add(buttonPanel(), BorderLayout.SOUTH);
}
public JPanel greenPanel() {
String greenTitle = "Green Panel";
Border greenBorder = BorderFactory.createTitledBorder(greenTitle);
JPanel greenPanel = new JPanel();
// Demonstration purposes only -----//
greenPanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
greenPanel.setBorder(greenBorder);
greenPanel.setBackground(new Color(165, 195, 70));
return greenPanel;
}
public JPanel bluePanel() {
String blueTitle = "Blue Panel";
Border blueBorder = BorderFactory.createTitledBorder(blueTitle);
JPanel bluePanel = new JPanel();
// Demonstration purposes only -----//
bluePanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
bluePanel.setBorder(blueBorder);
bluePanel.setBackground(new Color(80, 105, 212));
return bluePanel;
}
public JPanel redPanel() {
String redTitle = "Kirmizi Panel";
Border redBorder = BorderFactory.createTitledBorder(redTitle);
JPanel redPanel = new JPanel();
// Demonstration purposes only -----//
redPanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
redPanel.setBorder(redBorder);
redPanel.setBackground(new Color(255, 100, 90));
return redPanel;
}
public JPanel buttonPanel() {
Border greyBorder = BorderFactory.createTitledBorder("Grey Panel");
JButton blue = new JButton("Blue");
JButton red = new JButton("Red");
JButton green = new JButton("Green");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBorder(greyBorder);
buttonPanel.setBackground(new Color(200, 200, 200));
buttonPanel.add(blue);
buttonPanel.add(green);
buttonPanel.add(red);
blue.addActionListener(this);
green.addActionListener(this);
red.addActionListener(this);
return buttonPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("blue".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "blue");
} else if ("red".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "red");
} else if ("green".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "green");
}
}
}
}
There's a lot of room for simplification and reduction of duplicate workflows, but I'll leave that for you to figure out ;)

Using one button to change the color of multiple JPanels

So i have three panels that i have three different buttons for to change them each to their respective colors. I need to add a fourth button that will return all three panels to their original default light gray color. I add this "reset" button and it only changes the first panel back. What am i doing wrong?
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PanelDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JPanel redPanel;
private JPanel whitePanel;
private JPanel bluePanel;
public static void main(String[] args)
{
PanelDemo gui = new PanelDemo();
gui.setVisible(true);
}
public PanelDemo()
{
super("Panel Demonstration");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new GridLayout(1, 3));
redPanel = new JPanel();
redPanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(redPanel);
whitePanel = new JPanel();
whitePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(whitePanel);
bluePanel = new JPanel();
bluePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(bluePanel);
add(biggerPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.LIGHT_GRAY);
buttonPanel.setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(this);
buttonPanel.add(redButton);
JButton whiteButton = new JButton("White");
whiteButton.setBackground(Color.WHITE);
whiteButton.addActionListener(this);
buttonPanel.add(whiteButton);
JButton blueButton = new JButton("Blue");
blueButton.setBackground(Color.BLUE);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
JButton resetButton = new JButton("Reset");
resetButton.setBackground(Color.LIGHT_GRAY);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
add(buttonPanel, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset"))
redPanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
bluePanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
whitePanel.setBackground(Color.LIGHT_GRAY);
else
System.out.println("Unexpected error.");
}
}
Here was your problem. You had if else's on each panel for the reset. Compare the code below to what you have. It was just a simple logic issue.
public void actionPerformed(ActionEvent e) {
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset")) {
redPanel.setBackground(Color.LIGHT_GRAY);
bluePanel.setBackground(Color.LIGHT_GRAY);
whitePanel.setBackground(Color.LIGHT_GRAY);
}
else
System.out.println("Unexpected error.");
And a couple of suggestions.
Don't extend JFrame. Just use an instance of it. It's better technique.
Put the following as the last statement in your constructor. It will center the panel on your screen.
setLocationRelativeTo(null);
// or when using a frame instance.
frame.setLocationRelativeTo(null);

How to make two colors in one window?

I want to do the same like this:
Here's the code:
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
class QuizGUI {
public static void main(String args[]) {
JFrame frm = new JFrame("Simple Quiz");
frm.setLayout(null);
JLabel lbl1 = new JLabel("Which Animal can fly?");
JLabel lbl2 = new JLabel("You have selected: ");
JLabel lblOutput = new JLabel();
JRadioButton rCat = new JRadioButton("Cat");
JRadioButton rBird = new JRadioButton("Bird");
JRadioButton rFish = new JRadioButton("Fish");
ButtonGroup bg = new ButtonGroup();
bg.add(rCat);
bg.add(rBird);
bg.add(rFish);
lbl1.setBounds(0, 0, 200, 20);
rCat.setBounds(0, 20, 100, 20);
rBird.setBounds(0, 40, 100, 20);
rFish.setBounds(0, 60, 100, 20);
lbl2.setBounds(0, 80, 200, 20);
lblOutput.setBounds(0, 105, 200, 20);
frm.add(lbl1);
frm.add(rCat);
frm.add(rBird);
frm.add(rFish);
frm.add(lbl2);
frm.add(lblOutput);
rCat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rCat.isSelected()) {
lblOutput.setText("Cat can't fly, Try again.");
}
}
});
rBird.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rBird.isSelected()) {
lblOutput.setText("Bird can fly, Excellent.");
}
}
});
rFish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rFish.isSelected()) {
lblOutput.setText("Cat can't fly, Try again.");
}
}
});
frm.setVisible(true);
frm.setSize(350, 200);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The problem is, I want the colors of window like image the background is white and the background for choices is gray.
I tried frame.setBackground but doesn't work.
I tried some codes for another examples and the color was white. I don't know why the window is all gray like this:
From the code you posted in your question:
frm.setLayout(null);
This is not a good idea. I recommend always using a layout manager. JFrame is a top-level container. It has a content pane which, by default, is a JPanel. The default layout manager for the content pane is BorderLayout. You can refer to the source code for JFrame in order to confirm this.
In my opinion BorderLayout is suitable for your GUI. One JPanel is the NORTH component and it displays the question, namely Which Animal can fly?, the radio buttons are the CENTER component and the text You have selected: is the SOUTH panel.
Each JPanel can then have its own background color. I am using JDK 13 on Windows 10 and the default background color is gray. Hence, in the code below, I set the background color for the NORTH and SOUTH panels and leave the CENTER panel with its default background color.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
public class QuizGUI implements ActionListener, Runnable {
private static final String BIRD = "Bird";
private static final String CAT = "Cat";
private static final String FISH = "Fish";
private JFrame frame;
private JLabel resultLabel;
#Override // java.awt.event.ActionListener
public void actionPerformed(ActionEvent event) {
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case BIRD:
resultLabel.setText(BIRD + " can fly. Excellent.");
break;
case CAT:
resultLabel.setText(CAT + " can't fly. Try again.");
break;
case FISH:
resultLabel.setText(FISH + " can't fly. Try again.");
break;
default:
resultLabel.setText(actionCommand + " is not handled.");
}
}
#Override // java.lang.Runnable
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
frame = new JFrame("Simple Quiz");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createQuestionPanel(), BorderLayout.PAGE_START);
frame.add(createChoicesPanel(), BorderLayout.CENTER);
frame.add(createOutcomePanel(), BorderLayout.PAGE_END);
frame.setSize(350, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createRadioButton(String text, ButtonGroup bg, JPanel panel) {
JRadioButton radioButton = new JRadioButton(text);
radioButton.addActionListener(this);
bg.add(radioButton);
panel.add(radioButton);
}
private JPanel createChoicesPanel() {
JPanel choicesPanel = new JPanel(new GridLayout(0, 1));
ButtonGroup bg = new ButtonGroup();
createRadioButton(CAT, bg, choicesPanel);
createRadioButton(BIRD, bg, choicesPanel);
createRadioButton(FISH, bg, choicesPanel);
return choicesPanel;
}
private JPanel createOutcomePanel() {
JPanel outcomePanel = new JPanel(new GridLayout(0, 1, 0, 5));
outcomePanel.setBackground(Color.WHITE);
JLabel promptLabel = new JLabel("You have selected:");
setBoldFont(promptLabel);
outcomePanel.add(promptLabel);
resultLabel = new JLabel(" ");
outcomePanel.add(resultLabel);
return outcomePanel;
}
private JPanel createQuestionPanel() {
JPanel questionPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
questionPanel.setBackground(Color.WHITE);
JLabel questionLabel = new JLabel("Which Animal can fly?");
setBoldFont(questionLabel);
questionPanel.add(questionLabel);
return questionPanel;
}
private void setBoldFont(JLabel label) {
Font boldFont = label.getFont().deriveFont(Font.BOLD);
label.setFont(boldFont);
}
public static void main(String[] args) {
String slaf = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(slaf);
}
catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
UnsupportedLookAndFeelException x) {
System.out.println("WARNING (ignored): Failed to set [system] look-and-feel");
x.printStackTrace();
}
EventQueue.invokeLater(new QuizGUI());
}
}
First create a private JPanel called contentPane in your QuizGUI class. Then in your main method, type:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frm.setContentPane(contentPane);
contentPane.setLayout(null);
then, change all frm.add() with contentPane.add()
I hope this helped!

Set JTextFields and JButtons position in CardLayout

This is a java template i found about Card Layout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main {
private static final String CARD_JBUTTON = "Card JButton";
private static final String CARD_JTEXTFIELD = "Card JTextField";
private static final String CARD_JRADIOBUTTON = "Card JRadioButton";
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Card Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// This JPanel is the base for CardLayout for other JPanels.
final JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(200, 200));
/* Here we be making objects of the Window Series classes
* so that, each one of them can be added to the JPanel
* having CardLayout.
*/
Window1 win1 = new Window1();
contentPane.add(win1, CARD_JBUTTON);
Window2 win2 = new Window2();
contentPane.add(win2, CARD_JTEXTFIELD);
Window3 win3 = new Window3();
contentPane.add(win3, CARD_JRADIOBUTTON);
/* We need two JButtons to go to the next Card
* or come back to the previous Card, as and when
* desired by the User.
*/
JPanel buttonPanel = new JPanel();
final JButton previousButton = new JButton("PREVIOUS");
previousButton.setBackground(Color.BLACK);
previousButton.setForeground(Color.WHITE);
final JButton nextButton = new JButton("NEXT");
nextButton.setBackground(Color.RED);
nextButton.setForeground(Color.WHITE);
buttonPanel.add(previousButton);
buttonPanel.add(nextButton);
/* Adding the ActionListeners to the JButton,
* so that the user can see the next Card or
* come back to the previous Card, as desired.
*/
previousButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.previous(contentPane);
}
});
nextButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
// Adding the contentPane (JPanel) and buttonPanel to JFrame.
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
And this is my Window1.java
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
class Window1 extends JPanel
{
/*
* Here this is our first Card of CardLayout, which will
* be added to the contentPane object of JPanel, which
* has the LayoutManager set to CardLayout.
* This card consists of Two JButtons.
*/
private ActionListener action;
public Window1()
{
init();
}
private void init()
{
final JButton clickButton = new JButton("Click ME");
final JButton dontClickButton = new JButton("DON\'T CLICK ME");
final JTextField title = new JTextField(12);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == clickButton)
{
String myString = title.getText();
System.out.println(myString);
}
else if (ae.getSource() == dontClickButton)
{
JOptionPane.showMessageDialog(null, "I told you not to click me!"
, "Wrong Button", JOptionPane.PLAIN_MESSAGE);
}
}
};
clickButton.addActionListener(action);
dontClickButton.addActionListener(action);
add(clickButton);
add(dontClickButton);
add(title);
}
}
Now my problem is that how do i set the position of the textfields and buttons in Window1?
With this code they are set in the center of the view aligned horizontally.
I tried to use title.setLocation(5,5); but it's not working. Any suggestions?
Now my problem is that how do i set the position of the textfields and buttons in Window1?
Rows like Jlabel - JTextField then new row ,and in the end of the page the button
The thing is you're not using any layout managers. The default layout manager for JPanel is FlowLayout, which will do exactly what you're experiencing (horizontal layout of the components).
Getting vertical alignment could be achieved by using different layout managers. You could use a GridBagLayout for all the component, or a GridLayout, or you could nest JPanel with different layout managers. The possibilities are endless. It just comes down to the exact look you want.
See Laying out Components Within a Container to learn how to use different layout managers. I'll give you an example, but don't let it stop you from looking at the tutorials. You need to learn them.
Also besides just positioning of the components layout managers use dynamic sizing either by respecting the preferred of components are not respecting them. You can see a picture in this answer of some of the layout managers that do and don't respect preferred sizes.
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class LayoutManagers extends JPanel{
public LayoutManagers() {
JLabel label = new JLabel("Text Field");
JTextField textField = new JTextField(20);
JRadioButton rb1 = new JRadioButton("Radio 1");
JRadioButton rb2 = new JRadioButton("Radio 2");
JButton button = new JButton("Button");
JPanel panel1 = new JPanel();
panel1.add(label);
panel1.add(textField);
JPanel panel2 = new JPanel();
panel2.add(rb1);
panel2.add(rb2);
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.TRAILING));
panel3.add(button);
JPanel panel4 = new JPanel(new GridLayout(3, 1));
panel4.add(panel1);
panel4.add(panel2);
panel4.add(panel3);
setLayout(new GridBagLayout());
add(panel4);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new JFrame();
frame.add(new LayoutManagers());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}

JTextPane doesn't display JScrollPane and doesn't Wrap Text

I need to display links so I'm using JTextPane with setContentType. However, the content doesn't wrap and there's no scroll. The content of JTextPane will be returned from a RSS feed. Here's the full code:
import java.awt.*;
import javax.swing.*;
class Main extends JFrame
{
JFrame frame;
JTabbedPane tabbedPane;
JPanel home, news;
public Main()
{
setTitle("My Title" );
setSize( 900, 600 );
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
home();
news();
tabbedPane = new JTabbedPane();
tabbedPane.addTab( " Home", home );
tabbedPane.addTab( "News", news );
JPanel framePanel = new JPanel();
framePanel.setLayout(new BorderLayout());
framePanel.add( tabbedPane, BorderLayout.CENTER );
getContentPane().add( framePanel );
}
public void home()
{
home = new JPanel();
// some stuffs here
}
public void news()
{
news = new JPanel();
JTextPane newsTextPane = new JTextPane();
newsTextPane.setContentType("text/html");
newsTextPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(newsTextPane);
scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
news.add(scrollPane);
RSS reader = RSS .getInstance();
reader.writeNews();
String rssNews = reader.writeNews();
newsTextPane.setText(rssNews);
}
public static void main( String args[] )
{
RSS reader = RSS.getInstance();
reader.writeNews();
Main mainFrame = new Main();
mainFrame.setVisible( true );
mainFrame.setDefaultCloseOperation( EXIT_ON_CLOSE );
}
}
My result:
I just used your code and it does not cause any problems:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities
public class TestScrolling {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initUI();
});
}
public static void initUI() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append("loads loads loads loads of text here ");
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane newsTextPane = new JTextPane();
newsTextPane.setContentType("text/html");
newsTextPane.setEditable(false);
newsTextPane.setText(sb.toString());
JScrollPane scrollPane = new JScrollPane(newsTextPane);
scrollPane.setVerticalScrollBarPolicy(
javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
frame.add(scrollPane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
EDIT:
You have to force somehow the width of the scrollPane. In my example it is done implicitly by adding the scrollpane to the content pane of the frame, which by default uses the BorderLayout. In your case, you used a FlowLayout which allocates the preferred size of the scrollpane which is about the preferred size of the JTextPane.
Are you using a panel or something around your JScrollPane?
Taking the sscc of #Guillaume Polet with innapropriate size the example won't work :
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class TestScrolling {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append("loads loads loads loads of text here ");
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane newsTextPane = new JTextPane();
newsTextPane.setContentType("text/html");
newsTextPane.setEditable(false);
newsTextPane.setText(sb.toString());
JScrollPane scrollPane = new JScrollPane(newsTextPane);
scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
JPanel pan = new JPanel();
pan.setMinimumSize(new Dimension(500,500));
pan.add(scrollPane);
frame.add(pan);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
I see your adding your JscrollPane to panel. Can you provide the creation/modification you made on that panel and where this panel is used?

Categories