Change Swing L&F at command line not work well - java

I made an application with some widgets and at command line I want change their look and feel:
java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel LookAndFeelAppl
but after invoked that command only a widget into the class constructor change its L&F but other that I created into a separate methods don't!!! Also tha JFrame itself not change.
public class LookAndFeelAppl extends JFrame
{
private JLabel label;
private JButton button;
public LookAndFeelAppl()
{
super("Look And Feel Demo");
setLayout(null);
final UIManager.LookAndFeelInfo plaf[] = UIManager.getInstalledLookAndFeels();
JLabel lable_laf = new JLabel("Choose L&F:");
final JComboBox cb = new JComboBox();
createOtherGUI();
cb.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
int ix = cb.getSelectedIndex();
try
{
UIManager.setLookAndFeel(plaf[ix].getClassName());
SwingUtilities.updateComponentTreeUI(LookAndFeelAppl.this);
}
catch (Exception ex)
{
}
}
});
// HERE IS THE PROBLEM!!!! THIS LOOP GOES BEFORE
// THE ITEMLISTENER BECAUSE WHEN I ADD ITEMS AN ITEMEVENT
// IS RAISED THAT SET AGAIN THE L&F WITH setLookAndFeel!!!
for (int i = 0, n = plaf.length; i < n; i++)
{
cb.addItem(plaf[i].getName());
}
//--------------------------------------------------------
add(lable_laf);
add(cb);
lable_laf.setBounds(10, 10, 150, 25);
cb.setBounds(10, 35, 150, 25);
}
public void createOtherGUI()
{
button = new JButton("BUTTON!!!!");
add(button);
button.setBounds(300, 45, 150, 35);
}
public static void main(String args[])
{
LookAndFeelAppl window = new LookAndFeelAppl();
window.setSize(1000, 700);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
}

I ran this in Eclipse (latest version) using JDK 1.6.0_13 on windows. In the run configuration (VM arguments) of Eclipse I used -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel
public class Test extends JFrame {
public Test() {
super("Test L&F");
JComboBox box = new JComboBox(new String[] {"One", "Two", "Three"});
getContentPane().add(box, BorderLayout.SOUTH);
createControls();
setSize(300, 300);
setVisible(true);
}
private void createControls() {
JComboBox box = new JComboBox(new String[] {"One", "Two", "Three"});
getContentPane().add(box, BorderLayout.NORTH);
}
public static void main(String[] args) {
new Test();
}
}
Sorry, formatting is weird but you get the idea...

Few things to try and questions:
I see you are setting the L&F for windows, so I'm assuming you are running this on a windows box? The reason I ask is I'm not sure what the JDK is supporting as far as cross-platform L&Fs, just something to think about.
Did you try other L&Fs with the same result? (e.g. Nimbus)
This may or may not do anything but where do you have main(...)? Try putting it in the JFrame and in a separate class that constructs the JFrame.
Worst comes to worse you could always pass the L&F classname in as an arg to main(...) (or a props file) then use the UIManager to set it BEFORE any swing components are created.
Good luck,
Dave

Related

How can I change the style of the split bar in a JSplitPane?

I am using JSplitPanes for some of my panels, but they are a bit thick, especially when you have a few of them showing.
Is it possible to style these bars into something thinner, like a line with an arrow, or even just a line?
You can use setDividerSize to it in order to change its width. Its default value is 10. Full example:
public class SplitPaneTest extends JFrame {
public SplitPaneTest() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel left = new JPanel();
JPanel right = new JPanel();
JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
System.out.println(sp.getDividerSize()); //Prints 10
sp.setDividerSize(1);
add(sp, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new SplitPaneTest().setVisible(true);
});
}
}
However, Look & Feels are capable of changing the way it looks since they change its UI. If the above solution does not work for you, you will have to mess with its UI. For example, in one of my applications I did not want any line (while using Windows Look and Feel), so in order to make it invisible I had to:
sp.setUI(new BasicSplitPaneUI() {
#Override
public BasicSplitPaneDivider createDefaultDivider() {
return new BasicSplitPaneDivider(this) {
private static final long serialVersionUID = -6000773723083732304L;
#Override
public void paint(Graphics g) {
//Divider gets no painting
}
};
}
});

Create object on Jbutton click

