This is my SSCE (though in three seperate classes).
StartUp.java
public class Startup {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MainFrame gui = new MainFrame();
}
});
}
}
MainFrame.java
package gui;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class MainFrame {
private JFrame mainFrame;
private JMenuBar menuBar;
private JMenu menuRoboControl;
private JMenuItem menuItemStart;
private JMenuItem menuItemShutdown;
private JPanel cardPanel;
private final JPanel comListCard = new ComListCard();
public MainFrame() {
initComponents();
}
private void menuItemStartActionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) cardPanel.getLayout();
cardLayout.show(cardPanel, "selectPort");
}
private void menuItemShutdownActionPerformed(ActionEvent e) {
mainFrame.dispose();
System.exit(0);
}
private void initComponents() {
mainFrame = new JFrame();
menuBar = new JMenuBar();
menuRoboControl = new JMenu();
menuItemStart = new JMenuItem();
menuItemShutdown = new JMenuItem();
cardPanel = new JPanel();
//======== mainFrame ========
{
Container mainFrameContentPane = mainFrame.getContentPane();
mainFrameContentPane.setLayout(new BoxLayout(mainFrameContentPane, BoxLayout.X_AXIS));
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//======== menuBar ========
{
//======== menuRoboControl ========
{
menuRoboControl.setText("RoboControl");
//---- menuItemStart ----
menuItemStart.setText("Start Robot");
menuItemStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemStartActionPerformed(e);
}
});
menuRoboControl.add(menuItemStart);
//---- menuItemShutdown ----
menuItemShutdown.setText("Shutdown Robot");
menuItemShutdown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuItemShutdownActionPerformed(e);
}
});
menuRoboControl.add(menuItemShutdown);
}
menuBar.add(menuRoboControl);
}
mainFrame.setJMenuBar(menuBar);
//======== cardPanel ========
{
cardPanel.setLayout(new CardLayout());
cardPanel.add(comListCard, "selectPort");
}
mainFrameContentPane.add(cardPanel);
mainFrame.setSize(835, 635);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
}
}
ComListCard.java
package gui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComListCard extends JPanel {
private JTextArea portInfo;
private JScrollPane scrollPane1;
private JList<String> portList;
private JButton selectPort;
public ComListCard() {
initComponents();
}
public void initComponents() {
portInfo = new JTextArea();
scrollPane1 = new JScrollPane();
portList = new JList<>();
selectPort = new JButton();
//======== comListCard ========
{
this.setLayout(new GridBagLayout());
((GridBagLayout) this.getLayout()).columnWidths = new int[]{298, 214, 0, 0};
((GridBagLayout) this.getLayout()).rowHeights = new int[]{0, 0, 0, 0, 86, 220, 0, 0, 0};
((GridBagLayout) this.getLayout()).columnWeights = new double[]{0.0, 0.0, 1.0, 1.0E-4};
((GridBagLayout) this.getLayout()).rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0E-4};
//---- portInfo ----
portInfo.setText("Select the port connected to your XBee. If you do not know what port it is connected to, check your Device Manager.");
portInfo.setLineWrap(true);
portInfo.setWrapStyleWord(true);
portInfo.setOpaque(false);
portInfo.setEnabled(false);
portInfo.setEditable(false);
portInfo.setBorder(null);
this.add(portInfo, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== scrollPane1 ========
{
//---- portList ----
portList.setModel(new AbstractListModel<String>() {
String[] values = {
"1",
"2",
"3",
"4"
};
#Override
public int getSize() {
return values.length;
}
#Override
public String getElementAt(int i) {
return values[i];
}
});
scrollPane1.setViewportView(portList);
}
this.add(scrollPane1, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- selectPort ----
selectPort.setText("Select");
this.add(selectPort, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
}
}
}
Now some information on the problem. GUI works fine, purely about the CardLayout. As you can see I created a main window with a JPanel inside acting as the holder of the card. I created a card and have added it too to CardLayout. But it already appears from the start of the program while it should only appear after pressing the button (referring to the actionlistener where I put .show(..).
Any help appreciated. Not in a hurry either.
A CardLayout is designed to "hold" multiple cards (panels), but only one card will ever be displayed at a time. The key is that "one" of the panels is always displayed. So the CardLayout is functioning properly.
If you has an application that needs to dynamically display an panel on a frame then you must add the panel at run time. In this case the basic logic would be:
panel.add(...);
panel.revalidate();
panel.repaint();
With the above approach, space is not reserved on the frame for the panel when the frame is initially displayed (so you may also need to pack() the frame to make sure the panel is visible).
If you really want to see an empty space for your card panel when the frame is displayed, then you could simply create a panel with no components added to it and then add this panel to your CardLayout. Then when you invoke the show() method, you will swap in your panel with the components.
Related
I'm trying to make a simple program where there is a text input field and a label, and when you input something to the field it stores the input as "testInput" and changes the label to that text. I'm using Eclipse's Window Builder plugin for this, and it has worked fine before. What happens now is it will take the text in, but wont send it back out to the jLabel. Here is my code:
package interest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestWin {
String testInput;
private JFrame frame;
private JTextField txtTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestWin window = new TestWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestWin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
txtTest = new JTextField();
//Change label when enter is pressed
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
txtTest.setText("test");
GridBagConstraints gbc_txtTest = new GridBagConstraints();
gbc_txtTest.insets = new Insets(0, 0, 5, 0);
gbc_txtTest.fill = GridBagConstraints.HORIZONTAL;
gbc_txtTest.gridx = 5;
gbc_txtTest.gridy = 1;
frame.getContentPane().add(txtTest, gbc_txtTest);
txtTest.setColumns(10);
JLabel lblTest = new JLabel("test");
GridBagConstraints gbc_lblTest = new GridBagConstraints();
gbc_lblTest.gridx = 5;
gbc_lblTest.gridy = 4;
frame.getContentPane().add(lblTest, gbc_lblTest);
}
}
I'm sure I'm making a really simple mistake, so any help is appreciated!
Put
JLabel lblTest = new JLabel("test");
at the begining of initialize() (or anywhere above txtTest.addActionListener...), and then replace
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
txtTest.setText(testInput);
}
});
for
txtTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
testInput = txtTest.getText();
lblTest.setText(testInput); //This line was changed.
}
});
This question already has answers here:
Setting background images in JFrame
(4 answers)
Closed 8 years ago.
I want to add a background image to my frame.But when i add an image to my frame it was added successfully but other things like j label and buttons added on frame afterwords don't appear on frame. i have kept image on Desktop. below is my code
package UI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Color;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.Insets;
public class EditTeamInterface extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EditTeamInterface frame = new EditTeamInterface();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
//frame.getContentPane().setBackground(Color.white);
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Abdullah/Desktop/cricketBackGround1.jpg")))));
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public EditTeamInterface() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 624, 356);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblNewLabel = new JLabel("EDIT OPTIONS");
lblNewLabel.setFont(new Font("SketchFlow Print", Font.BOLD, 18));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
contentPane.add(lblNewLabel, gbc_lblNewLabel);
JButton btnNewButton = new JButton("New button");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.gridx = 5;
gbc_btnNewButton.gridy = 5;
contentPane.add(btnNewButton, gbc_btnNewButton);
}
}
In the EditTeamInterface's constructor, you set the content pane for the frame using setContentPane(contentPane);, but in the static void main, you replace it with
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Abdullah/Desktop/cricketBackGround1.jpg")))));
This discards everything you did before for this new content...
Instead of EditTeamInterface extending from JFrame, change it so that it extends from JPanel
Create a new instance of a JFrame, set the content pane to your label and then add EditTeamInterface to the frame.
Because JLabel has no layout manager by default, you should call setLayout(new BorderLayout()) on the frame after you set it's content pane to the label
While, using a JLabel, this way will work, JLabel will NOT calculate it's preferred size based on the needs of it's contents, but rather based on the properties of the icon and text. This doesn't really make it suitable for this task.
A better solution is to use a custom JPanel and override it's paintComponent to render the image you want. If you're clever, you will make it so that this class is re-usable.
Something like this for example
So using WindowBuilder (latest version of Ecliple, Kepler) I've created a frame as so:
But I'd like to switch between them with a button, which I've created on the panelWelcome.
I'm guessing I'd add an itemListener, then create a method that switches between the cards.
The problem is, I have no idea how to proceed after that. Here's the code that's automatically generated:
package client;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
JPanel panelWelcome = new JPanel();
frame.getContentPane().add(panelWelcome, "name_98933171901972");
GridBagLayout gbl_panelWelcome = new GridBagLayout();
gbl_panelWelcome.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_panelWelcome.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panelWelcome.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panelWelcome.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panelWelcome.setLayout(gbl_panelWelcome);
JLabel lblTitle = new JLabel("MEMEPlayer");
lblTitle.setFont(new Font("Segoe UI", Font.BOLD, 12));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.gridx = 5;
gbc_lblTitle.gridy = 0;
panelWelcome.add(lblTitle, gbc_lblTitle);
JLabel lblNewLabel = new JLabel("Welcome! To get started, select a movie from the drop down menu");
lblNewLabel.setFont(new Font("Segoe UI", Font.PLAIN, 11));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 5;
gbc_lblNewLabel.gridy = 2;
panelWelcome.add(lblNewLabel, gbc_lblNewLabel);
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"The Avengers (2012)", "Monsters, Inc. (2001)", "Prometheus (2012)"}));
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.gridx = 5;
gbc_comboBox.gridy = 4;
panelWelcome.add(comboBox, gbc_comboBox);
JButton btnNewButton = new JButton("Next >");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton.gridx = 5;
gbc_btnNewButton.gridy = 6;
btnNewButton.addItemListener((ItemListener) this);
panelWelcome.add(btnNewButton, gbc_btnNewButton);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setIcon(new ImageIcon("C:\\temp\\Meme1\\largeVLC.png"));
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.gridx = 5;
gbc_lblNewLabel_1.gridy = 8;
panelWelcome.add(lblNewLabel_1, gbc_lblNewLabel_1);
JPanel panelVideo = new JPanel();
frame.getContentPane().add(panelVideo, "name_98968999152440");
}
}
Thanks for any help!
The problem I see you're facing is that you are setting the layout to the frame. This is a problem because it means that the frame can only have on visible component at a time. That component being one of the panels. So you can put a button. The button would have to be on the one of the panels, which may be hard to maintain, in terms of navigation.
So instead, have a main JPanel that has the CardLayout, and add your card panels to that main panel. Then you can add the main panel to the frame, along with buttons for navigation.
Another option is to have a menu bar with option to change the cards, then that way, you can keep the card layout on the frame, because navigation is controlled by the menu options.
See How to Use CardLayout if you're not really sure even how to use CardLayout, hand coding. You're going to need a reference to layout and call one of its navigation methods like show(), next(), or previous()
You may also find this post interesting. It used Netbeans, but maybe you'll pick something up
I had been practicing GridBagLayout from some time, but still I feel confused when I want desired output. I want this kind of output
but i mess up creating one on which table is on one side and the two buttons are on other sides. The table gets squeezed.
Can anybody give me code to align the components (buttons and a table) like this. References for components are
activateServer, addFiles and table
Thanks in advance !
EDIT : this is the code which i am using (Short code for illustrating only prob)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ServerCode extends JFrame
{
ServerCode()
{
JTable table = new JTable(10,3);
JButton addFiles= new JButton("Add files"),activateServer = new JButton("Activate Button");
setLayout(new GridBagLayout());
add(table,new GridBagConstraints(0,0,6,6, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(addFiles,new GridBagConstraints(1,6,2,1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(activateServer,new GridBagConstraints(6,6,2,1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
setSize(700,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String...args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ServerCode();
}
});
}
}
And its output is :
Heck, I'd just use a BorderLayout for this. Forget GridBagLayout if it is not needed. For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class LayoutFoo extends JPanel {
private static final int PREF_W = 800;
public LayoutFoo() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton("Foo"));
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(new JButton("Bar"));
String[] columnNames = {"Mon", "Tues", "Wed"};
DefaultTableModel model = new DefaultTableModel(columnNames, 25);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getViewport().setPreferredSize(table.getPreferredSize());
// scrollPane.getViewport().setPreferredSize(table.getPreferredScrollableViewportSize());
JLabel southLabel = new JLabel("Foobars!");
southLabel.setForeground(Color.white);
JPanel southPanel = new JPanel();
southPanel.setBackground(Color.black);
southPanel.add(southLabel);
setLayout(new BorderLayout(5, 5));
add(buttonPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER );
add(southPanel, BorderLayout.SOUTH);
}
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
int width = PREF_W > superSize.width ? PREF_W : superSize.width;
return new Dimension(width, superSize.height);
}
private static void createAndShowGUI() {
LayoutFoo paintEg = new LayoutFoo();
JFrame frame = new JFrame("Smart File Transfer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If you want to keep the GridBagLayout i believe you need something like this:
add(activateServer,new GridBagConstraints(0,0,1,1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(addFiles,new GridBagConstraints(1,0,1,1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
add(table,new GridBagConstraints(0,1,2,1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0,0));
if you are having problems using the creator of GridBagConstraints you should try using the easier way like in this example
for more info try the oracle documentation
I have a JTextPane sandwiched between 2 JLabels - is there a known reason why the cursor shows through if i have it on the left most part of the textpane but not on the right?
Here is the code to better demonstrate what i mean:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class Testing {
/**
* #param args
*/
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel cp = new JPanel(new BorderLayout());
f.setContentPane(cp);
final SubPanel subPanel = new SubPanel();
cp.add(subPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(new JLabel("Align"));
final JComboBox alignCB = new JComboBox(new String[] {"left", "centre", "right"});
alignCB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
subPanel.align((String) alignCB.getSelectedItem());
}
});
buttonPanel.add(alignCB);
buttonPanel.add(new JLabel("Justify"));
final JComboBox justifyCB = new JComboBox(new String[] {"left", "centre", "right"});
justifyCB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
subPanel.justify((String) justifyCB.getSelectedItem());
}
});
buttonPanel.add(justifyCB);
JTextField tf = new JTextField("TF");
tf.setBorder(null);
buttonPanel.add(tf);
cp.add(buttonPanel, BorderLayout.NORTH);
f.pack();
f.setSize(new Dimension(300,300));
f.setLocation(300, 300);
f.setVisible(true);
}
public static class SubPanel extends JPanel {
JPanel innerPanel = new JPanel(new GridBagLayout());
TextPaneWidget[] tps = new TextPaneWidget[3];
public SubPanel() {
// setBorder(BorderFactory.createLineBorder(Color.RED));
setBorder(null);
// innerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
innerPanel.setBorder(null);
for (int i = 0; i < tps.length; i++) {
tps[i] = new TextPaneWidget();
}
int gridy = 0;
for (TextPaneWidget tp : tps) {
innerPanel.add(tp, new GridBagConstraints(0,gridy, 1,1, 0.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
gridy++;
}
setLayout(new GridBagLayout());
add(innerPanel, new GridBagConstraints(0,0, 1,1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
}
public void align(String alignment) {
System.out.println("Align: " + alignment);
int anchor = GridBagConstraints.CENTER;
if ("right".equals(alignment)) {
anchor = GridBagConstraints.EAST;
} else if ("left".equals(alignment)) {
anchor = GridBagConstraints.WEST;
}
GridBagLayout gbl = (GridBagLayout) getLayout();
gbl.setConstraints(innerPanel, new GridBagConstraints(0,0, 1,1, 1.0, 0.0, anchor, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
revalidate();
repaint();
}
public void justify(String justification) {
System.out.println("Justify: " + justification);
for (TextPaneWidget tp : tps) {
tp.justify(justification);
}
}
}
public static class MyDocument extends DefaultStyledDocument {
#Override
public void insertString(int offset, String text, AttributeSet attributeSet) throws BadLocationException {
SimpleAttributeSet attrs = new SimpleAttributeSet(attributeSet);
StyleConstants.setForeground(attrs, Color.WHITE);
StyleConstants.setBackground(attrs, Color.RED);
super.insertString(offset, text, attrs);
}
}
public static class TextPaneWidget extends JPanel {
JTextPane tp = new JTextPane();
JLabel lSpace = new JLabel(" ");
JLabel rSpace = new JLabel(" ");
public TextPaneWidget() {
// setBorder(BorderFactory.createLineBorder(Color.GREEN));
setBorder(null);
Font font = new Font("monospaced", Font.BOLD, 13);
tp.setBorder(null);
tp.setDocument(new MyDocument());
tp.setFont(font);
tp.setText("Text");
tp.setOpaque(true);
setLayout(new GridBagLayout());
lSpace.setBackground(Color.MAGENTA);
lSpace.setOpaque(true);
lSpace.setBorder(null);
add(lSpace, new GridBagConstraints(0,0, 1,1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
add(tp, new GridBagConstraints(1,0, 1,1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
rSpace.setBackground(Color.MAGENTA);
rSpace.setOpaque(true);
rSpace.setBorder(null);
add(rSpace, new GridBagConstraints(2,0, 1,1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tp.setCaretPosition((e.getX() < tp.getX()) ? 0 : tp.getText().length());
tp.requestFocusInWindow();
}
});
lSpace.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tp.setCaretPosition(0);
tp.requestFocusInWindow();
}
});
rSpace.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tp.setCaretPosition(tp.getText().length());
tp.requestFocusInWindow();
}
});
}
public void justify(String justification) {
double leftWeight = 0.5;
double rightWeight = 0.5;
if ("right".equals(justification)) {
leftWeight = 1.0;
rightWeight = 0.0;
} else if ("left".equals(justification)) {
leftWeight = 0.0;
rightWeight = 1.0;
}
GridBagLayout gbl = (GridBagLayout) getLayout();
gbl.setConstraints(lSpace, new GridBagConstraints(0,0, 1,1, leftWeight, 0.0, GridBagConstraints.EAST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
gbl.setConstraints(rSpace, new GridBagConstraints(2,0, 1,1, rightWeight, 0.0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0,0,0,0), 0, 0));
revalidate();
repaint();
}
}
}
I think I understand what's happening. Thanks for providing the code.
When you define a JTextPane, the default border is a 3 pixel empty border. This empty border provides a place for the text pane cursor to show when the cursor is at the rightmost position. The cursor is at the rightmost position to allow characters to be typed at the end of a line of characters.
When you define a null border, which is the same as a 0 pixel empty border, there's no place for the text pane cursor to be drawn when it's in the rightmost position.
In order to see the cursor in the rightmost position, you have to define an empty border with at least 1 right pixel. If you want it to be more visually appealing, include 1 left pixel.
tp.setBorder(BorderFactory.createEmptyBorder(0,1,0,1));
You have to define an empty border, because an empty border is the only Border that does not paint. A Border that paints will paint over the text pane cursor in the rightmost position.
So, you are required to use an empty border with at least one right pixel for a JTextPane to display the rightmost cursor.
Edited to add:
When you're using the GridBagLayout, a method like this one reduces the number of parameters that you have to deal with when you add a component.
protected void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight,
Insets insets, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
Setting the background to the following fixes this...
tp.setBackground(Color.RED);
tp.setOpaque(true);