I am trying to create an object when the user presses the button.So far, I've come up with the implementation bellow, but it does not seem to work.I haven't been dealing with Swing and Java UI at all so I am guessing it might be an amateur mistake.
The object I am trying to create is from another type called DebitCard.
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GenerateCard window = new GenerateCard();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GenerateCard() {
}
{
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Generate card");
btnNewButton.setBounds(112, 213, 216, 41);
frame.getContentPane().add(btnNewButton);
}
private class buttonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Generate card")) {
DebitCard a = new DebitCard();
}
}
}
Based on your available code, you seem to have forgotten to register buttonEvent with btnNewButton
btnNewButton.addActionListener(new buttonEvent());
You might want to take a closer look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listener
Laying Out Components Within a Container
Code Conventions for the Java TM Programming Language (this will make your code easier to read and it easier for you to read others)

Moving a JLabel for a game

I am coding a Backgammon game that plays by itself. While the backend code is mostly done, me and my colleague have pretty much no experience in GUI coding. We used the Designer given by a plugin for Eclipse and most of the code was generated.
So here's the thing. Right now there is a JFrame which has a JPanel in which are 2 JLabels, one for the background and one for 1 playing piece (when I figure this out, the rest of them will be added). These are all in an initialize() method which is run through EventQueue.invokeLater(new Runnable()). After the board and the piece are drawn, the startGame() method is called, which finally comes to a method called movePiece(), with the sole purpose of moving that JLabel piece I talked about before.
I have tried mostly everything I can think of, I have scoured the forums and only found people talking about layouts (which I may or may not be using, as I said, generated code) and the darn JLabel won't move when I call setLocation() inside the movePiece() method. It always throws a NullPointerException at that line which is bizarre because the image is already drawn. I will include part of the code below.
I know this will probably look like some of the worse codes ever, but please bear with my lack of skill and help me make this better. Any insights?
public class Main{
public JLabel image1;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
new Main(1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
initialize();
}
public Main(int i){
startGame();
}
public void startGame() {
//game code
movePiece(Move.getPos(), Move.getDest());
//rest of code
}
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 1023, 617);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setPreferredSize(new Dimension(800, 700));
JPanel panel_1 = new JPanel();
panel_1.setPreferredSize(new Dimension(200, 700));
frame.getContentPane().add(panel_1, BorderLayout.EAST);
JButton btnNewButton = new JButton("Start Game");
/* ACTION LISTENER FOR THE BUTTON */
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton.setFocusable(false);
btnNewButton.setForeground(SystemColor.windowBorder);
btnNewButton.setBackground(SystemColor.menu);
btnNewButton.setVerifyInputWhenFocusTarget(false);
btnNewButton.setRequestFocusEnabled(false);
btnNewButton.setRolloverEnabled(false);
btnNewButton.setFont(new Font("Verdana", Font.PLAIN, 11));
btnNewButton.setDebugGraphicsOptions(DebugGraphics.NONE_OPTION);
/* ADDING THE BTN TO PANEL 1 TO THE RIGHT */
panel_1.add(btnNewButton);
JPanel parentPanel = new JPanel();
parentPanel.setFocusable(false);
parentPanel.setEnabled(false);
parentPanel.setDoubleBuffered(false);
parentPanel.setDebugGraphicsOptions(DebugGraphics.NONE_OPTION);
parentPanel.setIgnoreRepaint(true);
parentPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
parentPanel.setBorder(null);
parentPanel.setPreferredSize(new Dimension(800, 700));
parentPanel.setBackground(SystemColor.menu);
frame.getContentPane().add(parentPanel, BorderLayout.WEST);
/* BACKGAMMON BOARD LABEL-->PANEL */
ImageIcon imageIcon = new ImageIcon(
new ImageIcon("images/bg.png").getImage()
.getScaledInstance(800, 551, Image.SCALE_SMOOTH));
parentPanel.setLayout(null);
ImageIcon imageIcon1 = new ImageIcon(
new ImageIcon("images/pl.png").getImage()
.getScaledInstance(50, 50, Image.SCALE_SMOOTH));
image1 = new JLabel("");
image1.setBounds(37, 36, 50, 50);
parentPanel.add(image1);
image1.setIcon(imageIcon1);
JLabel bg = new JLabel("");
bg.setBounds(10, 11, 800, 551);
bg.setIcon(imageIcon);
parentPanel.add(bg);
}
void movePiece(int pos, int dest) {
//null exception happens here, ignore the arguments
image1.setLocation(37 + 50,36);
}
You create an instance of Main and make it visible...
Main window = new Main();
window.frame.setVisible(true);
You then create a new instance of Main, which, through it's constructor, calls your moviePiece method...
new Main(1);
But the new instance of Main has nothing to do with the previous instance or any of the components which they created.
Instead, trying doing...
window.movePiece(Move.getPos(), Move.getDest());
instead of new Main(1);

setDismissDelay to zero for tooltip manager

I set a dismissdelay '0' for a button tooltip. In windows I can't see the tooltip but In linux I am able to see the tooltip. In the java source code of javax.swing.ToolTipManager I did not find any platform dependent info.
Anyone have any idea?
public class TooltipInSwing extends JFrame {
public TooltipInSwing() {
super("TooltipInSwing");
setSize(400, 300);
getContentPane().setLayout(new FlowLayout());
JButton b1 = new JButton("Simple tooltip 1");
b1.setToolTipText("simple tool tip without a dismiss delay" + ToolTipManager.sharedInstance().getInitialDelay());
// set a new dismiss delay to a really big value, default is 4 sec.
ToolTipManager.sharedInstance().setDismissDelay(0);
getContentPane().add(b1);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String args[]) {
new TooltipInSwing();
}
}

unable to create new JLabel with html in method

I am trying to make a fix-width label in Java, which I find a solution here.
But I fail whenever I put any inside a label -- while the label is create inside a method.
my code is here :
public class testingGui
JFrame myframe = new JFrame("Some title here");
Container pane_ctn = myframe.getContentPane();
public static void main(String[] args){
testingGui gui = new testingGui();
gui.init();
}
private void init(){
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setSize(320, 480);
myframe.setVisible(true);
pane_ctn.setLayout(new BoxLayout(pane_ctn, BoxLayout.PAGE_AXIS));
JLabel lable = new JLabel("<html>Java is a general-purpose computer programming language</html>");
pane_ctn.add(lable);
}
}
The line JLabel lable = new JLabel("<html>Java is a general-purpose computer programming language</html>"); will never run. (and making pane_ctn into blank even if there's other UI element added)
However I found that it works while the label is create as a field, like this :
public class testingGui {
JFrame myframe = new JFrame("Some title here");
Container pane_ctn = myframe.getContentPane();
JLabel lable = new JLabel("<html>Java is a general-purpose computer programming language</html>");
// I just cut the whole line and paste here, nothing else has changed.
/* ... */
}
So here is my question :
How is the correct way to create a label with html inside a method call ? I need it created on the fly. Thank you.
Edit :
Thank you ybanen giving me a good answer, and others helpers, too.
Now I can creating Label that looking good.
It happens because you try to modify the GUI after it has been displayed. In your case, the best is to create the whole GUI and then to show the frame:
public class TestingGui {
public static void main(final String[] args) {
final JLabel label = new JLabel("<html>Java is a general-purpose computer programming language</html>");
final JFrame frame = new JFrame("Test");
final Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
frame.getContentPane().add(label);
frame.setSize(320, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
However, if you really need to add the label after the GUI has been displayed, you have to follow several rules:
Any modification of the GUI must be done in the Event Dispatching Thread (EDT).
After a container has been displayed, it has been laid out. So if you want to add a new component inside, you have to force a layout of its content (using revalidate() and then repaint()).
I need it created on the fly.
Why? Or rather, why not create and add the label at start-up, then set the text when needed?
My example is a To-Do list, I have a array to store the data, the label is create inside a for loop.
Use a JList!
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class EditableList {
private JComponent ui = null;
String[] items = {
"Do 100 push ups.",
"Buy a book.",
"Find a cat.",
"Java is a general purpose computer language that is concurrent, "
+ "class based, object oriented and specifically designed to have "
+ "as few implementation dependencies as possible.",
"Conquer the world."
};
EditableList() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JList<String> list = new JList<String>(items);
list.setCellRenderer(new ToDoListRenderer());
list.getSelectionModel().setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
ui.add(new JScrollPane(list));
JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER));
controls.add(new JButton("Edit Selected"));
controls.add(new JButton("Delete Selected"));
ui.add(controls, BorderLayout.PAGE_END);
}
class ToDoListRenderer extends DefaultListCellRenderer {
#Override
public Component getListCellRendererComponent(
JList<? extends Object> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
JLabel l = (JLabel)c;
l.setText("<HTML><body style='width: 250px;'>" + value.toString());
return l;
}
}
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) {
}
EditableList o = new EditableList();
JFrame f = new JFrame("To Do List");
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);
}
}

Categories